课时2:RequestMapping映射及个属性

.1 )RequestMapping映射及个属性

  1..映射 去匹配@RequestMapping注解,可以和方法名类名不一致 访问就是cc/we

package net.bt.handler;

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

@Controller
@RequestMapping("cc")
public class TestServlet {

    @RequestMapping("we")
    public String welcome(){
        return "success";
    }
}

  2.默认使用了请求转发的跳转方式

  3.@RequestMapping中的属性method 处理请求方式处理(post,get,put,delete)

    3.1 只处理post请求

@RequestMapping(value = "we",method = RequestMethod.POST)

    3.2 只处理get请求

@RequestMapping(value = "we",method = RequestMethod.GET)

  4.@RequestMapping中的属性params 处理请求中必须包含某个参数值

  @RequestMapping(value = "we",method = RequestMethod.POST,params = {"name",age!=23})

    4.1 必须参数必须有name并且age的不能等于23 列如

<a href="cc/we?name=zs">faqiqingqiu</a>

  5.ant风格的请求路径

    5.1 ?:单个字符 *任意个字符(0或多个字符) ** 任意目录

  @RequestMapping(value = "**/we1")
    public String welcome1(){
        return "success";
    }

      5.1 .2 请求时路径这么写

<a href="cc/ashhasaasasasasq/we1">faqiqingqiu</a>  《!--中间任意目录都可以  只要首尾符合就可以-->

  6.如何接受html/jsp发送过来的数据 方式一

    6.1 假如前端要传过来一个zs 可以这样写

<a href="cc/we2/zs">faqiqingqiu</a>

    6.2 在springmvc如何接收呢

   @RequestMapping(value = "we2/{name}")
    public String welcome2(@PathVariable("name")String name){
        System.out.println(name);
        return "success";
    }

  7..如何接受html/jsp发送过来的数据 方式二

    7.1 假如前端要传过来一个参数 可以这样写

<a href="cc/we3?uname=张三">请求</a>
<form action="cc/we3">
    <input type="text" name="uname">
    <input type="submit" />
</form>

    7.2 在springmvc如何接收呢

     @RequestMapping(value = "we3")
    public String welcome3(@RequestParam("uname") String name){
        System.out.println(name);
        return "success";
    }

      7.2.1 通过@RequestParam(传过来的参数) 获取 然后在赋值给name形参 就可以拿到 等价于request.getParameter()

      7.2.2 加入前端传过来的少了参数 而我接收的多了 如何避免报错

    @RequestMapping(value = "we3")
    public String welcome3(@RequestParam("uname") String name,@RequestParam(value = "uage",required = false,defaultValue = "20")Integer age){
        System.out.println(name);
        return "success";
    }

        required = false参数可有可无 defaultValue = "20"默认值

原文地址:https://www.cnblogs.com/thisHBZ/p/12528215.html