SSM03 —— 集成Web,SpringMVC

概述:本文记录了Spring与Web环境的集成与SpringMVC的简介和组件解析

Spring集成Web环境

ApplicationContext应用上下文获取方式

应用上下文对象是通过new ClasspathXmlApplicationContext(spring配置文件) 方式获取的,但是每次从容器中获得Bean时都要编写new ClasspathXmlApplicationContext(spring配置文件) ,这样的弊端是配置文件加载多次,应用上下文对象创建多次。

在Web项目中,可以使用ServletContextListener监听Web应用的启动,我们可以在Web应用启动时,就加载Spring的配置文件,创建应用上下文对象ApplicationContext,在将其存储到最大的域servletContext域中,这样就可以在任意位置从域中获得应用上下文ApplicationContext对象了。

Spring提供获取应用上下文的工具

上面的分析不用手动实现,Spring提供了一个监听器ContextLoaderListener就是对上述功能的封装,该监听器内部加载Spring配置文件,创建应用上下文对象,并存储到ServletContext域中,提供了一个客户端工具WebApplicationContextUtils供使用者获得应用上下文对象。
所以我们需要做的只有两件事:

  • 在web.xml中配置ContextLoaderListener监听器(导入spring-web坐标)
  • 使用WebApplicationContextUtils获得应用上下文对象ApplicationContext

导入Spring集成Web的坐标

1
2
3
4
5
<dependency> 
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>

配置ContextLoaderListener监听器

web.xml中:

1
2
3
4
5
6
7
8
9
10
11
<!--全局参数--> 
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--Spring的监听器-->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
通过工具获得应用上下文对象
1
2
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
Object obj = applicationContext.getBean("id");

SpringMVC简介

概述

SpringMVC 是一种基于 Java 的实现 MVC 设计模型的请求驱动类型的轻量级 Web 框架,属于SpringFrameWork 的后续产品,已经融合在 Spring Web Flow 中。

SpringMVC 已经成为目前最主流的MVC框架之一,并且随着Spring3.0 的发布,全面超越 Struts2,成为最优秀的 MVC 框架。它通过一套注解,让一个简单的 Java 类成为处理请求的控制器,而无须实现任何接口。同时它还支持 RESTful 编程风格的请求。

开发步骤

需求:客户端发起请求,服务器端接收请求,执行逻辑并进行视图跳转

步骤:

  • 导入SpringMVC相关坐标

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <!--Spring坐标--> 
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.5.RELEASE</version>
    </dependency>
    <!--SpringMVC坐标-->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.0.5.RELEASE</version>
    </dependency>
    <!--Servlet坐标-->
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    </dependency>
    <!--Jsp坐标-->
    <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.0</version>
    </dependency>
  • 配置SpringMVC核心控制器DispathcerServlet (web.xml中)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <!--配置SpringMVC的前端控制器-->
    <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>
  • 创建Controller类和视图页面

    1
    2
    3
    4
    5
    6
    public class UserController {
    public String save(){
    System.out.println("Controller save running....");
    return "success";
    }
    }

    视图页面xxx.jsp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>Title</title>
    </head>
    <body>
    <h1>Success!</h1>
    </body>
    </html>
  • 使用注解配置Controller类中业务方法的映射地址

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @Controller
    @RequestMapping("/user")
    public class UserController {

    // 请求地址 http://localhost:8080/user/quick
    @RequestMapping(value="/quick",method = RequestMethod.GET,params = {"username"})
    public String save(){
    System.out.println("Controller save running....");
    return "success";
    }
    }
  • 配置SpringMVC核心文件 spring-mvc.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    <?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.alibaba.com/schema/stat"
    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.alibaba.com/schema/stat http://www.alibaba.com/schema/stat.xsd">

    <!--Controller的组件扫描-->
    <context:component-scan base-package="com.itheima">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--配置内部资源视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!-- /jsp/success.jsp -->
    <property name="prefix" value="/jsp/"></property>
    <property name="suffix" value=".jsp"></property>
    </bean>
    </beans>
  • 客户端发起请求测试

SpringMVC流程图示

SpringMVC组件解析

执行流程

  1. 用户发送请求至前端控制器DispatcherServlet。
  2. DispatcherServlet收到请求调用HandlerMapping处理器映射器。
  3. 处理器映射器找到具体的处理器(可以根据xml配置、注解进行查找),生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。
  4. DispatcherServlet调用HandlerAdapter处理器适配器。
  5. HandlerAdapter经过适配调用具体的处理器(Controller,也叫后端控制器)。
  6. Controller执行完成返回ModelAndView。
  7. HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet。
  8. DispatcherServlet将ModelAndView传给ViewReslover视图解析器。
  9. ViewReslover解析后返回具体View。
  10. DispatcherServlet根据View进行渲染视图(即将模型数据填充至视图中)。DispatcherServlet响应用户。

SpringMVC组件解析

  1. 前端控制器:DispatcherServlet

用户请求到达前端控制器,它就相当于 MVC 模式中的 C,DispatcherServlet 是整个流程控制的中心,由它调用其它组件处理用户的请求,DispatcherServlet 的存在降低了组件之间的耦合性。

  1. 处理器映射器:HandlerMapping

HandlerMapping 负责根据用户请求找到 Handler 即处理器,SpringMVC 提供了不同的映射器实现不同的映射方式,例如:配置文件方式,实现接口方式,注解方式等。

  1. 处理器适配器:HandlerAdapter

通过 HandlerAdapter 对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理器进行执行。

  1. 处理器:Handler

它就是我们开发中要编写的具体业务控制器。由 DispatcherServlet 把用户请求转发到 Handler。由Handler 对具体的用户请求进行处理。

  1. 视图解析器:View Resolver
    View Resolver 负责将处理结果生成 View 视图,View Resolver 首先根据逻辑视图名解析成物理视图名,即具体的页面地址,再生成 View 视图对象,最后对 View 进行渲染将处理结果通过页面展示给用户。

  2. 视图:View
    SpringMVC 框架提供了很多的 View 视图类型的支持,包括:jstlView、freemarkerView、pdfView等。最常用的视图就是 jsp。一般情况下需要通过页面标签或页面模版技术将模型数据通过页面展示给用户,需要由程序员根据业务需求开发具体的页面

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="com.itheima.controller"/>进行组件扫描。

SpringMVC的XML配置解析

视图解析器
SpringMVC有默认组件配置,默认组件都是DispatcherServlet.properties配置文件中配置的,该配置文件地址org/springframework/web/servlet/DispatcherServlet.properties,该文件中配置了默认的视图解析器,如下:

1
org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver

翻看该解析器源码,可以看到该解析器的默认设置,如下:

1
2
3
4
REDIRECT_URL_PREFIX = "redirect:" --重定向前缀
FORWARD_URL_PREFIX = "forward:" --转发前缀(默认值)
prefix = ""; --视图名称前缀
suffix = ""; --视图名称后缀

我们可以通过属性注入的方式修改视图的的前后缀

1
2
3
4
5
<!--配置内部资源视图解析器--> 
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

SpringMVC的数据响应

数据响应方式1:页面跳转

  • 直接返回字符串

    此种方式会将返回的字符串与视图解析器的前后缀拼接后跳转

    返回带有前缀的字符串:

    转发:forward:/WEB-INF/views/index.jsp

    重定向:redirect:/index.jsp

    1
    2
    3
    4
    5
    6
    7
    //原始的形式
    // 请求地址 http://localhost:8080/user/quick
    @RequestMapping(value="/quick")
    public String save(){
    System.out.println("Controller save running....");
    return "success";//这里返回的字符串
    }
  • 通过ModelAndView对象返回

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    @RequestMapping(value="/quick2")
    public ModelAndView save2(){
    /*
    Model:模型 作用封装数据
    View:视图 作用展示数据
    */
    ModelAndView modelAndView = new ModelAndView();
    //设置模型数据
    modelAndView.addObject("username","itcast");
    //设置视图名称
    modelAndView.setViewName("success");

    return modelAndView;
    }

    @RequestMapping(value="/quick3")
    public ModelAndView save3(ModelAndView modelAndView){
    modelAndView.addObject("username","itheima");
    modelAndView.setViewName("success");
    return modelAndView;
    }

    @RequestMapping(value="/quick4")
    public String save4(Model model){
    model.addAttribute("username","博学谷");
    return "success";
    }
  • 向request域存储数据

    在进行转发时,往往要向request域中存储数据,在jsp页面中显示,那么Controller中怎样向request域中存储数据呢?

    (1)通过SpringMVC框架注入的request对象setAttribute()方法设置

    1
    2
    3
    4
    5
    @RequestMapping(value="/quick5")
    public String save5(HttpServletRequest request){
    request.setAttribute("username","酷丁鱼");
    return "success";
    }

    (2)通过ModelAndView的addObject()方法设置

    1
    2
    3
    4
    5
    6
    @RequestMapping(value="/quick3")
    public ModelAndView save3(ModelAndView modelAndView){
    modelAndView.addObject("username","itheima");
    modelAndView.setViewName("success");
    return modelAndView;
    }

数据响应方式2:回写数据

  • 直接返回字符串

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

    1
    2
    3
    4
    @RequestMapping(value="/quick6")
    public void save6(HttpServletResponse response) throws IOException {
    response.getWriter().print("hello itcast");
    }

    (2)将需要回写的字符串直接返回,但此时需要通过@ResponseBody注解告知SpringMVC框架,方法返回的字符串不是跳转是直接在http响应体中返回。

    1
    2
    3
    4
    5
    6
    //注意跟直接返回字符串的原始字符串很像,但是多了@ResponseBody注解
    @RequestMapping(value="/quick7")
    @ResponseBody //告知SpringMVC框架 不进行视图跳转 直接进行数据响应
    public String save7() throws IOException {
    return "hello itheima";
    }

    在异步项目中,客户端与服务器端往往要进行json格式字符串交互,此时我们可以手动拼接json字符串返回。

    1
    2
    3
    4
    5
    @RequestMapping(value="/quick8")
    @ResponseBody
    public String save8() throws IOException {
    return "{\"username\":\"zhangsan\",\"age\":18}";
    }

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <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>

    通过jackson转换json字符串,回写字符串

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @RequestMapping(value="/quick9")
    @ResponseBody
    public String save9() throws IOException {
    User user = new User();
    user.setUsername("lisi");
    user.setAge(30);
    //使用json的转换工具将对象转换成json格式字符串在返回
    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper.writeValueAsString(user);

    return json;
    }
  • 返回对象或集合

    通过SpringMVC帮助我们对对象或集合进行json字符串的转换并回写,为处理器适配器配置消息转换参数,指定使用jackson进行对象或集合的转换,因此需要在spring-mvc.xml中进行如下配置:

    (spring-mvc.xml)

    1
    2
    3
    4
    5
    6
    7
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
    <list>
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
    </list>
    </property>
    </bean>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @RequestMapping(value="/quick10")
    @ResponseBody
    //期望SpringMVC自动将User转换成json格式的字符串
    public User save10() throws IOException {
    User user = new User();
    user.setUsername("lisi2");
    user.setAge(32);

    return user;
    }

    在方法上添加@ResponseBody就可以返回json格式的字符串,但是这样配置比较麻烦,配置的代码比较多,因此,我们可以使用mvc的注解驱动代替上述配置。

    1
    2
    <!--mvc的注解驱动-->
    <mvc:annotation-driven conversion-service="conversionService"/>

    在 SpringMVC 的各个组件中,处理器映射器、处理器适配器、视图解析器称为 SpringMVC 的三大组件。

    使用<mvc:annotation-driven>自动加载 RequestMappingHandlerMapping(处理映射器)和RequestMappingHandlerAdapter(处理适配器),可用在Spring-xml.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。同时使用<mvc:annotation-driven>默认底层就会集成jackson进行对象或集合的json格式字符串的转换

SpringMVC获得请求数据

获得请求参数

客户端请求参数的格式是:name=value&name=value… …

服务器端要获得请求的参数,有时还需要进行数据的封装,SpringMVC可以接收如下类型的参数:

  • 基本类型参数
  • POJO类型参数
  • 数组类型参数
  • 集合类型参数

获得基本类型参数

Controller中的业务方法的参数名称要与请求参数的name一致,参数值会自动映射匹配。

http://localhost:8080/itheima_spring_mvc/user/quick11?username=zhangsan&age=12

1
2
3
4
5
6
@RequestMapping(value="/quick11")
@ResponseBody //代表不进行页面跳转
public void save11(String username,int age) throws IOException {
System.out.println(username);
System.out.println(age);
}

获得POJO类型参数

Controller中的业务方法的POJO参数的属性名与请求参数的name一致,参数值会自动映射匹配。

http://localhost:8080/itheima_spring_mvc/user/quick12?username=zhangsan&age=12

1
2
3
4
5
@RequestMapping(value="/quick12")
@ResponseBody
public void save12(User user) throws IOException {
System.out.println(user);
}

获得数组类型参数

Controller中的业务方法数组名称与请求参数的name一致,参数值会自动映射匹配。

http://localhost:8080/itheima_spring_mvc/user/quick13?strs=111&strs=222&strs=333

1
2
3
4
5
@RequestMapping(value="/quick13")
@ResponseBody
public void save13(String[] strs) throws IOException {
System.out.println(Arrays.asList(strs));
}

获得集合类型参数

获得集合参数时,要将集合参数包装到一个POJO中才可以。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/quick14" method="post">
<%--表明是第几个User对象的username age--%>
<input type="text" name="userList[0].username"><br/>
<input type="text" name="userList[0].age"><br/>
<input type="text" name="userList[1].username"><br/>
<input type="text" name="userList[1].age"><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class VO {
private List<User> userList;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
@Override
public String toString() {
return "VO{" +
"userList=" + userList +
'}';
}
}
1
2
3
4
5
@RequestMapping(value="/quick14")
@ResponseBody
public void save14(VO vo) throws IOException {//ViewObject
System.out.println(vo);
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
<script>
var userList = new Array();
userList.push({username:"zhangsan",age:18});
userList.push({username:"lisi",age:28});

$.ajax({
type:"POST",
url:"${pageContext.request.contextPath}/user/quick15",
data:JSON.stringify(userList),
contentType:"application/json;charset=utf-8"
});

</script>
</head>
<body>
</body>
</html>
1
2
3
4
5
@RequestMapping(value="/quick15")
@ResponseBody
public void save15(@RequestBody List<User> userList) throws IOException {
System.out.println(userList);
}

注意:通过谷歌开发者工具抓包发现,没有加载到jquery文件,原因是SpringMVC的前端控制器
DispatcherServleturl-pattern配置的是/,代表对所有的资源都进行过滤操作,我们可以通过以下两种方式指定放行静态资源:

  • 在spring-mvc.xml配置文件中指定放行的资源<mvc:resources mapping="/js/**" location="/js/"/>
  • 使用<mvc:default-servlet-handler/>标签

请求数据乱码问题

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

1
2
3
4
5
6
7
8
9
10
11
12
13
<!--配置全局过滤的filter-->
<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>

参数绑定注解@requestParam

当请求的参数名称与Controller的业务方法参数名称不一致时,就需要通过@RequestParam注解显示的绑定。

1
2
3
4
5
@RequestMapping(value="/quick16")
@ResponseBody
public void save16(@RequestParam(value="name") String username) throws IOException {
System.out.println(username);
}

注解@RequestParam还有如下参数可以使用:

  • value:与请求参数名称
  • required:此在指定的请求参数是否必须包括,默认是true,提交时如果没有此参数则报错
  • defaultValue:当没有指定请求参数时,则使用指定的默认值赋值
1
2
3
4
5
@RequestMapping(value="/quick16")
@ResponseBody
public void save16(@RequestParam(value="name",required = false,defaultValue = "itcast") String username) throws IOException {
System.out.println(username);
}

获得Rest风格的参数

REST(Representional State Transfer),表现形式状态转换

Rest是一种软件架构风格设计风格,而不是标准,只是提供了一组设计原则和约束条件。主要用于客户端和服务器交互类的软件,基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存机制等。

根据Rest风格对资源进行访问称为Restful

描述模块的名称通常使用复数,也就是加s的格式描述,表示此类资源而非单个资源,例如:users,books,accounts

传统风格资源描述形式:

http://localhost/user/getByID?id=1

http://localhost/user/saveUser

Rest风格描述形式:

http://localhost/user/1

http://localhost/user

优点:

  • 隐藏资源的访问行为,无法通过地址得知对资源是何种操作
  • 书写简化

Rest风格的请求是使用“url+请求方式”表示一次请求目的的,HTTP 协议里面四个表示操作方式的动词如下:

  • GET:用于获取资源
  • POST:用于新建资源
  • PUT:用于更新资源
  • DELETE:用于删除资源

例如:

  • /user/1 GET : 得到 id = 1 的 user
  • /user/1 DELETE: 删除 id = 1 的 user
  • /user/1 PUT: 更新 id = 1 的 user
  • /user POST: 新增 user

上述url地址/user/1中的1就是要获得的请求参数,在SpringMVC中可以使用占位符进行参数绑定。地址/user/1可以写成/user/{id},占位符{id}对应的就是1的值。

在业务方法中我们可以使用@PathVariable注解进行占位符的匹配获取工作。

http://localhost:8080/itheima_spring_mvc/user/quick17/zhangsan

1
2
3
4
5
@RequestMapping(value="/quick17/{name}")
@ResponseBody
public void save17(@PathVariable(value="name") String username) throws IOException {
System.out.println(username);
}

Restful快速开发:

  • 名称:@GetMapping @POSTMapping @ PutMapping @DeleteMapping
  • 类型:方法注解
  • 位置:基于SpringMVC的Restful开发控制器方法定义上方
  • 作用:设置当前控制器方法请求访问路径与请求动作,每种对应一个请求动作,例如@GetMapping对应GET请求
  • 属性:value(默认):请求访问路径

自定义类型转换器

SpringMVC 默认已经提供了一些常用的类型转换器,例如客户端提交的字符串转换成int型进行参数设置。

但是不是所有的数据类型都提供了转换器,没有提供的就需要自定义转换器,例如:日期类型的数据就需要自定义转换器。

自定义类型转换器的开发步骤:

  • 定义转换器类实现Converter接口

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    import org.springframework.core.convert.converter.Converter;

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class DateConverter implements Converter<String, Date> {
    public Date convert(String dateStr) {
    //将日期字符串转换成日期对象 返回
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Date date = null;
    try {
    date = format.parse(dateStr);
    } catch (ParseException e) {
    e.printStackTrace();
    }
    return date;
    }
    }
  • 在配置文件中声明转换器(spring-mvc.xml)

    1
    2
    3
    4
    5
    6
    7
    8
    <!--声明转换器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
    <list>
    <bean class="com.itheima.converter.DateConverter"></bean>
    </list>
    </property>
    </bean>
  • <annotation-driven>中引用转换器

    1
    2
    <!--mvc的注解驱动-->
    <mvc:annotation-driven conversion-service="conversionService"/>
    1
    2
    3
    4
    5
    @RequestMapping(value="/quick18")
    @ResponseBody
    public void save18(Date date) throws IOException {
    System.out.println(date);
    }

获得Servlet相关API

SpringMVC支持使用原始ServletAPI对象作为控制器方法的参数进行注入,常用的对象如下:

  • HttpServletRequest
  • HttpServletResponse
  • HttpSession
1
2
3
4
5
6
7
@RequestMapping(value="/quick19")
@ResponseBody
public void save19(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
System.out.println(request);
System.out.println(response);
System.out.println(session);
}

获得请求头

@RequestHeader
使用@RequestHeader可以获得请求头信息,相当于web阶段学习的request.getHeader(name)
@RequestHeader注解的属性如下:

  • value:请求头的名称
  • required:是否必须携带此请求头
1
2
3
4
5
@RequestMapping(value="/quick20")
@ResponseBody
public void save20(@RequestHeader(value = "User-Agent",required = false) String user_agent) throws IOException {
System.out.println(user_agent);
}

@CookieValue
使用@CookieValue可以获得指定Cookie的值
@CookieValue注解的属性如下:

  • value:指定cookie的名称
  • required:是否必须携带此cookie
1
2
3
4
5
@RequestMapping(value="/quick21")
@ResponseBody
public void save21(@CookieValue(value = "JSESSIONID") String jsessionId) throws IOException {
System.out.println(jsessionId);
}

文件上传

文件上传客户端三要素

  • 表单项type=“file”
  • 表单的提交方式是post
  • 表单的enctype属性是多部分表单形式,及enctype=“multipart/form-data”

upload.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>

<form action="${pageContext.request.contextPath}/user/quick23" method="post" enctype="multipart/form-data">
名称<input type="text" name="username"><br/>
文件<input type="file" name="uploadFile"><br/>
<input type="submit" value="提交">
</form>

</body>
</html>

文件上传原理

  • 当form表单修改为多部分表单时,request.getParameter()将失效。
  • enctype="application/x-www-form-urlencoded"时,form表单的正文内容格式是:
    key=value&key=value&key=value
  • 当form表单的enctype取值为Mutilpart/form-data时,请求正文内容就变成多部分形式:

单文件上传步骤

  • 导入fileupload和io坐标 (pom.xml)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
    </dependency>
    <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.3</version>
    </dependency>
  • 配置文件上传解析器 (spring-mvc.xml)

    1
    2
    3
    4
    5
    <!--配置文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="UTF-8"/>
    <property name="maxUploadSize" value="500000"/>
    </bean>
  • 编写文件上传代码 (注意对应路径要有文件夹)

    1
    2
    3
    4
    5
    6
    7
    8
    @RequestMapping(value="/quick22")
    @ResponseBody
    public void save22(String username, MultipartFile uploadFile,MultipartFile uploadFile2) throws IOException {
    System.out.println(username);
    //获得上传文件的名称
    String originalFilename = uploadFile.getOriginalFilename();
    uploadFile.transferTo(new File("F:\\test\\"+originalFilename));
    }

多文件上传实现

多文件上传,只需要将页面修改为多个文件上传项,将方法参数MultipartFile类型修改为MultipartFile[]即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>

<form action="${pageContext.request.contextPath}/user/quick23" method="post" enctype="multipart/form-data">
名称<input type="text" name="username"><br/>
文件1<input type="file" name="uploadFile"><br/>
文件2<input type="file" name="uploadFile"><br/>
<input type="submit" value="提交">
</form>

<form action="${pageContext.request.contextPath}/user/quick22" method="post" enctype="multipart/form-data">
名称<input type="text" name="username"><br/>
文件1<input type="file" name="uploadFile"><br/>
文件2<input type="file" name="uploadFile2"><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
1
2
3
4
5
6
7
8
9
@RequestMapping(value="/quick23")
@ResponseBody
public void save23(String username, MultipartFile[] uploadFile) throws IOException {
System.out.println(username);
for (MultipartFile multipartFile : uploadFile) {
String originalFilename = multipartFile.getOriginalFilename();
multipartFile.transferTo(new File("F:\\test\\"+originalFilename));
}
}

Spring环境搭建步骤

  • 创建工程(Project&Module)
  • 导入静态页面(jsp页面)
  • 导入需要坐标(pom.xml)
  • 创建包结构(controller、service、dao、domain、utils)
  • 导入数据库脚本(见资料test.sql)
  • 创建POJO类(见资料User.java和Role.java)
  • 创建配置文件(applicationContext.xml、spring-mvc.xml、jdbc.properties、log4j.properties)
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2022 ZHU
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信