Java spring MVC gets / publishes in the same JSP
This is my controller
@RequestMapping(value = "/add",method = RequestMethod.GET)
public String add(Model model) {
return "add";
}
@RequestMapping(value = "/add",method = RequestMethod.POST)
public String added(@RequestParam("name") String name,Model model) {
City city = new City();
city.setCity(name);
service.addCity(city);
return "add";
}
This is my JSP view This is just to add... This is add jsp.. So send it back to yourself
<form method="post" action="/spring/krams/edit/add"> Linna nimi <input type="text" name="name"> <input type="submit" value="Test" name="submit" /> </form>
I want the JSP file to change so that when I publish it to this file, it will say... "City added." Is that possible?
What about updating the city?
@RequestMapping(value = "/update",method = RequestMethod.POST)
public String updated(@RequestParam("city") int city_id,@RequestParam("text") String name,Model model) {
service.updateCity(name,city_id);
return "update";
}
There's no object here?
Solution
In the post method, you can add attributes using the addAttribute method
@RequestMapping(value = "/add",Model model) {
City city = new City();
city.setCity(name);
service.addCity(city);
model.addAttribute("city",city);
return "add";
}
In JSP, you can check whether the attribute city is null (marked < C: if / >) If it's not null, it's because it's just added to the model, so you can display anything you want$ {city.city} is just a JSTL expression that accesses the city attribute and then calls getter to access the city attribute of the attribute:
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<c:if test="${city != null}">
CITY <c:out value="${city.city}" /> ADDED
</c:if>
UPDATE
If different messages are required according to the update / create operation, the following operations can be performed: (in the example, update when ID param is not null, because ID is the identifier of the city to be updated)
@RequestMapping(value = "/add",method = RequestMethod.POST)
public String added(@RequestParam(value="id",required=false) String id,@RequestParam("name") String name,Model model) {
City city;
String operation;
if(id== null){
//create operation
city = new City();
operation = "CREATE";
}else{
//update operation
city = service.findCity(id);
operation = "UPDATE";
}
city.setCity(name);
service.saveCity(city); //save or update
model.addAttribute("city",city);
model.addAttribute("operation",operation); //add operation param
return "add";
}
In JSP, you can:
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<c:if test="${operation == 'CREATE'}">
<c:if test="${city != null}">
CITY <c:out value="${city.city}" /> ADDED
</c:if>
<c:if test="${operation == 'UPDATE'}">
CITY <c:out value="${city.city}" /> UPDATED
</c:if>
</c:if>
