【SpringMVC】---RequestMapping、Ant 路径、PathVariable 注解、HiddenHttpMethodFilter 过滤器、用 POJO 作为参数

一、web.xml

<?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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SpringMVC_001_001</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>
      <!-- springDispatcherServlet 在应用启动的时候被创建,不是调用的时候被创建。 -->
      <!-- 实际上也可以不通过 contextConfigLocation 来配置 springmvc 的配置文件,而使用默认的。 -->
    <!-- 默认的配置文件为:/WEB-INF/<servlet-name>-servlet.xml -->
    <!-- 把 SRC 下的 spring-mvc.xml 移动在/WEB-INF/下并改名为 springDispatcherServlet-servlet.xml的文件,并注释 R20~R23 -->
    <!--配置 DispatcherServlet 初始化参数,作用是配置 SpringMVC 配置文件的位置和名称-->
    
    <servlet-name>springDispatcherServlet</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>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
      <!-- 将所有请求映射到DispatcherServlet处理 -->
      
  <servlet-mapping>
  
      <!--配置 DispatcherServlet 初始化参数,作用是配置 SpringMVC 配置文件的位置和名称-->
    <servlet-name>springDispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 配置HiddenHttpMethodFilter,可以把POST请求转换为DELETE或PUT请求 -->
  <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>
</web-app>

二、HelloWorld.java

package com.chinasofti.springmvc.handlers;

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.chinasofti.springmvc.entity.User;


@Controller
@RequestMapping(value="/springmvc")
public class HelloWorld {
    /**
     * 1、使用 RequestMapping 注解来映射请求的 URL(统一资源定位)
     * 2、返回值会通过视图解析器解析为实际的物理视图,对于 InternalResourceViewResolver 而言,
     * 视图解析器会做如下的解析:
     * 2.1、通过 prefix + returnVal + 后缀这样的方式得到实际的物理视图,然后做转发操作。
     * 如:/WEB-INF/views/success.jsp
     * @return
     */

    public static final String SUCCESS="success";

    /*
     * 测试跳换页面
     */
    @RequestMapping("/helloword")
    public String hello(){
        System.out.println("hello word");
        return SUCCESS;
        }
    
    /*
     * 测试Post提交
     */
    @RequestMapping(value="/helloword",method=RequestMethod.POST)
    public String testPost(){
        System.out.println("hello word");
        return SUCCESS;
        }
    
    
    /*
     * 测试Params参数 params表示要传递的参数,username表示传递的第一个参数,值不确定,第二个参数是
    age并且年龄不能是等于10的
     * */
    @RequestMapping(value="testParamaAndHeaders",params={"username","age!=10"},
            headers={"Accept-Language=zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"})
    public String testParamaAndHeaders(){
        System.out.println("testParamaAndHeaders");
        return SUCCESS;
    }
    
    
    /*
    * 测试Ant格式请求路径
    * */
    @RequestMapping(value="testAnt/*/abc",params={"username","age!=10"},
            headers={"Accept-Language=zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"})
    public String testAnt(){
    System.out.println("testAntPath");
    return SUCCESS;
    }
    
    
    /*
    * @PathVariable可以映射URL中的占位符到目标方法中
    */
    @RequestMapping("/testPathVariable/{id}")
    public String testPathVariable(@PathVariable("id") Integer id){
    System.out.println("testPathVariable:"+id);
    return SUCCESS;
    }
    
    
    /*
     *测试GET方法 --------------》查
     */
    @RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET)
    public String testRest(@PathVariable Integer id) {
    System.out.println("testRest GET:" + id);
    return SUCCESS;
    }
    
    // POST是新增,没有参数。------》增
    @RequestMapping(value = "/testRest", method = RequestMethod.POST)
    public String testRest() {
    System.out.println("testRest POST");
    return SUCCESS;
    }
    /*
     * 测试DELETE方法-----------》删
     */
    @RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE)
    public String testDeleteRest(@PathVariable Integer id) {
    System.out.println("testRest DELETE:" + id);
    return SUCCESS;
    }
    /*
     * 测试PUT方法--------------》改
     */
    @RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT)
    public String testPutRest(@PathVariable Integer id) {
    System.out.println("testRest PUT:" + id);
    return SUCCESS;
    }
    
    /*
     * 测试POJO
     */
    @RequestMapping("/testPojo")
    public String testPojo(User user){
    System.out.println(user.getUsername()+"	"+user.getPassword()+"	"+user.getEmail()+"	"+user.getAge()
    +"	"+user.getAddress().getProvince()+"	"+user.getAddress().getCity());
    return SUCCESS;
    }
    
    /*
     * 使用 Servlet 原生 API 作为参数
     *  **HttpServletRequest
    *     **HttpServletResponse
    *    **HttpSession
    *    Java.security.Principal
    *    Locale
    *    InputStream
    *    OutputStream
    *    Reader
    *    Writer
     */
    @RequestMapping("/testServletAPI")
    public String testServletAPI(HttpServletRequest request,HttpServletResponse response){
    System.out.println("ServletAPI:"+request+"	
"+response);
    return SUCCESS;
    }
}

三、Address

package com.chinasofti.springmvc.entity;

public class Address {
    private String province;
    private String city;
    public String getProvince() {
        return province;
    }
    public void setProvince(String province) {
        this.province = province;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    @Override
    public String toString() {
        return "Address [province=" + province + ", city=" + city + "]";
    }
}

User类

package com.chinasofti.springmvc.entity;

public class User {
    private String username;
    private String password;
    private String email;
    private Integer age;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }

    private Address address;
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "User [username=" + username + ", password=" + password + ", email=" + email + ", age=" + age
                + ", address=" + address + "]";
    }
}

四、spring-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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    
    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.chinasofti"></context:component-scan>

    <!-- 配置视图解析器:如何把 handler 方法返回值解析为实际的物理视图 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
</beans>

五、success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
测试成功!
</body>
</html>

六、index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

    <a href="springmvc/helloword">跳转页面</a>
    <br/>
    <br/>
    <hr />
    <form action="springmvc/helloword" method="post">
        <input type="submit" value="POST提交">
    </form>
    <br/>
    <hr />
    <a href="springmvc/testParamaAndHeaders?username='huazai'&age=11">测试params</a>
    <br/>
    <br/>
    <hr />
    <a href="springmvc/testAnt/xxxxxxxx/abc?username=huazai&age=11">测试Ant请求路径</a>
    <br/>
    <br/>
    <hr />
    <a href="springmvc/testPathVariable/11">测试PathVariable 注解请求路径</a>
    <br/>
    <br/>
    <br/>
    <hr />
    <form action="springmvc/testRest/1" method="post">
        <input type="hidden" name="_method" value="DELETE"> 
        <input type="submit" value="Test Rest DELETE">
    </form>
    <hr />
    <form action="springmvc/testRest/1" method="post">
        <input type="hidden" name="_method" value="PUT"> 
        <input type="submit" value="Test Rest PUT">
    </form>
    <hr />
    <form action="springmvc/testRest" method="post">
        <input type="submit" value="Test Rest Post">
    </form>
    <hr>
    <a href="springmvc/testRest/1">Test Rest Get</a>
    <hr>
    <form action="springmvc/testPojo" method="post">
        username:<input type="text"     value="" name="username"><br/>
        password:<input type="password" value="" name="password"><br/>
        email:   <input type="text"     value="" name="email"><br/>
        age:     <input type="text"     value="" name="age"><br/>
        province:<input type="text"     value="" name="address.province"><br/>
        city:     <input type="text"     value="" name="address.city"><br/>
                 <input type="submit"     value="gogogo">
    </form>
    <hr>
    <a href="springmvc/testServletAPI">testServletAPI</a>
    
</body>
</html>

关于-RequestMapping、Ant 路径、PathVariable 注解HiddenHttpMethodFilter 过滤器用 POJO 作为参数

原文地址:https://www.cnblogs.com/angelye/p/7474954.html