Maciaz
Maciaz

Reputation: 1224

How to combine GET & POST HTTP methods for the same view in Spring web app?

I have a view that is rendered with this method:

@RequestMapping("/employee/{id}")
public String showSpecificEmployee(@PathVariable String id, Model model){

    model.addAttribute("employee", employeeService.findEmployeeById(new Long(id)));

    DateCommand dateCommand = new DateCommand();
    dateCommand.setEmployeeId(new Long(id));

    model.addAttribute("date", dateCommand);

    return "specificEmployee";
}

The view displayes some basic information about the Employee. On the same view, I do have a form to choose a month and filter the information by Date. After the Date is chosen, I would like to have the view 'refreshed' with updated information. That means I do have a POST & GET methods bound to the same view.

@RequestMapping("/passdate")
public String updateWorkmonth(@ModelAttribute DateCommand dateCommand, Model model){

    model.addAttribute("employee", employeeService.findEmployeeWithFilteredWorkdaysAndPayments(dateCommand.getEmployeeId(), dateCommand.getActualDate()));
    model.addAttribute("date", dateCommand);

    return "specificEmployee";
}

After the second method is invoked looks like http://localhost:8080/passdate?employeeId=1&actualDate=2018-02, but I want it to be /employee/{id}. How do I combine those 2 methods, so they point to the same URL?

If I set @RequestMapping("/employee/{id}") on both methods, I keep getting an error.

Upvotes: 1

Views: 557

Answers (3)

Vadym Dudnyk
Vadym Dudnyk

Reputation: 172

You actually need only one GET method

@RequestMapping("/employee/{id}")

and optionally passed

@RequestParam("actualDate")

Upvotes: 1

Steven Fougeron
Steven Fougeron

Reputation: 66

You can specify the type of HTTP request you want in the @RequestMapping parametters

When you don't specify it, it uses GET by default

@RequestMapping(value = "/employee/{id}",method = RequestMethod.POST)

Upvotes: 0

Anton Tupy
Anton Tupy

Reputation: 969

You can redirect user to that url. Just replace in method updateWorkmonth one line

return "specificEmployee";

with

return "redirect:/employee/" + dateCommand.getEmployeeId();

Upvotes: 0

Related Questions