Spring与Web环境集成
在配置好的骨架maven web项目中,将测试代码写入doGet方法中,然后配置TomCat即可在控制台打印save的信息
导入Spring集成web的坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
配置servlet
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.zg.web.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/userServlet</url-pattern>
</servlet-mapping>
</web-app>
通过工具获得应用上下文对象
package com.zg.web;
import com.zg.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//找Spring容器要service对象进项save方法调用
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = app.getBean(UserService.class);
userService.save();
}
}
ApplicationContext应用上下文获取方式
应用上下文是通过new ClassPathXmlApplicationContext(Spring配置文件)方式获取的,但是每次从容器中获得Bean时都要编写new ClassPathXmlApplicationContext(Spring配置文件),这样的弊端是配置文件加载多次,应用上下文对象创建多次
在Web项目中,可以使用ServletContextListener监听Web应用的启动,我们可以在Web应用启动时,就加载Spring的配置文件,创建应用上下文对象ApplicationContext,在将其存储到最大的域servletContext域中,这样就可以在任意位置从域中获得应用上下文ApplicationContext对象了
我们从web层通过Spring容器获得service,然后service内部的Dao是在容器内部注入的。当web层后期有很多业务的时候(有很多service组件),而每个当中需要调用方法都需要通过应用上下文获取service,每个doGet里面都得写new ClassPathXmlApplicationContext,这样代表容器会创建很多个
导入Spring集成web的坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
编写ContxtLoaderListener
package com.zg.listener;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ContextLoaderListener implements ServletContextListener {
@Override
//上下文初始化方法
public void contextInitialized(ServletContextEvent servletContextEvent) {
//ApplicationContext app = new ClassPathXmlApplicationContext("application.xml");
//以上代码中的application.xml文件是写死的,所以需要在web.xml文件中获取全局参数防止耦合死
ServletContext servletContext = servletContextEvent.getServletContext();
//读取web.xml中的全局参数
//web.xml文件本身就是配置文件,所以在xml文件中配置<context-param>
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
//将Spring的应用上下文对象存储到ServletContext域中
servletContext.setAttribute("app",app);
System.out.println("spring容器创建完毕....");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
配置ContxtLoaderListener监听器
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--全局初始化参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.zg.web.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/userServlet</url-pattern>
</servlet-mapping>
</web-app>
WebApplicationContextUtils工具类设置应用上下文app名字
package com.zg.listener;
import org.springframework.context.ApplicationContext;
import javax.servlet.ServletContext;
public class WebApplicationContextUtils {
public static ApplicationContext getWebApplicationContext(ServletContext servletContext){
return (ApplicationContext) servletContext.getAttribute("app");
}
}
通过工具获得应用上下文对象
package com.zg.web;
import com.zg.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//找Spring容器要service对象进项save方法调用
//ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
ServletContext servletContext = req.getServletContext();
//ServletContext servletContext1 = this.getServletContext();
//ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
//ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UserService userService = app.getBean(UserService.class);
userService.save();
}
}
Spring提供获取应用上下文的工具
上面的分析不用手动实现,Spring提供了一个监听器ContextLoaderListener就是对上述功能的封装,该监听器内部加载配置文件,创建应用上下文对象,并存储到ServletContext域中,提供了一个客户端工具WebApplicationContextUtils供使用者获取应用上下文对象
1、在web.xml中配置contextLoaderListener监听器(导入Spring-web坐标)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
2、在web.xml文件中配置
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<!--配置全局过滤的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>
<!--全局初始化参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.zg.web.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/userServlet</url-pattern>
</servlet-mapping>
</web-app>
3、使用具WebApplicationContextUtils获取应用上下文对象ApplicationContext
package com.zg.web;
import com.zg.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//找Spring容器要service对象进项save方法调用
//ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
ServletContext servletContext = req.getServletContext();
//ServletContext servletContext1 = this.getServletContext();
//ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
//ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UserService userService = app.getBean(UserService.class);
userService.save();
}
}
SpringMVC简介
SpringMVC概述
SpringMVC是一种基于Java的实现MVC设计模式的请求驱动类型的轻量级Web框架,属于SpringFrameWork的后续产品,已经融合在Spring Web Flow中。
原先我们在web层编写时,使用servlet(一个类)请求时需要继承servlet接口或继承HttpServlet间接实现接口,使用Spring MVC不用实现任何接口,也不用继承任何类,就写一个简单的javaBean对象,他就可以成为一个请求处理的一个控制器
SpringMVC已经成为目前最主流的MVC框架之一,并且随着Spring3.0的发布,全面超越Struts2,成为最优秀的MVC框架。它通过一套注解,让一个简单的Java类成为处理请求的控制器,而无须实现任何接口。同时它还支持 RESTful编程风格的请求。
SpringMVC快速入门
需求:客户端发起请求,服务器接收请求,执行逻辑并进行视图跳转
开发步骤:
1、导入SpringMVC 相关坐标
2、配置SpringMVC 核心控制器DispathcerServlet
3、创建Controller类和视图页面
4、使用注解配置Controller类中业务方法的映射地址
5、配置SpringMVC核心文件spring-mvc.xml
6、客户端发起请求测试
在pom中导入SpringMVC 相关坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
在Web.xml中配置SpringMVC 核心控制器DispathcerServlet
<!--配置SpringMVC的前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param><!--servlet初始化参数,用来加载spring-nvc.xml-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!--服务器启动时加载servlet,创建对象-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
创建Controller和业务方法
package com.zg.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
public class UserController {
public String save(){
System.out.println("Controller save running...");
//return的是我要跳转的视图
return "success.jsp";
}
}
创建视图页面index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Success</h1>
</body>
</html>
使用注解配置Controller类中业务方法的映射地址
package com.zg.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class UserController {
@RequestMapping("/quick")
public String save(){
System.out.println("Controller save running...");
//return的是我要跳转的视图
return "success.jsp";
}
}
配置SpringMVC核心文件spring-mvc.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"
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">
<!--Controller的组件扫描-->
<context:component-scan base-package="com.zg.controller"></context:component-scan>
</beans>
访问测试地址http://localhost:8080/quick
SpringMVC 流程演示
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的存在降低了组件之间的耦合性。
2.处理器映射器:HandlerMapping
HandlerMapping负责根据用户请求找到Handler即处理器,SpringMVC提供了不同的映射器实现不同的映射方式,例如:配置文件方式,实现接口方式,注解方式等。
3.处理器适配器: HandlerAdapter
通过HandlerAdapter对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理器进行执行。
4.处理器: Handler
它就是我们开发中要编写的具体业务控制器。由DispatcherServlet把用户请求转发到Handler。由Handler 对具体的用户请求进行处理。
5.视图解析器: View Resolver
View Resolver 负责将处理结果生成View视图,View Resolver首先根据逻辑视图名解析成物理视图名,即具体的页面地址,再生成View视图对象,最后对View进行渲染将处理结果通过页面展示给用户。
6.视图: 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
package com.zg.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/user")
public class UserController {
//请求地址:http://127.0.0.1/;8080/user/quick?username=xxx
@RequestMapping(value = "/quick",method = RequestMethod.GET,params = {"username"})
public String save(){
System.out.println("Controller save running...");
//return的是我要跳转的视图
return "success.jsp";
}
}
MVC命名空间引入
<?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"
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">
<!--Controller的组件扫描-->
<context:component-scan base-package="com.zg.controller"></context:component-scan>
</beans>
组件扫描
SpringMVC 基于Spring容器,所以在进行SpringMVC操作时,需要将Controller存储到Spring容器中,如果使用@Controller注解标注的话,就需要使用<context:component-scan base-package="com.zg.controller"></context:component-scan>
进行组件扫描
SpringMVC的xml配置解析
视图解析器
SpringMVC有默认组件配置,默认组件都是DispatcherServlet.properties配置文件中配置的,该配置文件地址org/springframework/web/servlet/DispatcherServlet.properties,该文件中配置了默认的视图解析器,如下
org.springframework.web.servlet.ViewReslver=org.springframework.web.servlet.view.InternalResourceViewResolver
翻看该解析器源码,可以看到该解析器的默认设置
REDIRECT_URL_PREFIX = "redirect:" ---重定向前缀
FORWARD_URL_PREFIX = "forward:" ---转发前缀(默认值)
prefix = ""; --视图名称前缀
suffix = ""; --视图名称后缀
通过属性注入的方式修改驶入的前后缀
package com.zg.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/user")
public class UserController {
//请求地址:http://127.0.0.1/;8080/user/quick?username=xxx
@RequestMapping(value = "/quick",method = RequestMethod.GET,params = {"username"})
public String save(){
System.out.println("Controller save running...");
//return的是我要跳转的视图
//在这里默认是转发前缀forward,若是redirect其地址是会变的,因为转发
//return "forward:/success.jsp";
//但是这里如果要将sucess放在webapp下的jsp包中,则需要
// return "/jsp/success.jsp";
//但是可以在spring-mvc中将其进行配置,省略前后缀
return "success";
}
}
<?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"
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">
<!--Controller的组件扫描-->
<context:component-scan base-package="com.zg.controller"></context:component-scan>
<!--手动配置内部资源解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
SpringMVC的数据相应
SpringMVC的数据响应方式
页面跳转
直接返回字符串
通过ModelAndView对象返回
回写数据
直接返回字符串
返回对象或集合
页面跳转
直接返回字符串形式
直接返回字符串:此种方式会将返回的字符串与视图解析器的前后缀拼接后跳转
通过ModelAndView对象返回
web层
@RequestMapping(value = "/quick1")
public ModelAndView save1(){
//Model:模型,作用封装数据,View:视图,展示数据
ModelAndView modelAndView = new ModelAndView();
//设置模型数据,这样就相当于放在了域当中了
modelAndView.addObject("username","haha");
//设置视图名称
modelAndView.setViewName("success");
return modelAndView;
}
v层:<%@ page isELIgnored="false" %>
需要引入el表达式
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Success ${username}</h1>
</body>
</html>
SpringMVC可以对相应的方法进行注入
@RequestMapping(value = "/quick2")
public ModelAndView save2(ModelAndView modelAndView){
modelAndView.addObject("username","zgdaren");
//设置视图名称
modelAndView.setViewName("success");
return modelAndView;
}
@RequestMapping(value = "/quick3")
//使用model将数据使用model进行传入,视图使用字符串进行传入
public String save3(Model model){
model.addAttribute("username","haahahah");
return "success";
}
向request域存储数据
在进行转发时,往往要向request域中存储数据,在jsp页面中显示,所有通过SpringMVC框架注入的request对象setAttribute()方法设置
传入的形参,调用者传入实参,调用者为SpringMVC 框架
@RequestMapping(value = "/quick4")
public String save4(HttpServletRequest request){
request.setAttribute("username","玻璃杯");
return "success";
}
回写数据
直接返回字符串
web基础阶段,客户端访问服务器端,如果想回写字符串作为响应体返回的话,只需要使用response.getWriter().print(“hello world”)即可,那么在Controller中想要直接回写字符串应该怎样呢?
1、通过SpringMVC框架注入response对象,使用response.getWriter().print(“hello world”)回写数据,此时不需要视图跳转,业务方法返回值为void
@RequestMapping(value = "/quick5")
public void save5(HttpServletResponse response) throws IOException {
response.getWriter().print("hello zg");
}
2、将需要回写的字符串直接返回,但此时需要通过 @ResponseBody
注解告知SpringMVC框架,方法返回的字符串不是跳转而是直接在http响应体中进行返回字符串
@RequestMapping(value = "/quick6")
@ResponseBody//告诉springmvc不要发生跳转,而是直接打印
public String save6() throws IOException {
return "hello zg";
}
在异步项目中,客户端与服务器端往往要进行json格式的字符串交换,此时我们需要手动拼接json字符串并返回
@RequestMapping(value = "/quick7")
@ResponseBody//告诉springmvc不要发生跳转,而是直接打印
public String save7() throws IOException {
return "{\"username\":\"zhangsan\",\"age\":18}";
}
将Java对象转换为json的字符串
1、导入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>
2、通过jackson转换json格式字符串,回写字符串
@RequestMapping(value = "/quick8")
@ResponseBody//告诉springmvc不要发生跳转,而是直接打印
public String save8() throws IOException {
User user = new User();
user.setUsername("lisi");
user.setAge(22);
ObjectMapper objectMapper = new ObjectMapper();
String s = objectMapper.writeValueAsString(user);
return s;
}
返回对象或集合
通过SpringMVC帮助我们对对象或集合进行json字符串的转换并回写,为处理器适配消息转换参数,指定使用jackson进行对象或集合的转换,因此需要在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>
然后在返回对象或集合
@RequestMapping(value = "/quick9")
@ResponseBody//告诉springmvc不要发生跳转,而是直接打印
//期望SpringMVC自动将User转换成json格式的字符串
public User save9() throws IOException {
User user = new User();
user.setUsername("lisi");
user.setAge(22);
return user;
}
我们可以使用mvc的注解驱动代替上面spring-mvc.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.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.xsd">
<!--mvc的注释驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
在SpringMVC的各个组件中,处理器映射器、处理器适配器、视图解析器成为SpringMVC的三大组件,使用<mvc:annotation-driven>
自动加载RequestMappingHandlerMapping(处理映射器)和RequestMappingHandlerAdapter(处理适配器),可用在Spring-mvc.xml配置文件中使用<mvc:annotation-driven>
替代注解处理器和适配器的配置
同时使用<mvc:annotation-driven>
默认底层就会集成jackson进行对象或集合的json格式字符串的转换。
SpringMVC获得请求数据
获得请求参数
客户端请求参数的格式是:name = value&name=value…
服务器端获得请求的参数,有时还需要进行数据的封装,SpringMVC可以接收如下类型的参数:
基本参数类型
POJO类型参数
数组类型参数
集合类型参数
获得基本类型参数
Controller中的业务方法的参数名称要与请求参数的name一致,参数值会自动映射匹配
http://localhost:8080/user/quick10?username=zhangsan&age=22
@RequestMapping(value = "/quick10")
@ResponseBody//告诉springmvc不要发生跳转,而是直接打印
public void save10(String username,int age) throws IOException {
System.out.println(username);
System.out.println(age);
}
获得POJO类型参数
Controller的业务方法的POJO参数的属性名与请求参数的name一致,参数值会自动映射匹配
http://localhost:8080/user/quick11?username=zhangsan&age=22
这里需要先将POJO的JavaBean写出来
@RequestMapping(value = "/quick11")
@ResponseBody//告诉springmvc不要发生跳转,而是直接打印
public void save11(User user) throws IOException {
System.out.println(user);
}
获得数组类型参数
Cotroller中的业务方法数组名称与请求参数的name一致,参数值会自动映射匹配
http://localhost:8080/user/quick12?strs=aaa&strs=bbb&strs=ccc
@RequestMapping(value = "/quick12")
@ResponseBody//告诉springmvc不要发生跳转,而是直接打印
public void save12(String[] strs) throws IOException {
System.out.println(Arrays.asList(strs));//将strs作为一个list集合
}
获得集合类型参数
获得集合参数时,要将集合参数包装到一个POJO中才可以
编写前端页面进行接收参数
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/quick13" 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="text" name="userList[2].username"><br/>
<input type="text" name="userList[2].age"><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
将user作为参数传递入List集合当中
package com.zg.domain;
import java.util.List;
public class VO {
private List<User> userList;
public VO(List<User> userList) {
this.userList = userList;
}
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public VO() {
}
@Override
public String toString() {
return "VO{" +
"userList=" + userList +
'}';
}
}
获取请求参数
@RequestMapping(value = "/quick13")
@ResponseBody//告诉springmvc不要发生跳转,而是直接打印
public void save13(VO vo) throws IOException {
System.out.println(vo);//VO{userList=[User{username='bob', age=22}, User{username='aclice', age=32}, User{username='Mallry', age=21}]}
}
当使用ajax提交时,可以指定contentType为json形式,那么在方法参数位置使用@RequestBody可以直接接收集合数据而无需使用POJO进行包装
@RequestBody直接将请求体封装到集合当中
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<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:23})
$.ajax({
type:"POST",
url:"${pageContext.request.contextPath}/user/quick14",
data:JSON.stringify(userList),
contentType:"application/json;charset=utf-8"
});
</script>
</head>
<body>
</body>
</html>
@RequestMapping(value = "/quick14")
@ResponseBody//告诉springmvc不要发生跳转,而是直接打印
public void save14(@RequestBody List<User> userList) throws IOException {
System.out.println(userList);
}
获得集合类型参数
在通过抓包发现,没有加载到JQuery文件,原因是SpringMVC的前端控制器DispatcherServlet-pattern配置的是/,代表对所有资源进行都进行过滤操作,我们可以通过以下方式进行静态资源放行
1、在Spring-mvc.xml配置中指定放行的资源,但需要将这个maven项目clean一下
//开放资源的访问
<mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
2、在Spring-mvc.xml配置中使用<mvc:default-servlet-handler/>
标签,代表访问资源时,SpringMVC帮我找到对应的匹配地址/quick15,找不到就交由原始的容器tomcat帮我找到静态资源
请求数据乱码问题
当post请求时,数据会出现乱码,我们可以在web.xml设置过滤器来进行编码的过滤
<!--配置全局过滤的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注解显示的绑定
value:与请求参数名称
required:此在指定的请求参数是否必须包括,默认是true,提交时如果没有此参数则报错
defaultValue:当没有指定请求参数时,则使用指定的默认值赋值
@RequestMapping(value = "/quick15")
@ResponseBody
//将请求的name映射到请求参数username上
//required = false表示请求时name属性不是必须携带的,默认为true
//defaultValue = "zgDaren"如果没有请求参数则会在控制台打印defaultValue中的值zgDaren
public void save15(@RequestParam(value="name",required = false,defaultValue = "zgDaren") String username) throws IOException {
System.out.println(username);
}
获得Restful风格的参数
Restful值一种软件风格、设计风格,而不是标准,只是提供了一组设计原则和约束条件,主要用于客户端和服务器交互的软件,基于这个风格设计的软件可以更简洁,更优层次,更易于实现缓存机制等
Restful风格的请求是使用“url+请求方式”表示一次请求目的的,HTTP协议里面四个表示操作方式的动词如下:
GET:用于获取资源
POST:用于新建资源
PUT:用于更新资源
DELLETE:用于删除资源
例如:
/user/1 GET :得到id=1的user
/user/1 DELLETE:删除id=1的user
/user/1 PUT:更新id=1的user
/user POST:新增user
上述url地址/user/1中的1就是要获取的请求参数,在SpringMVC中可以使用哦占位符进行参数绑定,地址/user/1可以写成/user/{id},占位符{id}对应的1的值,在业务方法中我们可以使用@PathVariable注解进行占位符的匹配获取工作
//请求地址:localhost:8080/user/quick16/zhangsan
@RequestMapping(value = "/quick16/{username}")//这里的name不是以?=张三传入而是以url形式传入
@ResponseBody
public void save16(@PathVariable(value="username",required = false) String username) throws IOException {
System.out.println(username);
}
自定义类型转换器
SpringMVC默认已经提供了一些常用的类型转换器,例如客户端提交的字符串转换成int型进行参数设置,但不是所有数据类型都提供了转换器,没有提供的就需要自定义转换器,例如:日期类型的数据就需要自定义转换器
自定义类型转换器的开发步骤
1、定义转换器类实现Converter接口
package com.zg.converter;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
//string为转日期前的字符串,date为转换后的格式
public class DateConverter implements Converter<String,Date> {
@Override
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;
}
}
2、在spring-mvc.xml配置文件中声明转换器
<!--声明转换器,定义一个转换器的工厂对象,让工厂帮我们转换日期转换器的bean-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.zg.converter.DateConverter"></bean>
</list>
</property>
</bean>
3、在<annotation-driven>
中引用转换器
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
4、代码测试
/自定义类型转换器
@RequestMapping(value = "/quick17")
@ResponseBody
public void save17(Data data) throws IOException {
System.out.println(data);
}
获得Servlet相关API
SpringMVC 支持使用原始ServletAPI对象作为控制器方法的参数进行注入,常用的对象如下:
HttpServletRequest
HttpServletResponse
HttpSession
//这些springmvc中servlet会帮我们进行注入
@RequestMapping(value = "/quick18")
@ResponseBody
public void save18(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:是否必须携带此请求头
//获取请求头,required = false代表没有也能访问
@RequestMapping(value = "/quick19")
@ResponseBody
public void save19(@RequestHeader(value = "User-Agent",required = false) String user_agent) throws IOException {
System.out.println(user_agent);
}
@CookieValue
使用@CookieValue可以获得指定Cookic的值
@CookieValue注解的属性如下:
value:请求Cookic名称
required:是否必须携带此Cookic
@RequestMapping(value = "/quick20")
@ResponseBody
public void save20(@CookieValue(value = "JSESSIONID") String jessionid) throws IOException {
System.out.println(jessionid);
}
文件上传
文件上传客户端三要素
表单项type=“file”
表单的提交方式是post
表单的enctype属性是多部分表单形式,即enctype="multipart/form-data"
<form action="${pageContext.request.contextPath}/user/quick21" method="post" enctype="multipart/form-data">
名称<input type="text" name="username"><br>
文件<input type="file" name="upload"><br>
<input type="submit" value="提交">
</form>
文件上传原理
当form表单修改为多部分表单时,request.getParameter()将失效
enctype="application/x-www-form-urlencoded"时,form表单的正文内容格式是:key=value&key=value&key=value
当form表单的enctype取值为multipart/form-data时,请求正文内容就变成多部分形式
单文件上传步骤
1、导入fileupload和io坐标
<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.4</version>
</dependency>
2、配置文件上传解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--上传文件的大小-->
<property name="maxUploadSize" value="5242800"></property>
<!--上传单个文件的大小-->
<property name="maxUploadSizePerFile" value="5242800"></property>
<!--上传文件的额编码类型-->
<property name="defaultEncoding" value="utf-8"></property>
</bean>
3、编写文件上传代码
@RequestMapping(value = "/quick21")
@ResponseBody
public void save21(String username, MultipartFile upload) throws IOException {
System.out.println(username);
//获得上传文件名称
String originalFilename = upload.getOriginalFilename();//这里可以使用原始的IO存
upload.transferTo(new File("d:\\java\\"+originalFilename));
}
多文件上传
使用集合上传
@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("C:\\upload\\"+originalFilename));
}
}
一个一个上传
@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("C:\\upload\\"+originalFilename));
String originalFilename2 = uploadFile2.getOriginalFilename();
uploadFile2.transferTo(new File("C:\\upload\\"+originalFilename2));
}
前端代码
<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>