Spring Boot学习(四)Controller接收请求参数

Spring Boot学习(四)Controller接收请求参数html

1、经过实体Bean接收请求参数java

经过实体Bean来接收请求参数,适用于get和post方式,Bean的属性名称必须与请求参数名称相同。app

项目结构以下:post

1.Bean代码以下:学习

package com.example.beans;

public class Student {
    private int id;
    private String name;
    private String pwd;
//省略get和set
}

2.表单页面以下 mytest.htmlcode

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Controller接收请求参数</title>
</head>
<body>
<form action="/test/test1" method="post">
    姓名:<input type="text" name="name">
    <br/><br/>
    密码:<input type="password" name="passwd">
    <br/><br/>
    <input type="submit" value="肯定"/>
</form>
</body>
</html>

3.控制器代码以下:orm

@Controller
public class MyTest {

    @RequestMapping(value = "/test/login")
    public String test1(){
        return "/test/mytest";
    }

    @RequestMapping(value = "/test/test1",method=RequestMethod.POST)
    public String login(Student stu, Model model){
        model.addAttribute("stu",stu);
        return "/test/result";
    }
}

4.显示结果页面result.htmlxml

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>全部学生信息</title>
</head>
<body>
<h4 th:text="${stu.getName()}"></h4>
</body>
</html>

2、经过方法的参数接收htm

经过处理方法的形参接收请求参数,也就是直接把表单参数写在控制器类相应方法的形参中,即形参名称与请求参数名称彻底相同。该接收参数方式适用于get和post提交请求方式。对象

@RequestMapping(value="/test/test2",method = RequestMethod.POST)
    public String login(String name, String password, Model model){
        model.addAttribute("name",name);
        return "/test/result";
    }

3、经过HttpServletRequest接收请求参数

经过HttpServletRequest接收请求参数,适用于get和post提交请求方式

@RequestMapping(value="/test/test3",method=RequestMethod.POST)
    public String login(HttpServletRequest req,Model model){
        String name=req.getParameter("name");
        model.addAttribute("name",name);
        return "/test/result";
    }

4、经过@PathVariable接收URL中的请求参数

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

http://localhost:8080/test/test4/张三丰
@RequestMapping(value = "/test/test4/{name}",method = RequestMethod.GET)
    @ResponseBody
    public String test4(@PathVariable String name){
        return name;
    }

5、经过@RequestParam接收请求参数

@RequestMapping("/test/test5")
    @ResponseBody
    public String test5(@RequestParam String name,@RequestParam String passwd){
        return name;
    }

经过@RequestParam接收请求参数与经过处理方法的形参接收请求参数的区别是:当请求参数名与接收参数名不一致时,经过处理方法的形参接收请求参数不会报404错误,而经过@RequestParam接收请求参数会报404错误。

6、经过@ModelAttribute接收请求参数

@RequestMapping("/test/test6")
    public String test6(@ModelAttribute("stu") Student stu){
        return "/test/result";
    }

@ModelAttribute注解放在处理方法的形参上时,用于将多个请求参数封装到一个实体对象,从而简化数据绑定流程,并且自动暴露为模型数据,于视图页面展现时使用。而“经过Bean接收请求参数”只是将多个请求参数封装到一个实体对象,并不能暴露为模型数据(须要使用model.addAttribute语句才能暴露为模型数据)。

视图层代码以下:

<h4 th:text="${stu.getName()}"></h4>
相关文章
相关标签/搜索