目录
1.1ApplicationContext应用上下文获取方式
SpringMVC 是 Spring 提供的一种基于MVC设计模式的轻量级 Web 开发框架,本质上相当于Servlet,我们来看看如何在Spring中集成 Web 环境。
一、Spring集成 Web 环境
首先我们创建一个有web环境的项目spring_mvc,详细步骤可见链接。
我们快速实现Dao层和Service层的代码,实现一个save方法,打印save这几个字。
然后将UserDao和UserService利用xml配置文件放到Spring容器中,创建对应的Bean对象。
<!--配置UserDao到Spring容器中-->
<bean id="userDao" class="Dao.UserDaoImpl"></bean>
<!--配置UserService到Spring容器中-->
<bean id="userService" class="Service.UserServiceImpl">
<!--设置userDao的属性-->
<property name="userDao" ref="userDao"></property>
</bean>
然后我们新建一个Web包,创建一个UserServlet,我们在里面通过应用的getBean方法获取到UserService对象,调用save方法。
package Web;
import Service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/servlet/userServlet")//设置servlet访问路径
public class UserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");//获取Spring应用上下文对象
UserService userService = app.getBean(UserService.class);//通过id标识从容器中获得UserService对象
userService.save();//调用业务方法
}
}
这里我们通过注解@WebServlet 配置了访问的地址,所以不用在web.xml中再配置了。启动服务器,访问对应的url。
1.1ApplicationContext应用上下文获取方式
在上述的例子中,应用上下文对象是通过new ClasspathXmlApplicationContext(spring配置文件) 方式获取的,但是每次从容器中获得Bean时都要编写new ClasspathXmlApplicationContext(spring配置文件) ,这样的弊端是配置文件加载多次,应用上下文对象创建多次。
我们很容易想到,这个应用上下文对象能不能统一创建,只用加载一次配置文件,创建一次应用上下文对象,这样大家都来一起用这个对象。
在Web项目中,可以使用ServletContextListener监听Web应用的启动,我们可以在Web应用启动时,就加载Spring的配置文件,创建应用上下文对象ApplicationContext,在将其存储到最大的域servletContext域中,这样就可以在任意位置从域中获得应用上下文ApplicationContext对象了。
我们新建一个Listener包,创建一个ContextLoaderListener对象,用于监听ServletContext的创建。
package Listener;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener//配置监听器
public class ContextLoaderListener implements ServletContextListener {
//ServletContext初始化监听方法
public void contextInitialized(ServletContextEvent servletContextEvent) {
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");//获取Spring应用上下文对象
ServletContext servletContext = servletContextEvent.getServletContext();//获取ServletContext对象
servletContext.setAttribute("app",app);//将Spring的应用上下文对象存储到ServletContext域中
System.out.println("Spring应用上下文对象app已创建.....");
}
//ServletContext销毁监听方法
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
然后我们修改我们的servlet,不直接创建ApplicationContext对象,从ServletContext域中获取相应的对象。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext servletContext = request.getServletContext();//获取ServletContext对象
ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");//通过ServletContext对象获取app属性
UserService userService = app.getBean(UserService.class);//通过id标识从容器中获得UserService对象
userService.save();//调用业务方法
}
启动服务器,访问servlet的地址,可以看到方法正确执行了。
针对上面这个例子,我们可以把applicationContext.xml配置文件的名字作为参数设置到web.xml中,
<!--全局初始化参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
然后我们在代码中读取即可,
//应用上下文初始化监听方法
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();//获取ServletContext对象
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");//读取web.xml中的全局参数
ApplicationContext app=new ClassPathXmlApplicationContext(contextConfigLocation);//获取Spring应用上下文对象
servletContext.setAttribute("app",app);//将Spring的应用上下文对象存储到ServletContext域中
System.out.println("Spring应用上下文对象app已创建.....");
}
我们还可以对存储的参数名字再封装一次,让用户直接调用方法即可获取应用上下文对象,
class WebApplicationContextUtils {
//通过servlet获取ApplicationContext对象,从而不关注属性名字
public static ApplicationContext getApplicationContext(ServletContext servletContext){
return (ApplicationContext) servletContext.getAttribute("app");
}
}
在调用的时候直接使用该类的静态方法,
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext servletContext = request.getServletContext();//获取ServletContext对象
ApplicationContext app = WebApplicationContextUtils.getApplicationContext(servletContext);//通过工具类获取应用上下文对象
UserService userService = app.getBean(UserService.class);//通过id标识从容器中获得UserService对象
userService.save();//调用业务方法
}
1.2Spring提供获取应用上下文的工具
Spring提供了一个监听器ContextLoaderListener就是对上述功能的封装,该监听器内部加载Spring配置文件,创建应用上下文对象,并存储到ServletContext域中,提供了一个客户端工具WebApplicationContextUtils供使用者获得应用上下文对象。
所以我们需要做的只有两件事:
- 在web.xml中配置ContextLoaderListener监听器(要导入spring-web坐标)
- 使用WebApplicationContextUtils获得应用上下文对象ApplicationContext
第一步我们首先在pom.xml中导入spring-web坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
第二步我们在web.xml中配置ContextLoaderListener监听器
<!--配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
第三步我们使用WebApplicationContextUtils获得应用上下文对象ApplicationContext,
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext servletContext = request.getServletContext();//获取ServletContext对象
ApplicationContext app= WebApplicationContextUtils.getWebApplicationContext(servletContext);//通过spring-web的工具类获取应用上下文对象
UserService userService = app.getBean(UserService.class);//通过id标识从容器中获得UserService对象
userService.save();//调用业务方法
}
最后启动服务器,
二、SpringMVC简介
SpringMVC 是一种基于 Java 的实现 MVC 设计模型的请求驱动类型的轻量级 Web 框架,属于SpringFrameWork 的后续产品,已经融合在 Spring Web Flow 中。
SpringMVC 已经成为目前最主流的MVC框架之一,并且随着Spring3.0 的发布,全面超越 Struts2,成为最优秀的 MVC 框架。
它通过一套注解,让一个简单的 Java 类成为处理请求的控制器,而无须实现任何接口。同时它还支持 RESTful 编程风格的请求。
SpringMVC的开发步骤示意图如图所示:
- 导入SpringMVC相关坐标
- 配置SpringMVC核心控制器DispatcherServlet
- 创建Controller类和视图页面
- 使用注解配置Controller 类中业务方法的映射地址
- 配置SpringMVC核心文件 spring-mvc.xml
- 客户端发起请求测试
接下来我们一步步去实现。
第一步是导入Spring和SpringMVC的坐标,还有Servlet和Jsp的坐标,
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
第二步我们在web.xml中配置SpringMVC核心控制器DispatcherServlet,
<!--配置SpringMVC的核心控制器DispatcherServlet-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
第三步我们创建Controller类和视图页面,
我们先新建一个succes.jsp界面,
<h1>Success!</h1>
然后新建一个Controller包,存储SpringMVC中web层的类,
class UserController {
public String save(){
System.out.println("Controller save running.....");
return "success.jsp";
}
}
第四步使用注解配置Controller 类中业务方法的映射地址,
@Controller//放置到Spring容器中
class UserController {
@RequestMapping("/quick")//配置映射地址
public String save(){
System.out.println("Controller save running.....");
return "success.jsp";
}
}
第五步配置SpringMVC核心文件 spring-mvc.xml,我们在资源文件下新建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="Controller"></context:component-scan>
</beans>
写好之后我们还要将SpringMVC核心配置文件告诉核心控制器,我们在servlet标签中进行配置。
<!--配置SpringMVC的核心控制器DispatcherServlet-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置spring-mvc配置文件的路径到servlet初始参数中-->
<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>
第六步进行测试,我们启动服务器,输入刚刚设置的映射地址http://localhost:8080/quick
上述过程的一个流程图如下:
三、SpringMVC的组件解析
3.1SpringMVC的执行流程
- 用户发送请求至前端控制器DispatcherServlet。
- DispatcherServlet收到请求调用HandlerMapping处理器映射器。
- 处理器映射器找到具体的处理器(可以根据xml配置、注解进行查找),生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。
- DispatcherServlet调用HandlerAdapter处理器适配器。
- HandlerAdapter经过适配调用具体的处理器(Controller,也叫后端控制器)。
- Controller执行完成返回ModelAndView。
- HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet。
- DispatcherServlet将ModelAndView传给ViewReslover视图解析器。
- ViewReslover解析后返回具体View。
- DispatcherServlet根据View进行渲染视图(即将模型数据填充至视图中)。DispatcherServlet响应用户。
3.2SpringMVC组件解析
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。一般情况下需要通过页面标签或页面模版技术将模型数据通过页面展示给用户,需要由程序员根据业务需求开发具体的页面。
3.3SpringMVC注解解析
@RequestMapping
- 作用:用于建立请求 URL 和处理请求方法之间的对应关系
- 位置:
- 类上:请求URL 的第一级访问目录。此处不写的话,就相当于应用的根目录
- 方法上:请求 URL 的第二级访问目录,与类上的使用 @RequestMapping 标注的一级目录一起组成访问虚拟路径
- 属性 :
- value:用于指定请求的URL。它和path属性的作用是一样的
- method:用于指定请求的方式
- params:用于指定限制请求参数的条件。它支持简单的表达式。要求请求参数的key和value必须和配置的一模一样
例如:
params = {"accountName"},表示请求参数必须有accountName
params = {"moeny!100"},表示请求参数中money不能是100
3.4SpringMVC组件扫描
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=“XXXX"/>进行组件扫描。
3.5SpringMVC的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 = ""; --视图名称后缀
假设我们现在更改了success.jsp的位置,我们把它放在了WEBAPP/jsp包下,那么我们就要更改代码中相应的位置,
@RequestMapping("/quick")//配置映射地址
public String save(){
System.out.println("Controller save running.....");
return "/jsp/success.jsp";
}
这样才能正确转发到该位置,但是我们可以配置前缀后缀,简化我们输入的url,
<!--配置内部资源视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置资源解析时的前缀和后缀-->
<property name="prefix" value="/jsp"></property>
<property name="suffix" value=".jsp"></property>
</bean>
这样我们就可以直接填写页面的名字success即可,
@RequestMapping("/quick")//配置映射地址
public String save(){
System.out.println("Controller save running.....");
return "success";
}