SpringMVC学习笔记

图片描述

The request processing workflow in Spring Web MVC

官方文档说:The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale, time zone and theme resolution as well as support for uploading files. SpringMVC框架是围绕DispatchServlet设计的,可见其重要性。

Hello SpringMVC

通过配置文件开发

  • web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

如果不指定contextConfigLocation,则

Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there, overriding the definitions of any beans defined with the same name in the global scope.

  • springmvc-servlet

    <?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"
           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
    ">
        <!--配置HandlerMapping-->
        <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
        <!--配置Adapter-->
        <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
        <!--配置渲染器-->
        <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
            <!--结果示图的前缀、后缀-->
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    
        <bean name="/hello" class="org.spring.bin.HelloController"/>
    </beans>
  • HellController.java

    package org.spring.bin;
    
    import org.springframework.web.servlet.mvc.Controller;
    import org.springframework.web.servlet.ModelAndView;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class HelloController implements Controller{
        
        @Override
        public ModelAndView handlerRequest(HttpServletRequest req, HttpServletResponse resp){
            ModelAndView mv = new ModelAndView();
            //会根据在springmvc-servlet中配置的prefix、suffix来在/WEB-INF/jsp/hello.jsp
            mv.setViewName("hello");
            mv.addObject("msg", "hello springmvc");
            return mv;
        }
    }
  • /WEB-INF/jsp/hello.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>hello mySpringMVC</title>
    </head>
    <body>
       ${msg}
    </body>
    </html>

配置Tomcat,启动服务,在浏览器中请求host:port/hello即可

通过注解开发

web.xml、hello.jsp 参照《通过配置文件开发》

  • 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"
           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
    ">
        <context:component-scan base-package="org.spring.bin"/>
        <context:annotation-config />
        <!--配置渲染器-->
        <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
            <!--结果示图的前缀、后缀-->
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    </beans>
  • HelloController.java

package org.spring.bin;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@controller     
public class HelloController{
    
    @RequestMapping("/hello")
    public ModelAndView hello(HttpServletRequest req, HttpServletResponse resp){
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", "hello springmvc annotation");
        mv.setViewName("hello");
        return mv;
    }
} 

Controller配置汇总

1.通过URL对应Bean

<pre name="code" class="html"><!-- 配置HandlerMapping 根据beanname找对对应的controller -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
           <!-- 配置handleradapter -->
           <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
<span style="white-space:pre">    </span><!-- 配置controller -->
       <bean name="/hello.do" class="cn.com.jit.controller.HelloController"/>
以上配置访问/hello.do就会寻找ID为/hello.do的Bean,此类方式仅使用小型应用系统

2.为URL分配Bean

使用一个统一配置集合,对各个URL对应的Controller做关系映射

<!-- 最常用的 -->
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
           <property name="mappings">
               <props>
               <!-- key 对应URL请求名   value 对应处理器的ID-->
                   <prop key="/hello.do">hellocontroller</prop>
               </props>
           </property>
       </bean>
<bean id="hellocontroller" class="cn.com.jit.controller.HelloController"></bean>
此类配置还可以使用通配符,访问/hello.do时,Spring会把请求分配给helloController进行处理。

3.URL匹配Bean

如果定义的Conroller名称规范,也可以使用如下配置

<!-- 将hello*.do交给helloController去处理 --> 
<!-- 配置HandlerMapping 根据beanname找对对应的controller -->
       <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
           <!-- 配置controller  请求为hello*.do都将会被匹配 -->
       <bean name="/helloController" class="cn.com.jit.controller.HelloController"/>


4注解

 <!-- 配置springMVC 注解驱动 -->
       <mvc:annotation-driven/>
       <!-- 扫描器 -->
       <context:component-scan base-package="cn"></context:component-scan>
在controller中添加注解:
@Controller
@RequestMapping("/user")
public class UserController {
    
    /**
     * 时间编辑器
     */
     @InitBinder  
     public void initBinder(ServletRequestDataBinder binder) {  
         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
         //dateFormat.setLenient(false);  
         binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); 
        
    }
    
    @RequestMapping("/add1.do")
    public String add(HttpServletRequest request){
        
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("username:" + username + "---" + "password:" + password);
        
        return "user/user_list";
    }
    
    @RequestMapping("/add2.do")
    public String add2(String username, String password ){
        
        System.out.println("username:" + username + "-----" + "password:" + password);
        
        return "user/user_list";
    }
    
    @RequestMapping("/add3.do")
    public String add3(UserInfo userInfo){
        
        System.out.println(userInfo);
        
        return "user/user_list";
    }
    
    @RequestMapping("/add4.do")
    public String add4(String userName, Date date){
        
        System.out.println("username:" + userName + "---" + "date:" + date);
        
        return "user/user_list";
    }

}

菟潞寺沙弥
303 声望55 粉丝

引用和评论

0 条评论