Search code examples
jspspring-mvcjava-8tomcat8spring-4

SpringMVC : Throws 415 Unsupported Media Type while attempting POST request call for redirection


Browser response like below:

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

Instead of redirecting to the home page ( home.jsp )

welcome.jsp file:

<form method ="POST" action = "<c:url value='/login'/>" >

       <input id="name" name="name" type="text">
       <input id="password" name="password" type="password">
       <input type="submit" id="loginNew" value="LoginNew"> 
  </form>

Controller class:

@RequestMapping( value="/login" , method = RequestMethod.POST )
    public ModelAndView authenticate ( @RequestBody User userObj ) throws Exception {
       ModelAndView modelAndView = new ModelAndView ();
        try {
            user = userService.authenticateUser ( userObj );
        } catch ( Exception e ) {
            e.printStackTrace();
         }
        modelAndView.setViewName("/home");
        return modelAndView;
    }

Solution

  • By adding @ModelAttribute instead of @RequestBody in the method param solved the issue and then redirected to the home.jsp page as expected.

    @RequestMapping( value="/login" , method = RequestMethod.POST )
            public ModelAndView authenticate ( @ModelAttribute User userObj ) throws Exception {
               ModelAndView modelAndView = new ModelAndView ();
                try {
                    user = userService.authenticateUser ( userObj );
                } catch ( Exception e ) {
                    e.printStackTrace();
                 }
                modelAndView.setViewName("/home");
                return modelAndView;
            }