zoukankan      html  css  js  c++  java
  • @RequestParam与@PathVariable

    @PathVariable 

    带占位符的 URL 是 Spring3.0 新增的功能,该功能在SpringMVC 向 REST 目标挺进发展过程中具有里程碑的意义

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

    /**
    * localhost:8080/springmvc/hello/pathVariable/bigsea
    * localhost:8080/springmvc/hello/pathVariable/sea
    * 这些URL 都会 执行此方法 并且将 <b>bigsea</b>、<b>sea</b> 作为参数 传递到name字段
    * @param name
    * @return
    */
    @RequestMapping("/pathVariable/{name}")
    public String pathVariable(@PathVariable("name")String name){
    System.out.println("hello "+name);
    return "helloworld";
    }

    JSP(这里指定全路径):

    <h1>pathVariable</h1>
    <a href="${pageContext.request.contextPath}/hello/pathVariable/bigsea" > name is bigsea </a>
    <br/>
    <a href="${pageContext.request.contextPath}/hello/pathVariable/sea" > name is sea</a>
    <br/>

    运行结果:

    hello bigsea
    hello sea

    @RequestParam

    @RequestParam 绑定请求参数

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

    – value:参数名

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

    /**
    * 如果 required = true 则表示请求参数对应的 字段 必须存在.如果不存在则会抛出异常<br/>
    * @param firstName 可以为null
    * @param lastName 不能为null .为null报异常
    * @param age age字段表示如果没有 age 参数 则默认值为 0
    * @return
    */
    @RequestMapping("/requestParam")
    public String requestParam(@RequestParam(value="firstName",required=false)String firstName,
    @RequestParam( value="lastName" ,required = true) String lastName,
    @RequestParam(value="age",required = false ,defaultValue="0")int age) {
    System.out.println("hello my name is " + (firstName == null ? "" : firstName)
    + lastName + "," + age +" years old this year");
    return "helloworld";
    }

    Jsp:

    <a href="requestParam?firstName=big&lastName=sea" > name is bigsea , age is 0 </a>
    <br/>
    <a href="requestParam?lastName=sea&age=23" > name is sea , age is 23 </a>
    <br/>
    <a href="requestParam" > throws exception </a>

    运行结果:

    hello my name is bigsea,0 years old this year
    hello my name is sea,23 years old this year

  • 相关阅读:
    sql语句游标的写法
    oracle的安装与plsql的环境配置
    oracle中创建表时添加注释
    jsp中Java代码中怎么获取jsp页面元素
    sql模糊查询
    jQuery循环给某个ID赋值
    Codeforces Round #671 (Div. 2)
    TYVJ1935 导弹防御塔
    Educational Codeforces Round 95 (Rated for Div. 2)
    Codeforces Round #670 (Div. 2)
  • 原文地址:https://www.cnblogs.com/lqh969696/p/10494897.html
Copyright © 2011-2022 走看看