Java 之 SpringMVC(一篇文章精通系列)
[](()(5)配置注解

package cn.itbluebox.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class QuickController {
@RequestMapping("/quick")
public String quickMethod(){
System.out.println("quickMethod running.....");
return "index.jsp";
}
}
[](()(6)创建 spring-mvc.xml


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="cn.itbluebox"/>
</beans>
[](()(7)在 web.xml 配置 SpringMVC 的核心控制器

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.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>
</web-app>
[](()(8)引入 Tomcat 插件

<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>8090</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
运行测试






[http://localhost:8090/quick](()


[](()(9)配置视图解析器
视图解释器,不设置后缀直接跳转

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>

package cn.itbluebox.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class QuickController {
@RequestMapping("/quick")
public String quickMethod(){
System.out.println("quickMethod running.....");
return "index";
}
}
运行

[http://localhost:8090/quick](()


[](()3、SpringMVC 流程图示

[](()4、知识要点
SpringMVC 的开发步骤
导入 SpringMVC 相关坐标
配置 SpringMVC 核心控制器 DispathcerServlet
创建 Controller 类和视图页面
使用注解配置 Controller 类中业务方法的映射地址
配置 SpringMVC 核心文件 spring-mvc.xml
客户端发起请求测试
[](()二、SpringMVC 组件解析
[](()1、SpringMVC 的执行流程

用户发送请求至前端控制器 DispatcherServlet。
DispatcherServlet 收到请求调用 HandlerMapping 处理器映射器。
处理器映射器找到具体的处理器(可以根据 xml 配置、注解进行查找),生成处理器对象及处理器拦截器(如果有则生成)一并返回给 DispatcherServlet。
DispatcherServlet 调用 HandlerAdapter 处理器适配器。
HandlerAdapter 经过适配调用具体的处理器(Controller,也叫后端控制器)。
Controller 执行完成返回 ModelAndView。
HandlerAdapter 将 controller 执行结果 ModelAndView 返回给 DispatcherServlet。
DispatcherServlet 将 ModelAndView 传给 ViewReslover 视图解析器。
ViewReslover 解析后返回具体 View。
DispatcherServlet 根据 View 进行渲染视图(即将模型数据填充至视图中)。
DispatcherServlet 响应用户。
[](()2、SpringMVC 组件解析
前端控制器:DispatcherServlet
用户请求到达前端控制器,它就相当于 MVC 模式中的 C,
DispatcherServlet 是整个流程控制的中心,由
它调用其它组件处理用户的请求,
DispatcherServlet 的存在降低了组件之间的耦合性。
处理器映射器:HandlerMapping
HandlerMapping 负责根据用户请求找到 Handler 即处理器,
SpringMVC 提供了不同的映射器实现不同的
映射方式,例如:配置文件方式,实现接口方式,注解方式等。
处理器适配器:HandlerAdapter
通过 HandlerAdapter 对处理器进行执行,这是适配器模式的应用,
通过扩展适配器可以对更多类型的处理器进行执行。
处理器:Handler
它就是我们开发中要编写的具体业务控制器。
由 DispatcherServlet 把用户请求转发到 Handler。由 Handler 对具体的用户请求进行处理。
视图解析器:View Resolver
View Resolver 负责将处理结果生成 View 视图,
View Resolver 首先根据逻辑视图名解析成物理视图名,即具体的页面地址,再生成 View 视图对象,
最后对 View 进行渲染将处理结果通过页面展示给用户。
视图:View
SpringMVC 框架提供了很多的 View 视图类型的支持,包括:jstlView、freemarkerView、pdfView 等。最常用的视图就是 jsp。
一般情况下需要通过页面标签或页面模版技术将模型数据通过页面展示给用户,
需要由程序员根据业务需求开发具体的页面
[](()3、SpringMVC 注解解析
@RequestMapping
作用:用于建立请求 URL 和处理请求方法之间的对应关系
位置:类上,请求 URL 的第一级访问目录。
此处不写的话,就相当于应用的根目录
方法上,请求 URL 的第二级访问目录,
与类上的使用 @ReqquestMapping 标注的一级目录一起组成访问虚拟路径
属性:
value
:用于指定请求的 URL。它和 path 属性的作用是一样的
method
:用于指定请求的方式
params
:用于指定限制请求参数的条件。它支持简单的表达式。
要求请求参数的 key 和 value 必须和配置的一模一样
例如:
params = {"accountName"}
,表示请求参数必须有 accountName
params = {"moeny!100"}
,表示请求参数中 money 不能是 100
[](()(1)mvc 命名空间引入
命名空间:
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
约束地址:
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.xsd
[](()(2)组件扫描
SpringMVC 基于 Spring 容器,所以在进行 SpringMVC 操作时,
需要将 Controller 存储到 Spring 容器中,
如果使用@Controller
注解标注的话,就需要使用
<context:component-scan base-package=“cn.itbluebox.controller"/>
进行组件扫描。
[](()4、SpringMVC 的 XML 配置解析
视图解析器
SpringMVC 有默认组件配置,默认组件都是 DispatcherServlet.properties 配置文件中配置的,该配置文件地址 org/springframework/web/servlet/DispatcherServlet.properties,该文件中配置了默认的视图解析器,如下:
org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver
翻看该解析器源码,可以看到该解析器的默认设置,如下:
REDIRECT_URL_PREFIX = "redirect:" --重定向前缀
FORWARD_URL_PREFIX = "forward:" --转发前缀(默认值)
prefix = ""; --视图名称前缀
suffix = ""; --视图名称后缀
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
[](()5、知识要点
SpringMVC 的相关组件
前端控制器:
DispatcherServlet
处理器映射器:
HandlerMapping
处理器适配器:
HandlerAdapter
处理器:
Handler
视图解析器:
View Resolver
视图:
View
SpringMVC 的注解和配置
请求映射注解:@RequestMapping
视图解析器配置:
REDIRECT_URL_PREFIX = "redirect:"
FORWARD_URL_PREFIX = "forward:"
prefix = "";
suffix = "";
[](()三、SpringMVC 的数据响应
[](()1、SpringMVC 的数据响应方式
1) 页面跳转
直接返回字符串
通过 ModelAndView 对象返回
2) 回写数据
直接返回字符串
返回对象或集合
[](()2、页面跳转
Forward(请求转发)
Redirect(重定向)
[](()(1)返回字符串形式
直接返回字符串:
此种方式会将返回的字符串与视图解析器的前后缀拼接后跳转。

返回带有前缀的字符串:
转发:
forward:/WEB-INF/views/index.jsp
重定向:
redirect:/index.jsp
[](()(2)创建 JSP 页面


<%--
Created by IntelliJ IDEA.
User: ZHENG
Date: 2021/9/14
Time: 14:27
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>views 下的 index.jsp</h1>
${name}
</body>
</html>
完善 webapp 下的 index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>Hello SpringMVC!</h2>
${name}
</body>
</html>
[](()(3)返回 ModelAndView 对象(在刚刚的 QuickController 当中写如下接口接口)
Redirect(重定向)
@RequestMapping("/quick002")
public ModelAndView quickMethod2() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("redirect:index.jsp");
return modelAndView;
}
[http://localhost:8090/quick002](()

Forward(请求转发)
@RequestMapping("/quick003")
public ModelAndView quickMethod3() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("forward:/WEB-INF/views/index.jsp");
return modelAndView;
}
[http://localhost:8090/quick003](()

[](()(4)向 request 域存储数据(在刚刚的 QuickController 当中写如下接口接口)
在进行转发时,往往要向 request 域中存储数据,
在 jsp 页面中显示,那么 Controller 中怎样向 request 域中存储数据呢?
通过 SpringMVC 框架注入的
request
对象setAttribute()
方法设置
@RequestMapping("/quick004")
public String quickMethod4(HttpServletRequest request) {
request.setAttribute("name", "zhangsan");
return "index";
}
[http://localhost:8090/quick004](()

通过 ModelAndView 的
addObject()
方法设置
@RequestMapping("/quick005")
public ModelAndView quickMethod5() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("forward:/WEB-INF/views/index.jsp");
modelAndView.addObject("name", "list");
return modelAndView;
}
[http://localhost:8090/quick005](()

[](()3、回写数据
[](()(1)直接返回字符串
Web 基础阶段,客户端访问服务器端,
如果想直接回写字符串作为响应体返回的话,只需要使用
response.getWriter().print(“hello world”)
即可,
那么在 Controller 中想直接回写字符串该怎样呢?
通过
SpringMVC
框架注入的response
对象,
使用response.getWriter().print(“hello world”)
回写数据,
此时不需要视图跳转,业务方法返回值为 void。
@RequestMapping("/quick006")
public void quickMethod6(HttpServletResponse response)
throws IOException {
response.getWriter().print("hello world");
}
[http://localhost:8090/quick006](()

将需要回写的字符串直接返回,但此时需要通过
@ResponseBody
注解告知SpringMVC
框架,
方法返回的字符串不是跳转是直接在 http 响应体中返回。
@RequestMapping("/quick007")
@ResponseBody
public String quickMethod7() throws IOException{
return "hello springMVC!!!";
}
[http://localhost:8090/quick007](()

在异步项目中,客户端与服务器端往往要进行 json 格式字符串交互,
此时我们可以手动拼接 json 字符串返回。
@RequestMapping("/quick008")
@ResponseBody
public String quickMethod8() throws IOException {
return "{"name":"zhangsan","age":18}";
}
[http://localhost:8090/quick008](()

[](()(2)返回字符串(JSON)格式
引入依赖
上述方式手动拼接 json 格式字符串的方式很麻烦,
开发中往往要将复杂的 java 对象转换成 json 格式的字符串,
我们可以使用 web 阶段学习过的 json 转换工具 jackson 进行转换,导入 jackson 坐标。

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
创建 User 对象


package cn.itbluebox.pojo;
public class User {
private String name;
private Integer age;
public User() {
}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + ''' +
", age=" + age +
'}';
}
}
QuickController 当中创建 quickMethod9 方法

@RequestMapping("/quick009")
@ResponseBody
public String quickMethod9() throws IOException{
User user = new User();
user.setName("zhangsan");
user.setAge(18);
ObjectMapper objectMapper = new ObjectMapper();
String s = objectMapper.writeValueAsString(user);
return s;
}

[http://localhost:8090/quick009](()

[](()(3)返回对象或集合
通过 SpringMVC 帮助我们对对象或集合进行 json 字符串的转换并回写,
为处理器适配器配置消息转换参数,指定使用 jackson 进行对象或集合的转换,
《一线大厂 Java 面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】
因此需要在
spring-mvc.xml 中进行如下配置:

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
</list>
</property>
</bean>
返回 User 对象

@RequestMapping("/quick010")
@ResponseBody
public User quickMethod10() throws IOException{
User user = new User();
user.setName("lisi");
user.setAge(19);
return user;
}


返回 User 对象的集合

@RequestMapping("/quick011")
@ResponseBody
public ArrayList<User> quickMethod11() throws IOException{
ArrayList<User> users = new ArrayList<User>();
User user1 = new User("zhangsan",19);
User user2 = new User("lisi",29);
User user3 = new User("wangyu",39);
User user4 = new User("zhaoliu",29);
User user5 = new User("zhangzhan",39);
users.add(user1);
users.add(user2);
users.add(user3);
users.add(user4);
users.add(user5);
return users;
}

[](()(4)返回对象或者集合(简化配置)
在方法上添加 @ResponseBody 就可以返回 json 格式的字符串,但是这样配置比较麻烦,配置的代码比较多,因此,我们可以使用 mvc 的注解驱动代替上述配置。
在 SpringMVC 的各个组件中,处理器映射器、处理器适配器、
视图解析器称为 SpringMVC 的三大组件。
使用<mvc:annotation-driven>
自动加载 RequestMappingHandlerMapping
(处理映射器)
和
RequestMappingHandlerAdapter
( 处 理 适 配 器 ),
可用在Spring-xml.xml
配置文件中使用
<mvc:annotation-driven>
替代注解处理器和适配器的配置。
同时使用<mvc:annotation-driven>
默认底层就会集成 jackson 进行对象或集合的 json 格式字符串的转换。



[http://localhost:8090/quick011](()

[](()(5)SpringMVC 的数据响应方式
1) 页面跳转
直接返回字符串
通过 ModelAndView 对象返回
2) 回写数据
直接返回字符串
返回对象或集合
[](()四、SpringMVC 获得请求数据
[](()1、获得请求参数
客户端请求参数的格式是:name=value&name=value… …
服务器端要获得请求的参数,有时还需要进行数据的封装,
SpringMVC 可以接收如下类型的
参数:
基本类型参数
POJO 类型参数
数组类型参数
集合类型参数
Controller 中的业务方法的参数名称要与请求参数的 name 一致,参数值会自动映射匹配。

@RequestMapping("/quick012")
@ResponseBody
public void quickMethod12(String name,int age) throws IOException{
System.out.println(name);
System.out.println(age);
}
[http://localhost:8090/quick012?name=lisi&age=19](()


[](()2、获得 POJO 类型参数
Controller 中的业务方法的 POJO 参数的属性名与请求参数的 name 一致,参数值会自动映射匹配。

@RequestMapping("/quick013")
@ResponseBody
public void quickMethod13(User user) throws IOException{
System.out.println(user);
}

[http://localhost:8090/quick013?name=lisi&age=19](()


[](()3、获得数组类型参数
Controller 中的业务方法数组名称与请求参数的 name 一致,参数值会自动映射匹配。

@RequestMapping("/quick014")
@ResponseBody
public void quickMethod14(String[] strs) throws IOException{
System.out.println(Arrays.asList(strs));
}

[http://localhost:8090/quick014?strs=111&strs=222&strs=333](()


[](()4、获得集合类型参数
获得集合参数时,要将集合参数包装到一个 POJO 中才可以。
[](()(1)创建 Vo 对象

package cn.itbluebox.pojo;
import java.util.ArrayList;
public class Vo {
private ArrayList<User> userList;
public Vo() {
}
public Vo(ArrayList<User> userList) {
this.userList = userList;
}
public ArrayList<User> getUserList() {
return userList;
}
public void setUserList(ArrayList<User> userList) {
this.userList = userList;
}
@Override
public String toString() {
return "Vo{" +
"userList=" + userList +
'}';
}
}
[](()(2)在 QuickController 当中创建 quickMethod15 方法

@RequestMapping("/quick015")
@ResponseBody
public void quickMethod15(Vo vo) throws IOException{
System.out.println(vo.getUserList());
}
[](()(3)创建 login.jsp


<%--
Created by IntelliJ IDEA.
User: ZHENG
Date: 2021/9/14
Time: 15:36
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/quick015" method="post">
name:<input type="text" name="userList[0].name" ><br>
age:<input type="text" name="userList[0].age" ><br>
name:<input type="text" name="userList[1].name" ><br>
age:<input type="text" name="userList[1].age" ><br>
name:<input type="text" name="userList[3].name" ><br>
age:<input type="text" name="userList[3].age" ><br>
<input type="submit" value="提交"><br>
</form>
</body>
</html>


[](()5、获得集合类型参数(Ajax 提交)
当使用 ajax 提交时,可以指定 contentType 为 json 形式,
那么在方法参数位置使用
@RequestBody
可以直接接收集合数据而无需使用 POJO 进行包装。
[](()(1)引入 jquery-3.3.1.js,并创建 login.html


创建 ajax.html 页面

<html>
<head>
<title>Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="js/jquery-3.3.1.js"></script>
<script>
var userList = new Array();
userList.push({name:"zhangsan",age:18});
userList.push({name:"lisi",age:28});
$.ajax({
type:"POST",
url:"/quick016",
data:JSON.stringify(userList),
contentType:"application/json;charset=utf-8"
});
</script>
</head>
<body>
</body>
</html>
[](()(2)修改 web.xml
因为默认的配置 DispatcherServlet 屏蔽了 html 页面的访问,你需要加上如下:

<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
[](()(3)修改 spring-mvc.xml
注意:通过谷歌开发者工具抓包发现,没有加载到 jquery 文件,原因是 SpringMVC 的前端控制器 DispatcherServlet 的 url-pattern 配置的是/,代表对所有的资源都进行过滤操作,我们可以通过以下两种方式指定放行静态资源:
在
spring-mvc.xml
配置文件中指定放行的资源
使用
<mvc:default-servlet-handler/>
标签

[](()(4)在 QuickController 创建 quickMethod16 方法
当使用 ajax 提交时,可以指定 contentType 为 json 形式,那么在方法参数位置使用
@RequestBody
可以直接接收集合数据而无需使用 POJO 进行包装。

@RequestMapping("/quick016")
@ResponseBody
public void quickMethod16(@RequestBody List<User> userList) throws IOException{
System.out.println(userList);
}
[](()(5)运行测试



[](()(6)请求数据乱码问题
修改 ajax.html

刷新页面

当 post 请求时,数据会出现乱码,我们可以设置一个过滤器来进行编码的过滤。修改 web.xml

<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
从新运行

[http://localhost:8090/ajax.html](()
刷新页面


[](()6、参数绑定
[](()(1)参数绑定注解 @requestParam
[](()1)当请求的参数名称与 Controller 的业务方法参数名称不一致时,就需要通过
@RequestParam
注解显示的绑定。
创建 login2.jsp


<%--
Created by IntelliJ IDEA.
User: ZHENG
Date: 2021/9/14
Time: 16:55
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/quick017" method="post" >
<input type="text" name="name" ><br>
<input type="submit" value="提交" ><br>
</form>
</body>
</html>
在 QuickController 当中创建 quickMethod17 方法

评论