SpringMVC入门

注:本文前面搭建部分引用Java大联盟,后部分是博主编写。本文最后附上Java大联盟二维码。

1.SpringMVC是什么?

SpringMVC是目前最好的实现MVC设计模式的框架,是Spring框架的一个分支产品,以SpringIOC容器为基础,并利用容器的特性来简化它的配置。SpringMVC相当于Spring的一个子模块,可以很好的和Spring结合起来进行开发,是JavaWeb开发者必须要掌握的框架。

2.SpringMVC能干什么?

实现了MVC设计模式,MVC设计模式是一种常用的软件架构方式:以Controller(控制层),Model(模型层),View(视图层)三个模块分离的形式来组织代码。

3.MVC流程

控制层接受到客户端请求,调用模型层生成业务数据,传递给视图层,将最终的业务数据和视图响应给客户端做展示SpringMVC就是对这套流程的封装,屏蔽掉很多底层代码,开放出接口,让开发者可以更加轻松快捷的完成基于MVC模式的Web开发。
这里写图片描述

4.SpringMVC实现原理

1.DispatcherServlet:前端控制器,是整个流程控制的核心,控制其他组件的执行,统一调度,降低组件之间的耦合性,相当于总指挥。
2.Handler:处理器,完成具体业务逻辑,相当于Servlet或Action。
3.HandlerMapping:DispatcherServlet接收到请求之后,通过HandlerMapping将不同的请求分发到不同的Handler。
4.HandlerInterceptor:处理器拦截器,是一个接口,如果我们需要做一些拦截处理,可以来实现这个接口。
5.HandlerExecutionChain:处理器执行链,包括两部分内容:Handler和HandlerInterceptor(系统会有一个默认的HandlerInterceptor,如果需要额外拦截处理,可以添加拦截器设置)。
6.HandlerAdapter:处理器适配器,Handler执行业务方法之前,需要进行一系列的操作包括表单数据的验证,数据类型的转换,将表单数据封装到JavaBean等等,这一系列的操作,都是由HandlerAdapter来完成,DispatcherServlet通过HandlerAdapter执行不同的Handler。
7.ModelAndView:装载了模型数据和视图信息,作为Handler的处理结果,返回给DispatcherServlet。
8.ViewResolver:视图解析器,DispatcherServlet通过它将逻辑视图解析成物理视图,最终将渲染结果响应给客户端。

以上就是SpringMVC的核心组件。那么这些组件之间是如何进行交互的呢?

我们来看SpringMVC的实现流程:

1.客户端请求被DispatcherServlet(前端控制器)接收。
2.根据HandlerMapping映射到Handler。
3.生成Handler和HandlerInterceptor(如果有则生成)。
4.Handler和HandlerInterceptor以HandlerExecutionChain的形式一并返回给DispatcherServlet。
5.DispatcherServlet通过HandlerAdapter调用Handler的方法做业务逻辑处理。
6.返回一个ModelAndView对象给DispatcherServlet。
7.DispatcherServlet将获取的ModelAndView对象传给ViewResolver视图解析器,将逻辑视图解析成物理视图View。
8.ViewResolver返回一个View给DispatcherServlet。
9.DispatcherServlet根据View进行视图渲染(将模型数据填充到视图中)。
10.DispatcherServlet将渲染后的视图响应给客户端。
这里写图片描述

如何使用?
看到上面的实现原理,大家可能会有这样的担心,SpringMVC如此众多的组件开发起来一定很麻烦吧?答案是否定的,SpringMVC使用起来非常简单,很多组件都由框架提供,作为开发者我们直接使用即可,并不需要自己手动编写代码,真正需要我们开发者进行编写的组件只有两个,Handler:处理业务逻辑, View:JSP做展示。

4.环境搭建

1.创建maven工程,创建pom.xml配置SpringMVC依赖jar包。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.hzit</groupId>
  <artifactId>SpringMVCMaven</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVCTest Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <dependencies>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
   </dependencies>

  <build>
    <finalName>SpringMVCTest</finalName>
  </build>
</project>

2.web.xml中配置SpringMVC的DispatcherServlet。

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>    
      <welcome-file-list>
           <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
              <param-name>contextConfigLocation</param-name>
              <!-- 指定springmvc.xml的路径 -->
              <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>

3.创建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: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="com.southwind.handler"></context:component-scan>

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

</beans>

自动扫描的类结合注解交给IOC容器来管理,视图解析器是SpringMVC底层的类,开发者只需要进行配置即可完成JSP页面的跳转,如何配置很简单,记住一条:目标资源路径=前缀+返回值+后缀。
比如DispatcherServlet返回index,配置文件中前缀是/,后缀是.jsp,代入上述公式:目标资源路径=/index.jsp。一目了然,不需要再解释。
4.创建Handler类。

@Controller
public class HelloHandler {

    @RequestMapping("/index")
    public String index(){
        System.out.println("执行index业务代码");
        return "index";
    }

}

直接在业务方法出添加注解@RequestMapping(“/index”),将URL请求index直接与index业务方法映射,使用起来非常方便。

5.启动tomcat,打开浏览器输入URL测试。
这里写图片描述
1.DispatcherServlet接收到URL请求index,结合@RequestMapping(“/index”)注解将该请求交给index业务方法。
2.执行index业务方法,控制打印日志,并返回”index”字符串。
3.结合springmvc.xml中的视图解析器配置,找到目标资源:/index.jsp,即根目录的index.jsp,将该jsp资源返回客户端完成响应。
SpringMVC环境搭建成功。


5.SpringMVC进阶部分
@Controller
@SessionAttributes(value= {"adress"})
public class SpringmvcHandler {

     /**
      * 简单示例
      * @return
      */
     @RequestMapping("/hello")
     public String helloworld2() {

         System.out.println("进入Hello world!");

         return "success";
     }



     /**
      * 控制器处理请求业务方法
      * public String 方法名称(){  
      *      方法体
      * }
      * 
      * String:当方法处理完之后,所返回逻辑视图的名称
      * params = {"name"} 单个请求参数
      * params = {"name != tom"} 请求参数中不能有name = tom
      * params = {"name","age"} 多个请求参数
      * params = {"name","age != 13"} 请求参数中不能有age = 13 且必须有name这个参数
      * params = {"name = tom","age != 13"} 请求参数中name必须等于tom age不能为13
      * 
      * URL: /hello?name=tom
      * 
      * 请求头 headers
      * headers={ "accept=text/html" }
      * 
      */
     @RequestMapping(value = "/hello" , method = RequestMethod.POST, params = {"name"}, headers={ "accept=text/html" })
     public String helloworld1() {

         System.out.println("进入Hello world!");

         return "success";
     }

     /**
      * 
      * @PathVariable 可以将URL中的占位符参数绑定到控制器处理方法的入参中
      * URL: /PathVar/12
      * value 可以省略
      */
     @RequestMapping("testPathVar/{id}")
     public String testPathVar(@PathVariable(value = "id") Integer id){
        System.out.println("id = "+id);
        //userDao.delete(id);
        return "success";   
     }



     /**
      * 四种请求
      * 
      * GET表示获取资源  
      * POST用来新建资源 
      * PUT用来更新资源
      * DELETE用来删除资源
      * 
      */
     @RequestMapping(value = "testGet/{id}", method = RequestMethod.GET )
     public String testGet(@PathVariable("id") Integer id) {

         System.out.println("ID为"+id+"正在用get方式请求资源......");

         return "success";
     }

     /**
      * 
      * POST方式
      * 
      */
     @RequestMapping(value = "testPost", method = RequestMethod.POST )
     public String testGet() {

         System.out.println("正在用psot方式新建资源......");

         return "success";
     }

     /**
      * DELETE请求参数
      */
     @RequestMapping(value = "testDelete/{id}", method = RequestMethod.DELETE )
     public String testDelete(@PathVariable("id") Integer id) {

         System.out.println("ID为"+id+"正在用delete方式删除资源......");

         return "success";
     }


     /**
      * PUT请求参数
      */
     @RequestMapping(value = "testPut/{id}", method = RequestMethod.PUT)
     public String testPut(@PathVariable("id") Integer id) {

         System.out.println("ID为"+id+"正在用put方式更新资源......");

         return "success";
     }

     /**
      * 测试@RequestParam
      * SpringMVC是通过处理方法的请求参数进行绑定形参声明前面
      * 加入@RequestParam(value = "前端空间name的属性值")
      */
     @RequestMapping(value = "/testRequestParam")
     public String testRequestParam(@RequestParam(value = "id") Integer id,
                      @RequestParam(value = "name") String name) {

         System.out.println("@RequestParam 获取前端请求id:"+id);
         System.out.println("@RequestParam 获取前端请求name:"+name);

         return "success";
     }

     /**
      * 前端和接受参数名称一致可以省略注解
      * 如果一致,必须进行用value关联
      */
     @RequestMapping(value = "/testRequestParam2")
     public String testRequestParam2(Integer id,String name) {

         System.out.println("@RequestParam 获取前端请求id:"+id);
         System.out.println("@RequestParam 获取前端请求name:"+name);

         return "success";
     }

     /**
      *POJO属性绑定参数
      */
     @RequestMapping(value = "/testRequestParamPOJO")
     public String testRequestParamPOJO(User u) {

         System.out.println("@RequestParam 获取前端请求POJO-user:"+ u.toString());

         return "success";
     }

     /**
      *获取请求头中的参数信息
      */
     @RequestMapping(value = "/testRequestHeader")
     public String testRequestHeader(@RequestHeader("Accept") String accept,@RequestHeader("User-Agent") String Useragent) {

         System.out.println("@RequestHeader 获取请求头Accept:"+ accept);
         System.out.println("@RequestHeader 获取请求头User-Agent:"+ Useragent);

         return "success";
     }


     /**
      *获取请求头中的参数信息
      *CookieValue
      */
     @RequestMapping(value = "/testCookieValue")
     public String testCookieValue(@CookieValue("JSESSIONID") String id) {

         System.out.println("@CookieValue 获取CookieValue:"+ id);

         return "success";
     }

     /**
      * servlet API 对象
      * 
      * HttpServletRequest
      * HttpServletResponse  
      * HttpSession  
      * java.security.Principal  
      * locale 本地对象
      * inputStream
      * outputStream
      * Reader
      * Writer
      * 
      */
     @RequestMapping(value = "/testServletAPI")
     public String testServletAPI(HttpServletRequest request,HttpServletResponse reponse,HttpSession session) {

         System.out.println("testServletAPI request:"+request);
         System.out.println("testServletAPI reponse:"+reponse);
         System.out.println("testServletAPI session:"+session);

         return "success";
     }

     /**
      * ModelAndView
      * @return
      */
     @RequestMapping(value = "/testModelAndView")
     public ModelAndView testModelAndView() {

         ModelAndView mv =  new ModelAndView();

         //mv.setView("");  设置视图名称
         mv.setViewName("success");
         //设置参数  模型数据中的值是放到request中的
         //addObject 参数String  obj
         //addObjects 参数Map map
         mv.addObject("name","tom");


         return mv;
     }


     /**
      * testMap
      * @return
      */
     @RequestMapping(value = "/testMap")
     public String testMap(Map<String, Object> map) {

         map.put("age", "18");

         return "success";
     }



     /**
      * testModel
      * @return
      */
     @RequestMapping(value = "/testModel")
     public String testModel(Model model) {

         model.addAttribute("email", "abc@qq.com");
         return "success";
     }


     /**
      * testModelMap
      * @return
      */
     @RequestMapping(value = "/testModelMap")
     public String testModelMap(ModelMap modelMap) {

         modelMap.addAttribute("adress", "adress");
         return "success";
     }



     /**
      * testSessionAttributes
      * 在类上面标注@SessionAttributes
      * 示例: @SessionAttributes(value= {"adress"})
      * 这个adresss数据必须存在域中 resques范围中有效
      * 示例:@SessionAttributes(types= {String.class})
      * 表示将模型中所有String 施行共享
      */
     @RequestMapping(value = "/testSessionAttributes")
     public String testSessionAttributes() {

         return "result";
     }


     /**
      * ModelAttribute
      * @param account
      * @return
      */

     @RequestMapping(value = "/testModelAttribute")
     public String testModelAttributes(@ModelAttribute("abc")Account account) {

         System.out.println("testModelAttributes account:"+account.toString());

         return "success";
     }


     /**
      * @ModelAttribute 
      * 设置请求之前回去数据库查询数据和进行比对
      * @param map
      */
     @ModelAttribute(value="abc") //用来指定map中的key
     public Account start(Map<String, Object> map) {

         //假设是从数据库中取出的对象进行更新
         Account account = new Account(100, "tomJ", "2016-10-10");
         //设置进modelMap中   如果不设置@ModelAttribute account必须和上面参数一样 否则必须要进行绑定设置
         map.put("account", account);

         return account;

     }

     /**
      * 测试国际化让请求进入DisPatchServlet
      * @return
      */
     @RequestMapping(value = "/internationalization")
     public String internationalization() {
         return "internationalization";
     }


     @RequestMapping(value = "/toTime")
     public String toTime() {

         System.out.println("时间验证成功......");
         return "success";
     }

     /**
      * 用Ajax测试数据的接受的响应
      * @param user
      * @return
      */
     @RequestMapping(value = "/ajax")
     @ResponseBody
     public User ajax(User user){
         System.out.println("进入ajax........");
         System.out.println("user:"+user.toString());
         return user;
     }


     /**
      * 用Ajax测试数据的接受的响应
      * @param user
      * @return
      */
     @RequestMapping(value = "/ajaxs")
     @ResponseBody
     public User ajaxs(User user){
         System.out.println("进入ajaxs........");
         System.out.println("user:"+user.toString());
         return user;
     }

}

注解部分说明
@RequestMapping(value = “”) 如果只有一个value, value可以省略
@RequestMapping 除了可以修饰方法之外,还可以修饰类

@RequestMapping 还支持Ant风格的URL
/user/*/hello 匹配 /user/aaa/hello URL
/user/**/hello 匹配 /user/aa/bb/hello URL 0个或多个路径
/user/hello? 匹配/user/helloa URL
Ant风格的请求映射
Ant风格资源地址支持3中匹配符
?:匹配文件名中的一个字符
*:匹配文件名中的任意字符
**:匹配多层路径

@PathVariable 映射URL绑定的占位符,带占位符的URL是Spring3.0新增加功能,该功能在SpringMVC 向REST目标挺
近发展过程中具有里程碑意义

-通过@PathVariable可以将URL中的占位符参数绑定到
控制器处理方法的入参中

示例:

@RequestMapping("delete/{id}")
public String delete(@PathVariable("id") Integer id){
   userDao.delete(id);
   return "success"; 
}

REST风格 资源表现层状态转化,是目前最流行的一种互联网软件架构,它结构清晰,符合标准,易于理解,扩展方便,所以现在得到越来越多的网站的采用
资源 表现层 状态转换
具体点说及时 HTTP协议里面
GET:表示获取资源
POST:用来新建资源
PUT:用来更新资源
DELETE:用来删除资源
web只提供get post 但是rest风格是四种 HiddenHttpMethodFilter:过滤器,可以过滤我们所有的请求
,并且可以将请求细分为四种

public class HiddenHttpMethodFilter extends OncePerRequestFilter {

    /** Default method parameter: {@code _method} */
    public static final String DEFAULT_METHOD_PARAM = "_method";

    private String methodParam = DEFAULT_METHOD_PARAM;


    /**
     * Set the parameter name to look for HTTP methods.
     * @see #DEFAULT_METHOD_PARAM
     */
    public void setMethodParam(String methodParam) {
        Assert.hasText(methodParam, "'methodParam' must not be empty");
        this.methodParam = methodParam;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        String paramValue = request.getParameter(this.methodParam);
        if ("POST".equals(request.getMethod()) && StringUtils.hasLength(paramValue)) {
            String method = paramValue.toUpperCase(Locale.ENGLISH);
            HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method);
            filterChain.doFilter(wrapper, response);
        }
        else {
            filterChain.doFilter(request, response);
        }
    }


    /**
     * Simple {@link HttpServletRequest} wrapper that returns the supplied method for
     * {@link HttpServletRequest#getMethod()}.
     */
    private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {

        private final String method;

        public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
            super(request);
            this.method = method;
        }

        @Override
        public String getMethod() {
            return this.method;
        }
    }

}

浏览器只支持GET POST
GET 直接去找GET
POST 寻找请求参数,是否还有一个名字_method这样的请求方式,
DELETE,PUT请求如果没有,就是post

@RequestParam 绑定请求参数值

在处理方法入参处使用@RequestParam 可以把请求参数传递给请求方法

–value :请求名
–required :是否必须 默认为True,表示请求参数中必须包含对应的参数,若不存在,将
抛出异常

SpringMVC是通过处理方法的请求参数进行绑定形参声明前面,加入@RequestParam(value = “前端空间name的属性值”)
如果形参一致 则可以省略

POJO对象绑定属性值
前端name和属性名称一致,如果user里面有个属性引用其他对象,则
前端name用级联方式命名 比如 adress.city
@RequestHeader绑定请求爆头的属性值
请求头包含了若干个属性,服务器可据此获知客户端的信息
通过@requestHeader即可将请求头中的属性值绑定到处理
方法的入参中

     /**
      * 控制器处理请求业务方法
      * public String 方法名称(){  
      *      方法体
      * }
      * 
      * String:当方法处理完之后,所返回逻辑视图的名称
      * params = {"name"} 单个请求参数
      * params = {"name != tom"} 请求参数中不能有name = tom
      * params = {"name","age"} 多个请求参数
      * params = {"name","age != 13"} 请求参数中不能有age = 13 且必须有name这个参数
      * params = {"name = tom","age != 13"} 请求参数中name必须等于tom age不能为13
      * 
      * URL: /hello?name=tom
      * 
      * 请求头 headers
      * headers={ "accept=text/html" }
      * 
      */
     @RequestMapping(value = "/hello" , method = RequestMethod.POST, params = {"name"}, headers={ "accept=text/html" })
     public String helloworld1() {

         System.out.println("进入Hello world!");

         return "success";
     }

@CookieValue绑定请求中的Cookie值

/**
      * servlet API 对象
      * 
      * HttpServletRequest
      * HttpServletResponse  
      * HttpSession  
      * java.security.Principal  
      * locale 本地对象
      * inputStream
      * outputStream
      * Reader
      * Writer
      * 
      */
     @RequestMapping(value = "/testServletAPI")
     public String testServletAPI(HttpServletRequest request,HttpServletResponse reponse,HttpSession session) {

         System.out.println("testServletAPI request:"+request);
         System.out.println("testServletAPI reponse:"+reponse);
         System.out.println("testServletAPI session:"+session);

         return "success";
     }

@SessionAttributes:将模型中的某个属性值暂存到HttpSession中,一边多个请求之间可以共享这个属性

若希望在多个请求之间公用某个模型属性数据,则可以在控制器类上
标注一个@SessionAttributes,SpringMVC将模型中对应的属性暂时
存在HttpSession中
-@SessionAttributes除了可以通过属性名指定需要放到会话中的属性外
还可以通过属性模型对象类型指定哪些模型属性需要放到会话中

-@SessionAttributes(types=User.class)会将隐含模型中所有类型为User.class的属性添加到会话中.
-@SessionAttributes(value={“user1”,”user2”})
-@SessionAttributes(types={User.class,Dept.class})
-@SessionAttributes(value={“user1”,”user2”},types={Depts.calss})


下面直接贴出代码,每个功能都有想用解释(Jar包自己百度下载)

Controller

package com.springmvc.handler;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.springmvc.domain.Account;
import com.springmvc.domain.User;

@Controller
@SessionAttributes(value= {"adress"})
public class SpringmvcHandler {

     /**
      * 简单示例
      * @return
      */
     @RequestMapping("/hello")
     public String helloworld2() {

         System.out.println("进入Hello world!");

         return "success";
     }



     /**
      * 控制器处理请求业务方法
      * public String 方法名称(){  
      *      方法体
      * }
      * 
      * String:当方法处理完之后,所返回逻辑视图的名称
      * params = {"name"} 单个请求参数
      * params = {"name != tom"} 请求参数中不能有name = tom
      * params = {"name","age"} 多个请求参数
      * params = {"name","age != 13"} 请求参数中不能有age = 13 且必须有name这个参数
      * params = {"name = tom","age != 13"} 请求参数中name必须等于tom age不能为13
      * 
      * URL: /hello?name=tom
      * 
      * 请求头 headers
      * headers={ "accept=text/html" }
      * 
      */
     @RequestMapping(value = "/hello" , method = RequestMethod.POST, params = {"name"}, headers={ "accept=text/html" })
     public String helloworld1() {

         System.out.println("进入Hello world!");

         return "success";
     }

     /**
      * 
      * @PathVariable 可以将URL中的占位符参数绑定到控制器处理方法的入参中
      * URL: /PathVar/12
      * value 可以省略
      */
     @RequestMapping("testPathVar/{id}")
     public String testPathVar(@PathVariable(value = "id") Integer id){
        System.out.println("id = "+id);
        //userDao.delete(id);
        return "success";   
     }



     /**
      * 四种请求
      * 
      * GET表示获取资源  
      * POST用来新建资源 
      * PUT用来更新资源
      * DELETE用来删除资源
      * 
      */
     @RequestMapping(value = "testGet/{id}", method = RequestMethod.GET )
     public String testGet(@PathVariable("id") Integer id) {

         System.out.println("ID为"+id+"正在用get方式请求资源......");

         return "success";
     }

     /**
      * 
      * POST方式
      * 
      */
     @RequestMapping(value = "testPost", method = RequestMethod.POST )
     public String testGet() {

         System.out.println("正在用psot方式新建资源......");

         return "success";
     }

     /**
      * DELETE请求参数
      */
     @RequestMapping(value = "testDelete/{id}", method = RequestMethod.DELETE )
     public String testDelete(@PathVariable("id") Integer id) {

         System.out.println("ID为"+id+"正在用delete方式删除资源......");

         return "success";
     }


     /**
      * PUT请求参数
      */
     @RequestMapping(value = "testPut/{id}", method = RequestMethod.PUT)
     public String testPut(@PathVariable("id") Integer id) {

         System.out.println("ID为"+id+"正在用put方式更新资源......");

         return "success";
     }

     /**
      * 测试@RequestParam
      * SpringMVC是通过处理方法的请求参数进行绑定形参声明前面
      * 加入@RequestParam(value = "前端空间name的属性值")
      */
     @RequestMapping(value = "/testRequestParam")
     public String testRequestParam(@RequestParam(value = "id") Integer id,
                      @RequestParam(value = "name") String name) {

         System.out.println("@RequestParam 获取前端请求id:"+id);
         System.out.println("@RequestParam 获取前端请求name:"+name);

         return "success";
     }

     /**
      * 前端和接受参数名称一致可以省略注解
      * 如果一致,必须进行用value关联
      */
     @RequestMapping(value = "/testRequestParam2")
     public String testRequestParam2(Integer id,String name) {

         System.out.println("@RequestParam 获取前端请求id:"+id);
         System.out.println("@RequestParam 获取前端请求name:"+name);

         return "success";
     }

     /**
      *POJO属性绑定参数
      */
     @RequestMapping(value = "/testRequestParamPOJO")
     public String testRequestParamPOJO(User u) {

         System.out.println("@RequestParam 获取前端请求POJO-user:"+ u.toString());

         return "success";
     }

     /**
      *获取请求头中的参数信息
      */
     @RequestMapping(value = "/testRequestHeader")
     public String testRequestHeader(@RequestHeader("Accept") String accept,@RequestHeader("User-Agent") String Useragent) {

         System.out.println("@RequestHeader 获取请求头Accept:"+ accept);
         System.out.println("@RequestHeader 获取请求头User-Agent:"+ Useragent);

         return "success";
     }


     /**
      *获取请求头中的参数信息
      *CookieValue
      */
     @RequestMapping(value = "/testCookieValue")
     public String testCookieValue(@CookieValue("JSESSIONID") String id) {

         System.out.println("@CookieValue 获取CookieValue:"+ id);

         return "success";
     }

     /**
      * servlet API 对象
      * 
      * HttpServletRequest
      * HttpServletResponse  
      * HttpSession  
      * java.security.Principal  
      * locale 本地对象
      * inputStream
      * outputStream
      * Reader
      * Writer
      * 
      */
     @RequestMapping(value = "/testServletAPI")
     public String testServletAPI(HttpServletRequest request,HttpServletResponse reponse,HttpSession session) {

         System.out.println("testServletAPI request:"+request);
         System.out.println("testServletAPI reponse:"+reponse);
         System.out.println("testServletAPI session:"+session);

         return "success";
     }

     /**
      * ModelAndView
      * @return
      */
     @RequestMapping(value = "/testModelAndView")
     public ModelAndView testModelAndView() {

         ModelAndView mv =  new ModelAndView();

         //mv.setView("");  设置视图名称
         mv.setViewName("success");
         //设置参数  模型数据中的值是放到request中的
         //addObject 参数String  obj
         //addObjects 参数Map map
         mv.addObject("name","tom");


         return mv;
     }


     /**
      * testMap
      * @return
      */
     @RequestMapping(value = "/testMap")
     public String testMap(Map<String, Object> map) {

         map.put("age", "18");

         return "success";
     }



     /**
      * testModel
      * @return
      */
     @RequestMapping(value = "/testModel")
     public String testModel(Model model) {

         model.addAttribute("email", "abc@qq.com");
         return "success";
     }


     /**
      * testModelMap
      * @return
      */
     @RequestMapping(value = "/testModelMap")
     public String testModelMap(ModelMap modelMap) {

         modelMap.addAttribute("adress", "adress");
         return "success";
     }



     /**
      * testSessionAttributes
      * 在类上面标注@SessionAttributes
      * 示例: @SessionAttributes(value= {"adress"})
      * 这个adresss数据必须存在域中 resques范围中有效
      * 示例:@SessionAttributes(types= {String.class})
      * 表示将模型中所有String 施行共享
      */
     @RequestMapping(value = "/testSessionAttributes")
     public String testSessionAttributes() {

         return "result";
     }


     /**
      * ModelAttribute
      * @param account
      * @return
      */

     @RequestMapping(value = "/testModelAttribute")
     public String testModelAttributes(@ModelAttribute("abc")Account account) {

         System.out.println("testModelAttributes account:"+account.toString());

         return "success";
     }


     /**
      * @ModelAttribute 
      * 设置请求之前回去数据库查询数据和进行比对
      * @param map
      */
     @ModelAttribute(value="abc") //用来指定map中的key
     public Account start(Map<String, Object> map) {

         //假设是从数据库中取出的对象进行更新
         Account account = new Account(100, "tomJ", "2016-10-10");
         //设置进modelMap中   如果不设置@ModelAttribute account必须和上面参数一样 否则必须要进行绑定设置
         map.put("account", account);

         return account;

     }

     /**
      * 测试国际化让请求进入DisPatchServlet
      * @return
      */
     @RequestMapping(value = "/internationalization")
     public String internationalization() {
         return "internationalization";
     }


     @RequestMapping(value = "/toTime")
     public String toTime() {

         System.out.println("时间验证成功......");
         return "success";
     }

     /**
      * 用Ajax测试数据的接受的响应
      * @param user
      * @return
      */
     @RequestMapping(value = "/ajax")
     @ResponseBody
     public User ajax(User user){
         System.out.println("进入ajax........");
         System.out.println("user:"+user.toString());
         return user;
     }


     /**
      * 用Ajax测试数据的接受的响应
      * @param user
      * @return
      */
     @RequestMapping(value = "/ajaxs")
     @ResponseBody
     public User ajaxs(User user){
         System.out.println("进入ajaxs........");
         System.out.println("user:"+user.toString());
         return user;
     }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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">


    <display-name>SpringMVC_01</display-name>

    <!-- Spring MVC servlet -->  
    <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:spring-mvc.xml</param-value>  
                </init-param>  

               <!-- 
                                        在servlet的配置当中,<load-on-startup>5</load-on-startup>的含义是:
                标记容器是否在启动的时候就加载这个servlet。
                当值为0或者大于0时,表示容器在应用启动时就加载这个servlet;
                当是一个负数时或者没有指定时,则指示容器在该servlet被选择时才加载。
                正数的值越小,启动该servlet的优先级越高。
              -->     
              <load-on-startup>1</load-on-startup>  

              <!-- 在spring mvc3.2及以上版本增加了对请求的异步处理,是在servlet3的基础上进行封装的。 -->
              <async-supported>true</async-supported>  

    </servlet>  

    <servlet-mapping>  
        <servlet-name>SpringMVC</servlet-name>  
        <!-- 接受所有用户请求 注意这里是 / 不是  /*-->  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  

    <!-- delete put REST风格请求过滤器 -->
    <filter>
       <filter-name>hiddenHttpMethodFilter</filter-name>
       <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
       <filter-name>hiddenHttpMethodFilter</filter-name>
       <url-pattern>/*</url-pattern>
    </filter-mapping>



  <!-- 欢迎页面,初始页面 -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Sping-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:p="http://www.springframework.org/schema/p"  
    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-4.0.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd            
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx.xsd">  


  <!-- 
     <mvc:annotation-driven>作用帮我们取注册一个
     ResquestHandlerMapping,完成我们的映射
     RequestMappingHandlerAdapter, 获取请求参数以及绑定
     ExceptionHandlerExceptionResolver 异常
     <mvc:default-servlet-handler/>提供了默认Servlet控制器,其他的失效
     <mvc:annotation-driven>会帮我们注册三个常用bean

             如果都没有配置,默认会去注册RequestMappingHandlerAdapter
   -->                       
   <!-- 静态资源的处理 -->                   
   <!-- 让DisPatchServlet控制器失效,所有URL也失效 -->  
   <mvc:default-servlet-handler/>      
   <!-- 这个是让其他的URL有效,配合上面的使用进行静态资源设置 -->
   <mvc:annotation-driven></mvc:annotation-driven>      


   <!--  扫描注解 -->   
   <context:component-scan base-package="com.springmvc.*"></context:component-scan>                  
   <!-- 视图解析器   定义跳转的文件的前后缀 ,视图模式配置-->                
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->  
        <property name="prefix" value="/" />  
        <property name="suffix" value=".jsp" />  
    </bean>  


   <!-- a标签选择国际化 -->
   <bean id="SessionLocaleResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
   <!-- a标签选择国际化 配合使用-->
   <mvc:view-controller path="/globalA" view-name="global"/>
   <!-- 国际化 -->
   <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <!-- abc 是配置文件的前缀名称   -->
        <property name="basename" value="abc"></property>
   </bean>  


   <!-- 自定义命名空间 -->
   <!-- 
      URL : http://localhost:8080/SpringMVC_01/thecustom  直接映射到internationalization.jsp页面
              注意    : 如果配置了自定义视图路径,那么控制器中的所有映射将无效 直接抛出404
                              如果想要两种都可以运行,必须配置<mvc:annotation-driven></mvc:annotation-driven>
            <mvc:annotation-driven>是spring3.0之后增加的
    -->
   <mvc:view-controller path="/thecustom" view-name="internationalization"/>
   <!--  这个是配置自己自定义视图解析器解析路径    -->
   <mvc:view-controller path="/thecustomView" view-name="thecustomView"/>
   <mvc:annotation-driven></mvc:annotation-driven>


   <!--  配置自定义视图解析器    --> 
   <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
      <!-- roder 视图解析器的优先级,值越小优先级越高,反之 -->
      <property name="order" value="100"></property>
   </bean>



   <!-- 自定义拦截器 -->
   <mvc:interceptors>

      <!-- a标签选择国际化资源拦截器,配合下面  SessionLocaleResolver 使用 且这个拦截器是拦截所有 -->
      <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean> 


      <!-- mvc:interceptor 是一个关于拦截器的声明,mvc:mapping指定配置所有拦截器要拦截的资源-->
      <!-- 
                          如果拦截所有请求<mvc:interceptor>去掉即可<mvc:interceptors>直接放入<bean id="interceptor"....
          <mvc:mapping... 和  <mvc:interceptor> 删除即可。
       -->
      <mvc:interceptor>
         <mvc:mapping path="/toTime"/>
         <bean id="interceptor" class=" com.springmvc.interceptor.Interceptor"></bean>
      </mvc:interceptor>
   </mvc:interceptors>



</beans>  

个人demo链接:https://download.csdn.net/download/weixin_40263776/10280308
友情链接:这里写图片描述
如有不对,还望指正

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值