Servlet 基础
Servlet是JavaWeb的核心组件,是运行在服务器端的Java程序,用于处理客户端请求并生成响应。
Servlet 生命周期
Servlet的生命周期包含三个阶段:
- 初始化阶段:调用
init()方法,只执行一次 - 服务阶段:调用
service()方法,每次请求都会执行 - 销毁阶段:调用
destroy()方法,服务器关闭时执行
Servlet 示例代码
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello, Servlet!</h1>");
out.println("</body></html>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>欢迎, " + username + "!</h1>");
out.println("</body></html>");
}
}
JSP 技术
JSP(JavaServer Pages)是一种动态网页技术,允许在HTML中嵌入Java代码。
JSP 内置对象
request:请求对象response:响应对象session:会话对象application:应用程序对象out:输出对象pageContext:页面上下文对象config:配置对象page:页面对象exception:异常对象
JSP 示例
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>JSP 示例</title>
</head>
<body>
<h1>欢迎访问 JSP 页面</h1>
<%-- 脚本片段 --%>
<%
String username = request.getParameter("username");
if (username != null) {
%>
<p>你好, <%= username %>!</p>
<%
} else {
%>
<p>请输入用户名</p>
<%
}
%>
<%-- JSP 表达式 --%>
<p>当前时间: <%= new java.util.Date() %></p>
<form action="" method="post">
用户名: <input type="text" name="username">
<input type="submit" value="提交">
</form>
</body>
</html>
Spring Boot 框架
Spring Boot是Spring框架的快速开发脚手架,简化了Spring应用的创建和部署。
Spring Boot 核心特性
- 自动配置(Auto Configuration)
- 嵌入式服务器(Tomcat、Jetty、Undertow)
- 起步依赖(Starter Dependencies)
- Actuator监控
- 无代码生成和XML配置
Spring Boot 入门示例
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
@SpringBootApplication
@RestController
@RequestMapping("/api")
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
@GetMapping("/hello")
public String hello(@RequestParam(required = false, defaultValue = "World") String name) {
return "Hello, " + name + "!";
}
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return new User(id, "张三", 25);
}
@PostMapping("/users")
public User createUser(@RequestBody User user) {
System.out.println("创建用户: " + user.getName());
return user;
}
static class User {
private Long id;
private String name;
private Integer age;
public User(Long id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Long getId() { return id; }
public String getName() { return name; }
public Integer getAge() { return age; }
}
}
application.yml 配置
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/example_db
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.demo.entity
logging:
level:
com.example.demo: DEBUG
RESTful API 设计
REST(Representational State Transfer)是一种软件架构风格,用于设计Web服务。
RESTful 设计原则
- 使用HTTP方法表示操作:GET(查询)、POST(创建)、PUT(更新)、DELETE(删除)
- 使用URI表示资源
- 无状态通信
- 统一接口
- 支持多种数据格式(JSON、XML)
RESTful API 示例
| HTTP方法 | URI | 描述 |
|---|---|---|
| GET | /api/users | 获取所有用户 |
| GET | /api/users/{id} | 获取指定用户 |
| POST | /api/users | 创建新用户 |
| PUT | /api/users/{id} | 更新用户信息 |
| DELETE | /api/users/{id} | 删除用户 |
总结
JavaWeb开发是企业级应用的主流技术栈,掌握Servlet、JSP和Spring Boot是Java后端开发的基本功。Spring Boot凭借其自动配置和快速开发特性,已经成为现代JavaWeb开发的首选框架。