Search code examples
javaspringspring-mvchttp-response-codes

From a spring mvc controller action, how do I get access to request/response?


My action looks like:

public String add() {

   return "/WEB-INF/views/add.jsp";
}

In this case I need access to a posted form field parameter. Once I receive the posted parameter value, I will save it to the db and then return an http response code of 200 if there are no errors. If an error has occured, I will return HTTP 500 response code.

How can I set the http response code in the return (instead of the view unless I can do both?).


Solution

  • Assuming this is a @RequestMapping-annoted controller, then just declare the form field as a parameter:

    public String add(String myformFieldName) {
    

    To return an explicit status code on the response, then declare the response and set it:

    public String add(String myformFieldName, HttpServletResponse httpResponse) {
       httpResponse.setStatus(...); 
    }