• springMVC中使用 RequestBody POST请求 415 (Unsupported Media Type)


    前端代码:

    <html>
    <head>
        <base href="<%=basePath %>"/>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>Insert title here</title>
    </head>
    <body>
        <form method="post" action="<%=basePath%>user/login2">
            <label for="name">用户名</label>
            <input id="name" type="text" name="username">
            <br>
            <label for="pass">密码</label>
            <input id="pass" type="text" name="password">
            <button type="submit">提交</button>
        </form>
    </body>
    </html>

    后端代码:

    @PostMapping("/login2")
        public String loginLogic2(@RequestBody User user) {
            Subject subject = SecurityUtils.getSubject();
            // UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
            // 登录失败会抛出异常,则交由异常解析器处理
            //subject.login(token);
            System.out.println(user);
            return "main";
        }

    分析:

    出现问题的元婴是 @RequestBody 允许json的请求通过 而前端默认的请求类型为

    application/x-www-form-urlencoded ,所以出现媒体类型不一致,

    解决方案:

    1: @RequestBody(required=false)
    2: 去掉1中注解 由MVC自动进行装配,可以不是json数据

    后述: 实际上在全部ajax应用的时候允许使用@RequestBody,但是传统问题上可以设置其不是必须的参数.
  • 相关阅读:
    常用知识点集合
    LeetCode 66 Plus One
    LeetCode 88 Merge Sorted Array
    LeetCode 27 Remove Element
    LeetCode 26 Remove Duplicates from Sorted Array
    LeetCode 448 Find All Numbers Disappeared in an Array
    LeetCode 219 Contains Duplicate II
    LeetCode 118 Pascal's Triangle
    LeetCode 119 Pascal's Triangle II
    LeetCode 1 Two Sum
  • 原文地址:https://www.cnblogs.com/dgwblog/p/12495310.html
Copyright © 2020-2023  润新知