SpringMVC接收参数 具体示例 #yyds干货盘点#

Posted 梁云亮

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringMVC接收参数 具体示例 #yyds干货盘点#相关的知识,希望对你有一定的参考价值。

实体类

@Data
public class Dept {
    private Integer deptno;
    private String dname;
    private String loc;
}

后台控制器

@Controller
@RequestMapping("/dept")
public class DeptController {
    @RequestMapping("/add")
    void add(HttpServletRequest request){
        try {
            ServletInputStream is = request.getInputStream();
            String result = new BufferedReader(new InputStreamReader(is))
                    .lines().collect(Collectors.joining(System.lineSeparator()));
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping(value = "/add1")
    public ModelAndView add1(HttpServletRequest request) {
        String deptno = request.getParameter("deptno");
        String dname = request.getParameter("dname");
        String loc = request.getParameter("loc");
        Dept dept = new Dept(Integer.parseInt(deptno), dname, loc);
        return new ModelAndView("/res", "res", dept);
    }

    @PostMapping("/add2")
    public ModelAndView add2(Integer deptno, String dname, String loc) {//前台页面传递过来的数据会自动实例化
        Dept dept = new Dept(deptno, dname, loc);
        return new ModelAndView("/res", "res", dept);
    }

    @RequestMapping("/add3")
    public ModelAndView add3(Dept dept) {//前台页面传递过来的数据会自动实例化
        System.out.println(dept);
        return new ModelAndView("/res", "res", dept);
    }

    @RequestMapping("add4")
    public void add4(Dept dept, HttpServletResponse response) throws IOException {// 变量的名称无所谓,不是必须得和前台页面一致,只要类型不错就行了
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(dept);
        out.write(json);
    }

    @ResponseBody
    @RequestMapping("add5")
    public Dept add5(Dept dept) throws IOException {// 变量的名称无所谓,不是必须得和前台页面一致,只要类型不错就行了
        return dept;
    }

}

普通表单

示例一:后台通过HttpServletRequest获取

<form action="dept/add1" method="post">
    <input type="text" name="deptno">
    <input type="text" name="dname">
    <input type="text" name="loc">
    <input type="submit" value="添加部门">
</form>

示例二:后台通过具体的属性获取

<form action="dept/add2" method="post">
    <input type="text" name="deptno">
    <input type="text" name="dname">
    <input type="text" name="loc">
    <input type="submit" value="添加部门">
</form>

示例三:后台通过具体的对象获取

<form action="dept/add3" method="post">
    <input type="text" name="deptno" id="deptno">
    <input type="text" name="dname" id="dname">
    <input type="text" name="loc" id="loc">
    <input type="submit" value="添加部门">
</form>

示例四:后台通过具体的属性获取

<form>
    <input type="text" name="deptno">
    <input type="text" name="dname">
    <input type="text" name="loc">
    <input type="button" value="添加部门" onclick="add22();">
</form>
<script>
    function add22() {
        let form = document.forms[0];
        form.action = "dept/add2";
        form.method = "POST";
        form.submit();
    }
</script>

前台以JSON方式传递数据

后台通过具体的对象获取

<form action="dept/add3" method="post">
    <input type="text" name="deptno" id="deptno1">
    <input type="text" name="dname" id="dname1">
    <input type="text" name="loc" id="loc1">
    <button id="addBtn">添加部门</button>
</form>
<script>
    $(function () {
        $("#addBtn").click(function () {
            let deptno = $("#deptno1").val();
            let dname = $("#dname1").val();
            let loc = $("#loc1").val();
            let dept = {deptno: deptno, dname: dname, loc: loc};
            $.ajax({
                url: "dept/add4",   // 注:add3、add4、add5都可以。
                type: "POST",   
                data: dept,
                success: function (data) {
                    alert(data.deptno + "  " + data.dname + "  " + data.loc);
                }
            });
        });
    })
</script>

指定contentType

网页通过JSON形式向后台传递数据

<form id="deptForm2">
    <input type="text" name="deptno" id="deptno3">
    <input type="text" name="dname" id="dname3">
    <input type="text" name="loc" id="loc3">
    <input type="button" value="添加部门" onclick="add32();">
</form>
<script>
    function add32() {
        let deptno = $("#deptno3").val();
        let dname = $("#dname3").val();
        let loc = $("#loc3").val();
        let dept = {deptno: deptno, dname: dname, loc: loc};
        $.ajax({
            url: "dept/add1",
            type: "POST",   
            data: dept,
            // contentType: "application/json;charset=UTF-8",
            success: function (data) {
                alert(data.deptno + "  " + data.dname + "  " + data.loc);
            }
        });
    };
</script>

网页通过key/value形式向后台传递数据

<form id="deptForm1">
    <input type="text" name="deptno">
    <input type="text" name="dname">
    <input type="text" name="loc">
    <input type="button" value="添加部门" onclick="add31();">
</form>
<script>
    function add31() {
        // let p = $("#deptForm").serialize();
        // alert(p)  //deptno=32&dname=23&loc=32
        $.ajax({
            type: "post",
            dataType: "json", //预期服务器端返回的数据的类型
            url: "dept/add2",  // add1 - add5都能接收到数据
            // contentType: "application/x-www-form-urlencoded",//前端向服务器传递的数据的类型
            data: $("#deptForm1").serialize(),
            success: function (data) {
                console.info(data);
            }
        })
    }
</script>

注:

  • contentType: "application/x-www-form-urlencoded"

    • 如果不指定contentType,后台会将接收到的value值赋给Controller方法的对象参数(或封装后赋给Controller方法的对象参数):
    • 如果指定contentType,后台只能将接收到的value值赋给Controller方法的对应参数
  • contentType: "application/json;charset=UTF-8"
    • 如果不指定contentType,1-5都行
    • 如果指定contentType,只能通过add获取参数的值
    • 若控制器方法对象参数前面加@RequestBody@RequestParam,会报xhr

故:实际项目中,不建议指定contentType,省得为自己找麻烦

以上是关于SpringMVC接收参数 具体示例 #yyds干货盘点#的主要内容,如果未能解决你的问题,请参考以下文章

SpringMVC接收前端参数(Json数据)解析

SpringMVC接收多参数的处理方法

tomcat设置utf-8编码,springMVC后台接收参数反而乱码

springMVC的注解@RequestParam与@RequestBody

多条件分页查询springmvc要接收哪些参数

spring mvcspring mvc接收单个参数