@WebServlet("/api/hello")
public class HelloApi extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("application/json;charset=UTF-8");
resp.getWriter().write("{\"message\":\"Hello, Frontend!\"}");
}
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
@Valid + Bean Validation)@ControllerAdvice)java -jar 即可執行// fetch API
fetch('/api/users/1')
.then(r => r.json())
.then(data => console.log(data));
// axios
axios.post('/api/users', {name: 'Alice', email: 'alice@example.com'})
.then(res => console.log(res.data));
| 項目 | 建議 |
|---|---|
| CORS | @CrossOrigin 或 WebMvcConfigurer 全域配置 |
| 安全 | Spring Security + JWT/OAuth2 |
| 文件 | Springdoc OpenAPI (Swagger UI) |
| 監控 | Actuator + Prometheus/Grafana |
入門用 Servlet 理解本質;實務專案直接上 Spring Boot,專注業務邏輯而非基礎設施。前端視後端為標準 HTTP+JSON 服務,雙端解耦並行開發。