SpringMVC中使用DispatcherServlet

接触Web开发的时候我们会利用Servlet来接收和转发前端页面的各种请求,我们通常会在一个页面中对应一个Servlet来处理这个页面上和用户交互的信息,通常我门遇到5个以内的页面自己来写Servlet的时候我们会很容易的写出来,但是当一个项目由几十个页面的时候,我们会不停的重复写上几十个功能基本相近,代码基本相同的Servlet,显然这种工作是非常不必要的。

在使用框架开发Web项目的时候,Spring会给开发者一个Spring自带的Servlet,这个Servlet不需要用户自己写,直接使用即可,这样大大减少了大量的重复代码。这里,Spring为我们提供的Servlet的全名为:org.springframework.web.servlet.DispatcherServlet。

当我们使用Spring提供的Servlet的时候,我们的配置文件如下:

web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xmlns
="http://xmlns.jcp.org/xml/ns/javaee"
      xsi:schemaLocation
="http://xmlns.jcp.org/xml/ns/javaee
        http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

      id
="WebApp_ID" version="3.1"> 3 <display-name>TestWeb</display-name> 4 <welcome-file-list> 5 <welcome-file>index.html</welcome-file> 6 <welcome-file>index.htm</welcome-file> 7 <welcome-file>index.jsp</welcome-file> 8 <welcome-file>default.html</welcome-file> 9 <welcome-file>default.htm</welcome-file> 10 <welcome-file>default.jsp</welcome-file> 11 </welcome-file-list> 12 13 <servlet> 14 <servlet-name>springmvc</servlet-name> 15 <servlet-class> 16 org.springframework.web.servlet.DispatcherServlet 17 </servlet-class> 18 <load-on-startup>1</load-on-startup> 19 </servlet> 20 21 <servlet-mapping> 22 <servlet-name>springmvc</servlet-name> 23 <url-pattern>/</url-pattern> 24 </servlet-mapping> 25 26 </web-app>

spring的配置文件命名为springmvc-servlet.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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    
    <bean name="/product_input.action"
        class="app03a.controller.InputProductController"/>
    <bean name="/product_save.action"
        class="app03a.controller.SaveProductController"/>
    
</beans>

这里我设置了两个测试类来处理View发送来的数据,设置的两个类分别对应了两个action。

在使用spring中的Servlet的时候要记住这个框架是要有commons logging组件的。

========================================================

欢迎各位转载。 注意:转载请注明出处。
原文地址:https://www.cnblogs.com/Summer7C/p/4676923.html