Spring MVC入门与数据绑定
文章目录
MVC是一种著名的架构模式
Spring MVC
- Spring MVC是Spring体系的轻量级Web MVC框架
- Spring MVC的核心Controller控制器,用于处理请求,产生响应
- Spring MVC基于Spring IOC容器运行,所有对象被IOC管理
Spring 5.X 版本变化
- Spring 5.x最低要求JDK8与J2EE 7(Servlet 3.1/Tomcat 8.5+)
- Spring 5.x支持JDK8/9,可以使用新特性
- Spring 5.x最重要的新特性支持响应式编程
https://docs.spring.io/spring-framework/docs/current/reference/html/web.html
Spring MVC 环境配置
- Maven依赖spring-webmvc
- web.xml配置DispatcherServlet
- 配置applicationContext的mvc标记
- 开发Controller控制器
Maven依赖spring-webmvc
pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.16.RELEASE</version>
</dependency>
web.xml配置DispatcherServlet
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--DispatchServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<!--
DispatcherServlet是Spring MVC最核心的对象
DispatcherServlet用于拦截Http请求,
并根据请求的URL调用与之对应的controller方法,来完成Http请求的处理
-->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--applicationContext.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!--
在web应用启动时自动创建spring Ioc容器并且初始化DispatcherServlet
如果忘记写也可以运行,但是在第一次访问的时候创建,为了提高效率建议在web程序启动但时候创建
-->
<load-on-startup>0</load-on-startup>
</servlet>
<!--映射-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--"/"代表拦截所有请求-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
配置applicationContext的mvc标记
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--
context:component-scan 标签作用
在Spring IOC初始化过程中,自动创建并且管理springmvc及子包中
拥有以下注解对象
@Repository 通常使用这个的类都是与数据发生直接交互的类
@Service 业务逻辑类,通常放在xxxService
@Controller 控制器类 Spring控制器
@Component 不好区分类型使用这个
-->
<context:component-scan base-package="springmvc"/>
<!--启用Spring MVC注解开发模式-->
<mvc:annotation-driven/>
<!--将图片/js/css等静态资源排除在外,可提高执行效率-->
<mvc:default-servlet-handler/>
</beans>
完成上面3条配置Spring MVC就配置完成了,开发一个Controller测试一下。
开发Controller控制器
package springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller// Spring mvc控制器
// 这个类的根本作用处理http的请求并且返回相应
public class TestController {
//绑定Get方法
@GetMapping("/t")//localhost/t
// 直接向响应输出字符串数据,不跳转页面
@ResponseBody
public String test() {
return "Hello Spring MVC";
}
}
部署运行,记得将引用的jar添加到lib
在浏览器直接输入代码中配置的地址即可访问到http://localhost:8080/t
显示出结果:Hello Spring MVC
使用Spring MVC框架可以快速的完成web请求的处理,而不是像之前使用servlet的繁琐配置。
可以把TestController看成原有servlet的替代品,在开发的过程中编写方法上对应的注解,而不需要引入servlet那样的请求/响应对象,就可以完成原本复杂的请求以及web处理了。
Spring MVC处理示意图
Spring MVC数据绑定
URL映射
URL Mapping
- URL Mapping指将URL与Controller方法绑定
- 通过将URL与方法绑定,SpringMVC便可通过Tomcat对外暴露服务
URL Mapping注解
- @RequestMapping - 通用绑定
- @GetMapping - 绑定Get请求
- @PostMapping - 绑定Post请求
案例:GetMapping和PostMapping
URLMappingController
package springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class URLMappingController {
@GetMapping("/g")
@ResponseBody
public String getMapping(String managerName) {
return "this is get test1";
}
@PostMapping("/p")
@ResponseBody
public String postMapping() {
return "this is post";
}
}
get请求在浏览器中输入地址可以直接访问, 而post请求需要提交表单访问,index页面:增加一个映射到post请求地址的表单提交
<form action="/p" method="post">
<input type="submit" value="提交">
</form>
案例:通过RequestMapping可一次性为所有get请求和post请求url增加设定的前缀
URLMappingController
package springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/um")
public class URLMappingController {
@GetMapping("/g")
@ResponseBody
public String getMapping(String managerName) {
return "this is get test1";
}
@PostMapping("/p")
@ResponseBody
public String postMapping() {
return "this is post";
}
}
RequestMapping同样可作用在方法上,使其不再区分get/post请求(不推荐,每个方法的职责建议明确)
@RequestMapping("/g")//作用在方法上,不再区分get/post请求
@ResponseBody
public String getMapping(String managerName) {
return "this is get test1";
}
可使用这种方式指定get请求方式,作用跟@GetMapping(“/g”)一样
@RequestMapping(value = "/g", method = RequestMethod.GET)
Controller方法参数 - 接收请求参数
- 使用Controller方法参数接收
- 使用Java Bean接收数据
Controller方法参数接收数据
Post方式
index表单
<form action="/um/p" method="post">
<input name="username"><br>
<input name="password"><br>
<input type="submit" value="提交">
</form>
URLMappingController 对应的post方法
@PostMapping("/p")
@ResponseBody
public String postMapping(String username, String password) {
System.out.println(username + ":" + password);
return "this is post";
}
spring会自动尝试类型转换接收参数,当输入不正确的类型时就会报出400错误,所以在前台要进行严谨的表单校验。
Get方式
在URL中参数名为manager_name,而在java代码中这种命名不符合javaBean的规范,可以使用@RequestParam注解将指定的参数显示的注入到注解后面的参数变量中。
访问:http://localhost:8080/um/g?manager_name=lili
@GetMapping("/g")
@ResponseBody
public String getMapping(@RequestParam("manager_name") String managerName) {
System.out.println("manager_name is" + managerName);
return "this is get test1";
}
使用Java Bean接收请求参数
创建相应的实体类 符合Java Bean规范
User
package springmvc.entity;
public class User {
private String username;
private String password;
//get/set方法
}
URLMappingController 增加post方法
@PostMapping("/p1")
@ResponseBody
public String postMapping1(User user) {
System.out.println(user.getUsername() + ":" + user.getPassword());
return "this is post";
}
index映射修改成新的p1即可
使用该方式同样要求请求参数和User的属性名保持一致
如果在方法参数增加username参数,数据依然可以成功注入,由此可以验证不管参数存在多少,只要参数名符合规则,或者参数对象的数据名符合规则,就可以成功完成注入。
public String postMapping1(User user, String username)
接收表单复合数据
综合训练:学员调查问卷
知识点
- 利用数组或者List接收请求中的复合数据
- 利用@RequestParam为参数设置默认值
- 使用Map对象接收请求参数及注意事项
URI绝对路径与相对路径
相对路径的应用案例
form.html 表单页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div style="text-align:center" class="container">
<h2>问卷调查</h2>
<form action="./apply" method="post">
<h3>姓名:</h3>
<input name="name" class="text" style="">
<h3>您正在学习的技术方向</h3>
<select name="course" style="">
<option value="java">java</option>
<option value="h5">h5</option>
<option value="python">python</option>
<option value="php">php</option>
</select>
<div>
<h3>您学习目的是?</h3>
<input type="checkbox" name="purpose" value="1">就业找工作
<input type="checkbox" name="purpose" value="2">工作要求
<input type="checkbox" name="purpose" value="3">兴趣爱好
<input type="checkbox" name="purpose" value="4">其他
</div>
<div style="margin-top: 20px">
<input type="submit" value="提交">
</div>
</form>
</div>
</body>
</html>
springmvc.controller.FormController
使用数组接收复合数据
package springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class FormController {
@PostMapping("/apply")
@ResponseBody
//@RequestParam(value = "name", defaultValue = "ANON" 添加默认值
public String apply(@RequestParam(value = "name", defaultValue = "ANON") String name, String course, Integer[] purpose) {
System.out.println("name:" + name);
System.out.println("course:" + course);
for (Integer p : purpose) {
System.out.println(p);
}
return "SUCCESS";
}
}
使用List接收复合数据
@PostMapping("/apply")
@ResponseBody
public String apply(String name, String course,@RequestParam List<Integer> purpose) {
System.out.println("name:" + name);
System.out.println("course:" + course);
for (Integer p : purpose) {
System.out.println(p);
}
return "SUCCESS";
}
使用对象接收复合数据
新建一个实体类,属性对应前台数据
Form
package springmvc.entity;
import java.util.List;
public class Form {
private String name;
private String course;
private List<Integer> purpose;
//get/set方法
}
springmvc.controller.FormController
@PostMapping("/apply")
@ResponseBody
public String apply(Form form) {
System.out.println(form.getName());
return "SUCCESS";
}
使用Map - 无法接收复合数据
注意:Map只会把数组中第一个数据进行返回。
如果表单不包含复合数据可以使用Map接收,否则会造成数据丢失。
springmvc.controller.FormController
@PostMapping("/apply")
@ResponseBody
public String apply(@RequestParam Map map) {
System.out.println(map);
return "SUCCESS";
}
关联对象赋值
案例:
复杂内容表单,可以创建一个对象包含所有属性,然后通过Spring MVC自动对其进行赋值,但是这样做并不好,因为从分组上看上面上用户登陆信息,下面上身份证信息,按照面向对象设计方式对表单进行接收要创建两个类。
像这样创建两个对象就要设计到关联对象的赋值。
回到刚刚的学员问卷调查案例,要为填写问卷的人发放奖励,增加物流信息。
在表单中增加三个输入项;注意增加了快递类型对象的前缀
<h3>收货人</h3>
<input name="delivery.name" class="text" style="width: 150px">
<h3>联系电话</h3>
<input name="delivery.mobile" class="text" style="width: 150px">
<h3>收货地址</h3>
<input name="delivery.address" class="text" style="width: 150px">
增加快递信息类
Delivery
package springmvc.entity;
public class Delivery {
private String name;
private String address;
private String mobile;
//get/set方法
}
在原有Form类中增加Delivery对象;必须对对象属性实例化才能赋值成功。
package springmvc.entity;
import java.util.List;
public class Form {
private String name;
private String course;
private List<Integer> purpose;
private Delivery delivery = new Delivery();
//get/set方法
}
springmvc.controller.FormController
@PostMapping("/apply")
@ResponseBody
public String applyDelivery(Form form) {
System.out.println(form.getDelivery().getName());
return "SUCCESS";
}
日期类型转换
使用注解进行转换
回到最开始的post接收请求参数案例,增加日期项
<form action="/um/p" method="post">
<input name="username"><br>
<input name="password"><br>
<input name="createTime"><br>
<input type="submit" value="提交">
</form>
URLMappingController 增加DateTimeFormat对应格式的注解
package springmvc.controller;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springmvc.entity.User;
import java.util.Date;
@Controller
@RequestMapping("/um")
public class URLMappingController {
@PostMapping("/p")
@ResponseBody
public String postMapping(String username, String password, @DateTimeFormat(pattern = "yyyy-MM-dd") Date createTime) {
System.out.println(username + ":" + password);
return "this is post";
}
}
使用对象的方式接收数据在类中属性上增加注解
User实体类
package springmvc.entity;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
public class User {
private String username;
private String password;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date createTime;
//get/set方法
}
URLMappingController
package springmvc.controller;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springmvc.entity.User;
import java.util.Date;
@Controller
@RequestMapping("/um")
public class URLMappingController {
@PostMapping("/p")
@ResponseBody
public String postMapping1(User user) {
System.out.println(user.getUsername() + ":" + user.getPassword());
return "this is post";
}
}
设置全局默认时间格式
增加自定义日期转换类
MyDateConverter
package springmvc.converter;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyDateConverter implements Converter<String, Date> {
public Date convert(String s) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d = sdf.parse(s);
return d;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
}
applicationContext.xml 增加格式转换bean的配置,并在mvc:annotation-driven中定义服务使其生效
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="springmvc.converter.MyDateConverter"/>
</set>
</property>
</bean>
URLMappingController 测试,不使用DateTimeFormat注解也可以完成转换
@PostMapping("/p")
@ResponseBody
public String postMapping(String username, String password, Date createTime) {
System.out.println(username + ":" + password);
return "this is post";
}
在Spring MVC中,如果DateTimeFormat和全局模式时间格式都设置了,则以全局默认时间格式优先,如果存在不同的时间格式,则在MyDateConverter自定义的日期转换类中根据传人字符串的长度等进行多个if判断即可。
解决中文乱码
Web应用的中文乱码由来
- Tomcat默认使用字符集IS0-8859-1,属于西欧字符集
- 解决乱码的核心思路是将ISO-8859-1转换为UTF-8
- Controller中请求与响应都需要设置UTF-8字符集
中文乱码的配置
-
Get请求乱码– server.xml增加URIEncoding属性 (Tomcat 8.0以后版本默认就是UTF-8)
-
Post请求乱码– web.xml配置CharacterEncodingFilter过滤器
-
Response响应乱码– Spring配置配置文件中StringHttpMessageConverter消息转换器
解决请求中的中午乱吗
GET请求中文乱码问题
注意:8.0版本以后tomcat默认配置了UTF-8可以不做修改
需要配置tomcat的server.xml文件
打开tomcat安装路径找到server.xml文件
找到Connector在最后增加属性URIEncoding=“UTF-8”,8.0之后可以不加默认就是UTF-8
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8"/>
POST请求中文乱码问题
web.xml 增加过滤器的配置
<filter>
<filter-name>characterFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
解决响应中的中文乱码
Spring配置文件中配置StringHttpMessageConverter消息转换器
applicationContext.xml
<!--启用Spring MVC注解开发模式-->
<mvc:annotation-driven conversion-service="conversionService">
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<!--之前servlet中是这样设置的:response.setContentType=("text/html;charset=utf-8")-->
<value>text/html;charset=utf-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
响应输出结果
@ResponseBody - 产生响应文本
- @ResponseBody直接产生响应体的数据,过程不涉及任何视图
- @ResponseBody可产生标准字符串/JSON/XML等格式数据
- @ResponseBody被StringHttpMessageConverter影响
ModelAndView - 利用模板引擎渲染输出
- ModelAndView对象是指"模型(数据)与视图(界面)"对象
- 通过ModelAndView可将包含数据对象与模板引擎进行绑定
- SpringMVC中默认的View是JSP,也可以配置其他模板引擎
ModelAndView案例:
URLMappingController
@RequestMapping("/um")
public class URLMappingController {
//......
@GetMapping("/view")
public ModelAndView showView(Integer userId) {
// 如果不加/代表相对路径,相对路径要包含指定的url前缀,也就是/um/view.jsp路径
ModelAndView mav = new ModelAndView("/view.jsp");
// mav.setViewName("/view.jsp"); //效果和上边一样
User user = new User();
if (userId == 1) {
user.setUsername("lily");
} else if (userId == 2) {
user.setUsername("smith");
} else if (userId == 3) {
user.setUsername("lina");
}
mav.addObject("u", user);
return mav;
}
view.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>I'm a view</h1>
<hr>
<h2>Username:${u.username}</h2>
</body>
</html>
访问http://localhost:8080/um/view?userId=1根据请求参数显示内容
ModelAndView对象核心用法
- mav.addObject()方法设置的属性默认存放在当前请求中
- 默认ModelAndView使用请求转发(forward)至页面
- 重定向使用new ModelAndView(“redirect:/index.jsp”)
页面重定向,增加redirect
此时访问http://localhost:8080/um/view?userId=1时就会被转到http://localhost:8080/view.jsp,而请求的数据也会丢失。
ModelAndView mav = new ModelAndView("redirect:/view.jsp");
当跳转的页面和当前controller处理关系不紧密的时候可以使用redirect重定向,比如注册完成回到首页
String与ModelMap方式实现
如果增加ResponseBody,则访问http://localhost:8080/um/view?userId=1会将"/view.jsp"字符串显示在浏览器中
如果去掉ResponseBody,则代表Spring MVC会将ModelMap中的数据和view.jsp组合渲染生成html后,返回网页的html显示
ModelMap对象并不是必须的,可以不增加ModelMap,返回view字符串,因为在很多场景下我们并不需要为要跳转的页面赋值数据
通常ModelMap对象都会附加到所有参数最后的位置
//String与ModelMap
//Controller方法返回String的情况
//1.方法被@ResponseBody描述,SpringMVC直接响应string字符串本身
//2.方法不存在@ResponseBody,则SpringMVc处理string指代的视图(页面)
@GetMapping("/view")
// @ResponseBody
public String showView1(Integer userId, ModelMap modelMap) {
String view = "/view.jsp";
User user = new User();
if (userId == 1) {
user.setUsername("lily");
} else if (userId == 2) {
user.setUsername("smith");
} else if (userId == 3) {
user.setUsername("lina");
}
modelMap.addAttribute("u", user);
return view;
}
Spring MVC整合Freemarker
Spring MVC默认使用jsp作为模版引擎
整合步骤分3步:
pom.xml 引入依赖freemarker和spring上下文的支持包
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.2.16.RELEASE</version>
</dependency>
启用Freemarker模版引擎
applicationContext.xml
<!-- 启动Freemarker模板引擎 -->
<bean id="ViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<!--产生结果以后向客户端输出内容的时候,以哪种字符集来显示响应文本-->
<property name="contentType" value="text/html;charset=utf-8"/>
<!--指定Freemarker模版文件扩展名-->
<property name="suffix" value=".ftl"/>
</bean>
配置Freemarker参数
applicationContext.xml
<!-- 配置Freemarker参数 -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<!--设置模板保存的目录-->
<property name="templateLoaderPath" value="/WEB-INF/ftl"/>
<!--其他模版引擎设置-->
<property name="freemarkerSettings">
<props>
<!--设置Freemarker脚本与数据渲染时使用的字符集-->
<prop key="defaultEncoding">UTF-8</prop>
</props>
</property>
</bean>
测试:
新建FreemarkerController
package springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import springmvc.entity.User;
@Controller
@RequestMapping("/fm")
public class FreemarkerController {
@GetMapping("/test")
public ModelAndView showTest() {
//之前配置好了.ftl后缀和/ftl跟路径,所以直接写test文件名即可
ModelAndView mav = new ModelAndView("/test");
User user = new User();
user.setUsername("andy");
mav.addObject("u", user);
return mav;
}
}
WEB-INF下新建之前配置的ftl目录,新建test.ftl文件
<h1>${u.username}</h1>
注意,pom.xml引入的包还需要在tomcat配置中增加
访问http://localhost:8080/fm/test即可显示定义好的username,“andy”
加粗样式