SpringMVC
Spring MVC 是 Spring 框架的一部分,专为构建 Web 应用程序而设计。遵循模型-视图-控制器(MVC)架构模式,这种模式有助于将应用程序的输入逻辑、业务逻辑和UI逻辑分离。
- 模型(Model):表示应用程序的数据和业务逻辑,通常由 JavaBean 或 POJO(Plain Old Java Object)实现。
- 视图(View):负责展示数据给用户,可以是 JSP、HTML、XML、JSON 等任何形式。
- 控制器(Controller):处理用户的请求,并返回相应的模型和视图信息。
引入依赖包
<properties><spring.version>4.0.2.RELEASE</spring.version>
</properties>
...
<dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${spring.version}</version>
</dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version>
</dependency>
<!-- JSON依赖 -->
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.4.3</version>
</dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.4.3</version>
</dependency>
扫包并开启注解
<!--自动扫描的包名,只扫描@Controller -->
<context:component-scan base-package="com.hz.controller" >
<!--开启注解-->
<mvc:annotation-driven/>
在 web.xml
中配置前端控制器 DispatcherServlet
<!-- 配置前端控制器 -->
<servlet><servlet-name>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- 初始化参数 加载 spring 配置文件 --><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-*.xml</param-value></init-param><!-- 启动时加载 --><load-on-startup>1</load-on-startup>
</servlet><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><url-pattern>/</url-pattern>
</servlet-mapping>
常用注解
@Controller
:标注一个普通的JavaBean成为可以处理请求的控制器。
@RequestMapping
:通过请求URL进行映射。
-
method
@GetMapping
:用于处理 GET 请求。相当于@RequestMapping(method = RequestMethod.GET)
-
@PostMapping
:用于处理 POST 请求。相当于@RequestMapping(method = RequestMethod.POST)
public enum RequestMethod {GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;private RequestMethod() {}
}
@Controller
public class IndexController {@RequestMapping(value="/user", method = RequestMethod.GET)// 相当于 @GetMapping("/user")public ModelAndView index() {// 设置要跳转的页面 默认转发ModelAndView modelAndView = new ModelAndView("/index.jsp");return modelAndView;}
}
- params
{"param1=value1", "param2", "!param3"}
表示请求必须满足以下条件- 包含名为
param1
的参数,且其值必须是value1
;包含名为param2
的参数;不能包含名为param3
的参数。
@RequestParam
:提取请求中的查询参数或表单参数。
value
:指定请求参数的名称(若参数名称与方法参数名称相同,可省略)required
:参数是否必需(默认为true
)defaultValue
:指定默认值(required
为false
时才有效)
@RequestMapping(value = "/user", method = RequestMethod.GET, params = { "userId=123", "token", "!invalidParam" })
public ModelAndView getUser(@RequestParam("userId") String userId, @RequestParam("token") String token) {ModelAndView modelAndView = new ModelAndView();modelAndView.addObject("message", "User ID: " + userId + ", Token: " + token);modelAndView.setViewName("/user.jsp");return modelAndView;
}
@RequestParam("userId")
和@RequestParam("token")
注解用于从请求中提取userId
和token
参数的值。
// 有效请求http://localhost:8080/user?userId=123&token=abc123
// 无效请求
// userId 的值不是 123http://localhost:8080/user?userId=456&token=abc123
// 缺少 token 参数http://localhost:8080/user?userId=123
// 包含 invalidParam 参数http://localhost:8080/user?userId=123&token=abc123&invalidParam=something
@RequestParam
还可以用于处理数组和集合类型的参数。
@GetMapping("/users")
public ModelAndView getUsers(@RequestParam("userIds") String[] userIds) {}
@GetMapping("/users")
public ModelAndView getUsers(@RequestParam("userIds") List<String> userIds) {}
通过实体类接收参数
传入参数名必须与实体类对应,一般用于添加,修改类中多个属性时
public class User {private String userName;private String email;// 默认构造器public User() {}// 带参数的构造器public User(String userName, String email) {this.userName = userName;this.email = email;}// Getter 和 Setter 方法...// 重写 toString 方法@Overridepublic String toString() {return "User{" +"userName='" + userName + '\'' +", email='" + email + '\'' + '}';
}}
@Controller
public class UserController {@RequestMapping(value = "/user", method = RequestMethod.GET)public String index1(User user) {System.out.println("userName: " + user.getUserName());System.out.println("email: " + user.getEmail());System.out.println("toString: " + user.toString());return "/user.jsp";}
}
// 有效请求
http://localhost:8080/user?userName=张三&email=zhangsan@example.com