学习SpringMVC——配置文件和第一个SpringMVC应用

来源:互联网 发布:苹果平板淘宝开店在哪 编辑:程序博客网 时间:2024/05/18 02:27

SpringMVC的配置文件有两个,分别是部署描述符文件(web.xml)和Spring MVC配置文件(springmvc.xml)。配置的内容主要有以下几点:

  1. 配置前端控制器DispatcherServlet;
  2. 配置处理器适配器;
  3. 配置处理器映射器;
  4. 配置视图解析器;
  5. 配置控制器(Handler)。

    具体的配置在下面的SpringMVC应用中具体讲解。

一、环境的搭建

单纯的SpringMVC应用,需要用到的jar包并不多,如下图所示:
这里写图片描述

二、配置前端控制器DispatcherServlet

SpringMVC的前端控制器是一个servlet:org.springframework.web.servlet.DispatcherServlet,Struts2的前端控制器是一个Filter。配置servlet需要配置<servlet><servlet-mapping>,如下所示:

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>Study_SpringMVC</display-name>  <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list>  <!-- 配置前端控制器DispatcherServlet -->  <servlet>    <servlet-name>springmvc</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <init-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath:springmvc.xml</param-value>    </init-param>  </servlet>  <servlet-mapping>    <servlet-name>springmvc</servlet-name>    <url-pattern>/</url-pattern>  </servlet-mapping>  </web-app>

需要注意的是,在<init-param>指定了SpringMVC的配置文件的位置,如果没有指定配置文件位置的话,需要将配置文件命名为[servlet-name]-servlet.xml,并将其放在web.xml相同的路径下。

三、配置处理器适配器

SpringMVC中,常用的处理器适配器有两种,SimpleControllerHandlerAdapter和HttpRequestHandlerAdapter。
(1)SimpleControllerHandlerAdapter是默认的处理器适配器,如果不在配置文件中配置,SpringMVC将使用这个适配器。所以,当我把处理器适配器的配置注释掉后,SpringMVC应用依然可用;
(2)HttpRequestHandlerAdapter需要handler实现HttpRequestHandler接口。如果要使用HttpRequestHandlerAdapter,必须显式地配置。如:<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"></bean>

这里使用的是SimpleControllerHandlerAdapter,配置如下:

<?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:mvc="http://www.springframework.org/schema/mvc"       xmlns:context="http://www.springframework.org/schema/context"       xmlns:aop="http://www.springframework.org/schema/aop"        xmlns:tx="http://www.springframework.org/schema/tx"       xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd        http://www.springframework.org/schema/mvc         http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd         http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context.xsd        http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd        http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx.xsd">    <!-- 配置处理器适配器:HandlerAdapter。所有处理器适配器都实现了HandlerAdapter接口-->    <!-- SimpleControllerHandlerAdapter适配器能执行实现了Controller接口的Handler。所以,现在配置了这个适配器的话,所有的处理器Handler必须要实现Controller接口才行。-->    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" /></beans>

四、配置处理器映射器

常用的处理器映射器也有两种,分别是BeanNameUrlHandlerMapping和SimpleUrlHandlerMapping。
(1)BeanNameUrlHandlerMapping,通过控制器(handler)的<bean>的name属性来匹配相应的控制器。配置如下:

<!-- 配置处理器映射器 --><!-- 将bean的name作为url进行查找,需要在配置Handler时指定bean name --><bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />

(2)SimpleUrlHandlerMapping是BeanNameUrlHandlerMapping的增强版本,它可以将url和控制器(handler)bean的id进行统一映射配置。如:

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">      <property name="mappings">          <props>              <!-- itemsController1为控制器的id属性,/queryItems1.action是URL -->              <prop key="/queryItems1.action">itemController1<prop/>              <prop key="/queryItems2.action">itemController1<prop/>          </props>      </property>  </bean>  

五、配置视图解析器

视图解析器可以指定前缀和后缀属性,这样一来,在handler中的view路径名可以缩短。配置如下所示:

<!-- 配置视图解析器 -->    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/WEB-INF/jsp/"></property>        <property name="suffix" value=".jsp"></property>    </bean>

这样一来,视图路径设置为return new ModelAndView("productForm");时,视图解析器将自动增加前缀和后缀,最终的视图的路径为/WEB-INF/jsp/productForm.jsp

六、编写控制器类

这个应用中,共编写了两个控制器类,如下:
InputProductController:

package controller;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.mvc.Controller;public class InputProductController implements Controller {    private final Log logger = LogFactory.getLog(InputProductController.class);    @Override    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {        // TODO Auto-generated method stub        logger.info("调用了InputProductController");        return new ModelAndView("productForm");    }}

SaveProductController:

package controller;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.mvc.Controller;import model.Product;public class SaveProductController implements Controller {    private final Log logger = LogFactory.getLog(SaveProductController.class);    @Override    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {        // TODO Auto-generated method stub        logger.info("调用SaveProductController");        request.setCharacterEncoding("UTF-8");        Product product = new Product();        product.setName(request.getParameter("name"));        product.setDescription(request.getParameter("description"));        product.setPrice(request.getParameter("price"));        return new ModelAndView("productDetails", "product", product);    }}

七、配置控制器(Handler)

这里直接将整个springmvc.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:mvc="http://www.springframework.org/schema/mvc"       xmlns:context="http://www.springframework.org/schema/context"       xmlns:aop="http://www.springframework.org/schema/aop"        xmlns:tx="http://www.springframework.org/schema/tx"       xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd        http://www.springframework.org/schema/mvc         http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd         http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context.xsd        http://www.springframework.org/schema/aop        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd        http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx.xsd">    <!-- 配置处理器适配器:HandlerAdapter。所有处理器适配器都实现了HandlerAdapter接口-->    <!-- SimpleControllerHandlerAdapter适配器能执行实现了Controller接口的Handler。所以,现在配置了这个适配器的话,所有的处理器Handler必须要实现Controller接口才行。-->    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />    <!-- 配置处理器映射器 -->    <!-- 将bean的name作为url进行查找,需要在配置Handler时指定beanname(就是url)-->    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />    <!-- 配置视图解析器 -->    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/WEB-INF/jsp/"></property>        <property name="suffix" value=".jsp"></property>    </bean>    <!-- 配置Handler -->    <bean name="/inputProduct" class="controller.InputProductController"></bean>    <bean name="/saveProduct" class="controller.SaveProductController"></bean></beans>

至此,需要配置的东西已经全部配置完毕。为了测试,还需要新建一个Product类和两个jsp页面,这里就不贴代码了,直接上一个项目的总体架构图:
这里写图片描述

启动tomcat,在浏览器中输入http://localhost:8080/Study_SpringMVC/inputProduct,就会跳到productForm.jsp页面,如下:
这里写图片描述

输入相应信息,点击提交后,将跳转到productDetails.jsp页面,并将输入的信息展示出来,如下:
这里写图片描述

如有错误之处,欢迎留言指正。

原创粉丝点击