SpringMVC 学习(二)——使用 @RequestMapping 映射请求

Spring MVC 使用 @RequestMapping 注解控制器指定可 以 URL

在控制器的及方法定义处都可

@RequestMapping

义处:提供初求映射信息。相于  WEB 用的根目

方法:提供分映射信息。相义处 URL。若

义处 @RequestMapping方法处标记 URL

WEB 用的根目

DispatcherServlet 获请求后,就通控制器上

@RequestMapping 提供的映射信息求所对应理 方法。

 

 

使用 @RequestMapping 映射求示例

 

义处标记

@RequestMapping 限定了理 器可以理所有 URI /hello  求,它 WEB 容器部 署的根路径

理器可以定多个理方法,理来 自/hello 下的

 

 

 

P404. RequestMapping_请求方式

映射求参数、求方法或

@RequestMapping 除了可以使用 URL 映射求外,

可以使用求方法、求参数及映射

@RequestMapping value method params heads  表示 URL求方法、求参数及的映射条 件,他系,合使用多个条件可让请求映射 更加精化。

params headers支持简单的表

param1: 表示求必包含名 param1 求参数

!param1: 表示求不能包含名 param1 求参数

param1 != value1: 表示求包含名 param1 求参数,但其不能 value1

{“param1=value1”, “param2”}: 求必包含名 param1 param2  求参数,且 param1 参数的须为 value1

映射求参数、求方法或

P606. RequestMapping_Ant 路径

Ant 源地址支持 3 匹配符

?匹配文件名中的一个字符

*匹配文件名中的任意字符

**** 匹配多路径

@RequestMapping 支持 Ant 格的 URL

/user/*/createUser: 匹配

/user/aaa/createUser/user/bbb/createUser URL

/user/**/createUser: 匹配

/user/createUser/user/aaa/bbb/createUser URL

/user/createUser??: 匹配

/user/createUseraa/user/createUserbb URL

 

P707. RequestMapping_PathVariable注解

@PathVariable  映射 URL 定的占位符

占位符的 URL Spring3.0 新增的功能功能在

SpringMVC REST 进发程中具有里程碑的 意

@PathVariable 可以将 URL 中占位符参数定到控 制器理方法的入参中URL 中的 {xxx} 占位符可以通

@PathVariable("xxx") 定到操作方法的入参中。

 

 

REST

REST Representational State Transfer。(源)表现层态转化。是目前 最流行的一件架。它结构清晰、符合准、易于理解、展方便,  所以正得到越来越多网站的采用

源(Resources:网上的一个体,或者是网上的一个具体信息。它 可以是一段文本、一张图片、一首歌曲、一之就是一个具体的存在。 可以用一个URI源定位符)指向它,每种资对应一个特定的 URI 。要 源,访问它的URI就可以,因此 URI 为每一个源的独一无二的识 别

现层Representation源具体呈出来的形式,叫做它的表现层

Representation。比如,文本可以用 txt 格式表,也可以用 HTML 格 式、XML 格式、JSON 格式表,甚至可以采用二制格式。

态转化(State Transfer每发出一个求,就代表了客端和服器的一 次交互程。HTTP协议,是一个无状态协议,即所有的状都保存在服器 端。因此,如果客端想要操作服器,必手段,器端

态转State Transfer。而这种转化是建立在表现层之上的,所以就是

现层态转。具体,就是 HTTP 协议里面,四个表示操作方式的

GETPOSTPUTDELETE。它别对应基本操作:GET 用来源,POST 用来新建源,PUT 用来更新源,DELETE 用来源。

 

示例:

/order/1  HTTP GET :得到 id = 1 order

/order/1  HTTP DELETE id = 1 order

/order/1  HTTP PUT更新id = 1 order

/order  HTTP POST新增 order

HiddenHttpMethodFilter浏览 form 只支持 GET

POST 求,而DELETEPUT method 并不支

Spring3.0 添加了一个过滤器,可以将转换 为标准的 http 方法,使得支持 GETPOSTPUT

DELETE 求。

 

 

@PathVariable URL 占位符到入参

 

占位符的 URL Spring3.0 新增的功能功能在

SpringMVC REST 进发程中具有里程碑的 意

@PathVariable 可以将 URL 中占位符参数定到控 制器理方法的入参中URL 中的 {xxx} 占位符可以通@PathVariable("xxx") 定到操作方法的入参中。

代码示例:

helloWorld.java

package com.xuehj.springmvc.handler;

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;

/**
 * @program: SpringMVC
 * @description: TODO
 * @author: Mr.Xue
 * @create: 2018-12-24 09:36
 **/
@Controller
@RequestMapping("/view")
public class HelloWorld {
    /**
     * 1. 使用 @RequestMapping 注解来映射请求的 URL
     * 2. 返回值会通过视图解析器解析为实际的物理视图, 对于 InternalResourceViewResolver 视图解析器,
     * 会做如下的解析:通过 prefix + returnVal + 后缀 这样的方式得到实际的物理视图, 然会做转发操作
     * /WEB-INF/views/success.jsp
     *
     * @return
     */
    @RequestMapping("/helloworld")
    public String hello() {
        System.out.println("hello world");
        return "success.jsp";
    }

    /**
     * 常用: 使用 method 属性来指定请求方式
     */
    @RequestMapping(value = "/testMethod", method = RequestMethod.POST)
    public String testMethod() {
        System.out.println("testMethod");
        return "success.jsp";
    }

    /**
     * 了解: 可以使用 params 和 headers 来更加精确的映射请求. params 和 headers 支持简单的表达式.
     *
     * @return
     */
    @RequestMapping(value = "testParamsAndHeaders", params = {"username",
            "age!=10"}, headers = {"Accept-Language=en-US,zh;q=0.8"})
    public String testParamsAndHeaders() {
        System.out.println("testParamsAndHeaders");
        return "success.jsp";
    }

    @RequestMapping("/testAntPath/*/abc")
    public String testAntPath() {
        System.out.println("testAntPath");
        return "success.jsp";
    }

    /**
     * @param id
     * @return
     * @PathVariable 可以来映射 URL 中的占位符到目标方法的参数中.
     */
    @RequestMapping("/testPathVariable/{id}")
    public String testPathVariable(@PathVariable("id") int id) {
        System.out.println("testPathVariable: " + id);
        return "../success.jsp";
    }

    /**
     * Rest 风格的 URL.
     * 以 CRUD 为例:
     * 新增: /order POST
     * 修改: /order/1 PUT update?id=1
     * 获取: /order/1 GET get?id=1
     * 删除: /order/1 DELETE delete?id=1
     * <p>
     * 如何发送 PUT 请求和 DELETE 请求呢 ?
     * 1. 需要配置 HiddenHttpMethodFilter
     * 2. 需要发送 POST 请求
     * 3. 需要在发送 POST 请求时携带一个 name="_method" 的隐藏域, 值为 DELETE 或 PUT
     * <p>
     * 在 SpringMVC 的目标方法中如何得到 id 呢?
     * 使用 @PathVariable 注解
     */
    @RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET)
    public String testRest(@PathVariable Integer id) {
        System.out.println("testRest GET: " + id);
        return "../success.jsp";
    }

    @RequestMapping(value = "/testRest", method = RequestMethod.POST)
    public String testRest() {
        System.out.println("testRest POST");
        return "success.jsp";
    }

    @RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE)
    public String testRestDelete(@PathVariable Integer id) {
        System.out.println("testRest Delete: " + id);
        return "../success.jsp";
    }

    @RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT)
    public String testRestPut(@PathVariable Integer id) {
        System.out.println("testRest Put: " + id);
        return "../success.jsp";
    }

}

success.jsp

<%--
  Created by IntelliJ IDEA.
  User: 薛恒杰
  Date: 2018/12/24
  Time: 9:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java"  isErrorPage="true"%>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <h1>Hello World</h1>
    </body>
</html>

dispatcher-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: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.xuehj.springmvc"/>

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

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_4_0.xsd"
         version="4.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--
	配置 org.springframework.web.filter.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>

    <!-- 配置 DispatcherServlet -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置 DispatcherServlet 的一个初始化参数: 配置 SpringMVC 配置文件的位置和名称 -->
        <!--
            实际上也可以不通过 contextConfigLocation 来配置 SpringMVC 的配置文件, 而使用默认的.
            默认的配置文件为: /WEB-INF/<servlet-name>-servlet.xml
        -->
        <!--
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: 薛恒杰
  Date: 2018/12/24
  Time: 9:21
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>$Title$</title>
    </head>
    <body>
        <a href="view/helloworld">Hello world</a>

        <br><br>
        <a href="view/testMethod">testMethod</a>

        <br><br>
        <form method="post" action="${pageContext.request.contextPath}/view/testMethod">
            <input type="submit" value="提交"/>
        </form>

        <br><br>
        <a href="view/testParamsAndHeaders">Test ParamsAndHeaders</a>

        <br><br>
        <a href="view/testAntPath/ddd/abc">Test AntPath</a>

        <br><br>
        <a href="view/testPathVariable/1">Test PathVariable</a>

        <br><br>
        <a href="view/testRest/1">Test Rest Get</a>

        <br><br>
        <form action="view/testRest" method="post">
            <input type="submit" value="TestRest POST"/>
        </form>

        <br><br>
        <form action="view/testRest/1" method="post">
            <input type="hidden" name="_method" value="DELETE"/>
            <input type="submit" value="TestRest DELETE"/>
        </form>

        <br><br>
        <form action="view/testRest/1" method="post">
            <input type="hidden" name="_method" value="PUT"/>
            <input type="submit" value="TestRest PUT"/>
        </form>

    </body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_41577923/article/details/85232522