Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RequestMethod POST and GET in the same Controller?

First of all, here is my Controller:

@RequestMapping(value = "/esta", method = RequestMethod.POST)
public String handleRequest(HttpServletRequest request) {

    Esta estaobject = new Esta();
    // To test, if the parameters are set
    String user = request.getParameter("user");
    String name = request.getParameter("name");
    String shortname = request.getParameter("shortname");
    String was_admin_string = request.getParameter("was_admin");
    String sap_nr = request.getParameter("sap_nr");
    String etl_string = request.getParameter("etl");

    if (user != null && name != null && shortname != null && was_admin_string != null && sap_nr != null && etl_string != null) {
        some code...
    }

    request.getSession().setAttribute("esta", estaobject);

    return "esta";
}

When I visit the site, it check with the if-statement, if there are some parameters.
If not, then it should just display my form. Then, when I fill the form, it send it with POST and now there are some parameters and it goes through the if-statement.

My problem is: When I visit the site for the first time, it isn't a POST-request, so I get the error message Request method 'GET' not supported.
But change the form to a GET-request isn't a option for me. It must be POST.

So is there a solution to handle the same controller in POST and GET Requests?

like image 905
Michael Schmidt Avatar asked May 17 '13 06:05

Michael Schmidt


2 Answers

Make it an array of method values that it gets mapped to, like so:

@RequestMapping(value = "/esta", method = {RequestMethod.POST, RequestMethod.GET})
like image 190
CorayThan Avatar answered Oct 14 '22 08:10

CorayThan


Or you can write separate methods

@RequestMapping(value = {#some_vale}, method = RequestMethod.GET)
public random_method #1{
}

@RequestMapping(value = { #some_value }, method = RequestMethod.POST)
public random_method #2{
}

now you can implement your to visit the specific page and another to fill the form. Hope this will help you.

like image 33
myk. Avatar answered Oct 14 '22 07:10

myk.