设为首页 加入收藏

TOP

SpringMVC入门 -- 参数绑定(四)
2019-09-19 11:11:58 】 浏览:122
Tags:SpringMVC 入门 参数 绑定
{ @RequestMapping(value = "/hello", params = {"username", "age != 10"}, method = RequestMethod.GET, headers = "Referer: https://www.baidu.com/") public String show(){ return "hello"; } }

 

2、@PathVariable

(1)简介
  SpringMVC提供的一个注解,在方法参数中使用,用于获取参数。
  Spring3.0后支持 带占位符的URL,即相当于 /get/{id} 的形式。通过@PathVariable 可以将URL中的占位符参数绑定到方法的参数中。

【用法样例:】

package com.lyh.controller;

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;

@Controller
public class HelloController {

  @RequestMapping("/get/{id}")
  public String show(@PathVariable("id") Integer id){
    return "hello";
  }
}

 

3、@RequestParam

(1)简介
  SpringMVC提供的一个注解,在方法参数中使用,用于获取参数。
  @RequestParam 用于获取表单参数。等价于request.getParameter("name")。而@PathVariable 用于获取 URL 中的占位符。

(2)参数
  value:用于获取参数。
  required :表示是否需要该数据,默认为true,若不存在,则会抛出异常。
  defaultValue :表示默认的值,对于包装类型,默认为null,可以不设值,对于基本类型数据,需要设个初始值。

【举例:】
【index.jsp】
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" isErrorPage="true"%>
<html>
  <head>
    <title>首页</title>
  </head>
  <body>
      <form action="/testRequestParam/1">
          <label for="nickname">姓名</label>
          <input type="text" id="nickname" name ="nickname" placeholder="请输入姓名..." />

          <label for="password">密码</label>
          <input type="password" id="password" name ="password" placeholder="请输入密码..." />

          <label for="age">年龄</label>
          <input type="text" id="age" name ="age" placeholder="请输入年龄..." />

          <label for="salary">工资</label>
          <input type="text" id="salary" name ="salary" placeholder="请输入工资..." />
         <input type="submit" value="test requestParam"/>
      </form>
  </body>
</html>

【hello.jsp】
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" isErrorPage="true"%>
<html>
  <head>
    <title>Test RequestParam</title>
  </head>
  <body>
    <h2>${message}</h2>
    <h2>${msg}</h2>
  </body>
</html>

【HelloController.java】
package com.lyh.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {

    @RequestMapping(value = "/testRequestParam/{id}")
    public ModelAndView testRequestParam(@PathVariable("id") Integer id, @RequestParam(value = "nickname") String nickname,
                                         @R
首页 上一页 1 2 3 4 5 6 7 下一页 尾页 4/7/7
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇XXLJOB2.1.0数据源配置踩坑记录 下一篇Spring中@Component与@Bean的区别

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目