SpringMVC之使用 @RequestMapping 映射请求

@RequestMapping注解

SpringMVC使用该注解让控制器知道可以处理哪些请求路径的,除了可以修饰方法,还可以修饰在类上

– 类义处:提供初求映射信息。相WEB 用的根目
方法:提供分映射信息。相义处URL。若
义处@RequestMapping方法处标记URL
WEB 用的根目录 。

DispatcherServlet作为SpringMVC的前置控制器,拦截客户端请求后,通过该注解的映射信息确定请求的处理方法。

 @RequestMapping接口定义:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {

下面是一个测试类

package com.led.test;

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

/**
 * @author Alan
 * @date 2018/5/25 22:03
 */
@Controller
@RequestMapping("/test")
public class SpringMVCTest {
    private static final String SUCCESS = "success";

    @RequestMapping("/testRequestMapping")
    public String testRequestMapping(){
        System.out.println("testRequestMapping");
        return SUCCESS;
    }
}

index.jsp加上发送对应请求的链接:

<a href="test/testRequestMapping">Test RequestMapping</a>

运行项目,点击该链接,可以看到请求路径是类上的请求路径和方法的请求路径拼接起来的,同时控制台也有对应输出。

@RequestMapping里面还可以使用method属性定义请求方式:

 /**
     * 使用method定义请求方式
     * @return
     */
    @RequestMapping(value = "/testMethod",method = RequestMethod.POST)
    public String testMethod(){
        System.out.println("test method");
        return SUCCESS;
    }

index.jsp新增发送post方式的按钮,点击后成功跳转到success.jsp

<form action="test/testMethod" method="post">
      <input type="submit" value="submit">
  </form>

如果使用超链接方式(其实发送的是GET请求),将报如下错误:

猜你喜欢

转载自www.cnblogs.com/stm32stm32/p/9090899.html
今日推荐