Spring MVC是目前主流的实现MVC设计模式的企业级开发框架,是Spring 框架的子模块,无需整合
新建maven工程,选择webapp,配置pom,xml
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.7.RELEASEversion>
dependency>
dependencies>
在web,xml中配置DispatcherServlet
<web-app>
<display-name>Archetype Created Web Applicationdisplay-name>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name> contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
在resources中新建springmvc.xml,并配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<context:component-scan base-package="com.lin">context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/">property>
<property name="suffix" value=".jsp">property>
bean>
beans>
测试handler类
@Controller
public class HelloHandler {
@RequestMapping("/hello")
public String hello(){
System.out.println("Hello World");
// 调转到hello.jsp中
return "hello";
}
}
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/html;charset=UTF-8">property>
bean>
mvc:message-converters>
mvc:annotation-driven>
在web.xml中配置
<servlet-mapping>
<servlet-name>defaultservlet-name>
<url-pattern>*.cssurl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>defaultservlet-name>
<url-pattern>*.jsurl-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>defaultservlet-name>
<url-pattern>*.jpgurl-pattern>
servlet-mapping>
完成映射,类型转换等工作都由HandlerAdapter完成
@Controller :在类定义处添加,将该类交给IoC容器(在xml文件中配置自动扫描),称为一个控制器,可以接收请求
@ResponseBody :在方法处添加,会直接将业务方法的返回值响应给客户端
@RestController :在类定义出添加,相当于@Controller+@ResponseBody,表示直接将业务方法返回值交给客户端,不进行视图解析
@RequestMapping :在类定义处或方法处添加,将URL与业务方法进行映射
@RequestParam :在参数列表中添加,将http请求参数与业务方法形参绑定。相同名称则不需要添加
@RequestMapping(value = "/a",params = {"name=a"})
public String hello1(String name){
return name;
}
@RequestMapping(value = "/b",params = {"name=b"})
public String hello2(@RequestParam("name") String age){
return age;
}
上述传统URL:http://localhost:8080/hello?name=abc
REST:http://localhost:8080/hello/abc
@RequestMapping("/hello/{name}")
public String rest(@PathVariable("name") String name){
System.out.println(name);
return "hello";
}
@PathVariable :在参数列表处添加,完成URL与参数的映射
可以直接在业务方法中获取Cookie的值
@RequestMapping("/cookie")
public String cookie(@CookieValue(value = "JSESSIONID") String sessionId){
System.out.println(sessionId);
return "hello";
}
会根据请求参数名和 JavaBean 属性名进行自动匹配,自动为对象填充属性值,同时支持级联属性。
@RequestMapping("/login")
public String post(Person person){
System.out.println(person);
return "login";
}
@Data
public class Person {
private String name;
private Number number;
}
@Data
public class Number {
private String telNumber;
}
<body>
<form action="/login">
<input name="name">
<input name="number.telNumber">
<input type="submit" value="提交">
</form>
</body>
默认为转发
return "forward:/login.jsp";
// 等价于
return "login";
重定向
return "redirect:/login.jsp";
http://localhost:8080/array?list=a&list=b&list=c
@RequestMapping("/array")
@ResponseBody
public String array(String[] list){
String s = Arrays.toString(list);
return s;
}
Spring MVC 不支持 List 类型的直接转换,需要对 List 集合进行包装。(无法对对象赋值,只能对属性赋值)
@RequestMapping("/list")
public String test1(UserList list) {
StringBuffer stringBuffer = new StringBuffer();
for (Person person : list.getList()) {
stringBuffer.append(person);
}
return stringBuffer.toString();
}
@Data
public class UserList {
List<Person> list;
}
@Data
public class Person {
private String name;
private Number number;
}
@Data
public class Number {
private String telNumber;
}
<body>
<form action="/list">
<input name="list[0].name">
<input name="list[0].number.telNumber">
<input name="list[1].name">
<input name="list[1].number.telNumber">
<input type="submit" value="提交">
</form>
</body>
与List集合同理
@RequestMapping("/map")
public String test2(UserMap userMap){
StringBuffer stringBuffer = new StringBuffer();
for (String key:userMap.getMap().keySet()){
Person value = userMap.getMap().get(key);
stringBuffer.append(value);
}
return stringBuffer.toString();
}
<body>
<form action="/map">
<input name="map['a'].name">
<input name="map['a'].number.telNumber">
<input name="map['b'].name">
<input name="map['b'].number.telNumber">
<input type="submit" value="提交">
</form>
</body>
客户端发送 JSON 格式的数据,直接通过 Spring MVC 绑定到业务方法的形参中。
配置web,xml,使其支持静态资源
配置pom,xml导入包
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.68version>
dependency>
在springmvc.xml中配置json
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
controller
@RequestMapping("/json")
public Person json(@RequestBody Person user){
System.out.println(user);
user.setName("修改后");
return user;
}
jsp
<head>
<title>Title</title>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function(){
var user = {
"name":"修改前",
};
$.ajax({
url:"/json",
data:JSON.stringify(user),
type:"POST",
contentType:"application/json;charset=UTF-8",
dataType:"JSON",
success:function(data){
alert(data.name);
}
})
});
</script>
</head>
数据转换:将Http请求中的参数转换为业务方法中定义的形参,HandlerAdapter已经提供了一些通用的转换(Stirng转int,表单数据封装等),但特殊业务需要用户自定义转换器
public class DateConverter implements Converter<String, Date> {
private String pattern;
public DateConverter(String pattern) {
this.pattern = pattern;
}
@Override
public Date convert(String s) {
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date date = null;
try {
date = format.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.lin.converter.DateConverter">
<constructor-arg value="yyyy-MM-dd">constructor-arg>
bean>
list>
property>
bean>
<mvc:annotation-driven conversion-service="conversionService">
@RestController
public class ConverterHandler {
@RequestMapping("convert")
public String converter(Date date){
return date.toString();
}
}
与表单封装不一样,这里是在一个框中输入类似“15+张三+30”(使用+分隔)
public class PeopleConverter implements Converter<String, People> {
@Override
public People convert(String s) {
String[] split = s.split("\\+");
People people = new People();
people.setId(Integer.parseInt(split[0]));
people.setName(split[1]);
people.setAge(Integer.parseInt(split[2]));
return people;
}
}
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.lin.converter.DateConverter">
<constructor-arg value="yyyy-MM-dd">constructor-arg>
bean>
<bean class="com.lin.converter.PeopleConverter">bean>
list>
property>
bean>
<mvc:annotation-driven conversion-service="conversionService">
@RequestMapping("/convert1")
public String converter(People people){
return people.toString();
}