zoukankan      html  css  js  c++  java
  • 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,但是传统问题上可以设置其不是必须的参数.
  • 相关阅读:
    今天面试一些程序员(新,老)手的体会
    UVA 10635 Prince and Princess
    poj 2240 Arbitrage
    poj 2253 Frogger
    poj 2485 Highways
    UVA 11258 String Partition
    UVA 11151 Longest Palindrome
    poj 1125 Stockbroker Grapevine
    poj 1789 Truck History
    poj 3259 Wormholes
  • 原文地址:https://www.cnblogs.com/dgwblog/p/12495310.html
Copyright © 2011-2022 走看看