I have a page which i enter parameters to query a list of records.
When the query button is clicked i get the list when an item form the list is clicked it takes me back to the first page with the record in display.
When i hit another button 'new' to clear the page and return an empty page a parameter is there in the url and it sets the value of an item on the page.The item that is there in the url is the crimeRecNo.
How can i get rid of this i want to return an empty page?
Scenario
I am on a page with the following url :http://adomain/crimeTrack/crime_registration.htm
I click Query which does a POST to another url which displays the list of records :http://adomain/crimeTrack/crimeList.htm
On the above page in 2 above i then select one record which does a POST and takes me to the followig url: http://adomain/crimeTrack/getCrime/6.htm - where 6 is the crimeRecNo.
I am now on the above url and i hit the 'NEW' button to get a blank form with the url in 1 above. When i hit new a POST is done to the controller method in code sample 4 under
This method does a redirect to the url which is mapped to a GET method however the final url looks like this : http://adomain/crimeTrack/%20crime_registration.htm?crimeRecNo=6
The value 6 remains in the crimeRecNo field and the entire form is not cleared.
Under is the controller methods:
1. Initial page request
#RequestMapping(value = "crime_registration.htm", method = RequestMethod.GET)
public ModelAndView loadPage(HttpServletRequest request,HttpServletResponse response, #ModelAttribute Crime crime,BindingResult result, ModelMap m, Model model, SessionStatus status,HttpSession session) throws Exception {
try {
logger.debug("In Crime Registration Controller");
myCriminalList.put("dbcriminalList",
this.citizenManager.getListOfCriminals());
...................
session.setAttribute("page", 0);
return new ModelAndView("crime_registration");
} catch (Exception e) {
logger.debug("Exception In CrimeRegistration Controller : "
+ e.getMessage());
return new ModelAndView("crime_registration");
}
}
2. Query For List of Items
#RequestMapping(value = "crimeList.htm", method = RequestMethod.POST)
public ModelAndView handelCrimeList(#ModelAttribute Crime crime,
BindingResult result, ModelMap m, Model model) throws Exception {
if (crimeManager.getCrimesList(crime).size() <= 0) {
model.addAttribute("dbcriminals", myCriminalList);
........
model.addAttribute("crimeTypeList", crimeTypeManager.getCrimeTypeList(crime.getOffenceCatId()));
model.addAttribute("icon", "ui-icon ui-icon-circle-close");
model.addAttribute("results","Error: Query Caused No Records To Be Retrieved!");
return new ModelAndView("crime_registration");
}
model.addAttribute("crimes", crimeManager.getCrimesList(crime));
return new ModelAndView("crimeList");
}
3. Request For One Item/When item is selected from list
#RequestMapping(value = "getCrime/{crimeRecNo}.htm", method = RequestMethod.POST)
public ModelAndView getCrime(#PathVariable Integer crimeRecNo,
#ModelAttribute Crime crime, BindingResult result, ModelMap m,
Model model, HttpServletRequest request,
HttpServletResponse response, HttpSession session) throws Exception {
try {
model.addAttribute("crime", crimeManager.getCrimeRecord(crimeRecNo));
session.setAttribute("crimeRecNo", crimeRecNo);
//model.addAttribute("victimList", citizenManager.getVictimListByCrimeRecNo(crimeRecNo));
} catch (Exception e) {
logger.error("Exception in CitizenRegistrationController - ModelAndView getCitizen "
+ e);
}
int crimeCatId = crimeManager.getCrimeRecord(crimeRecNo).getOffenceCatId();
logger.info("crime category number is : "+crimeCatId);
myCrimeTypeList.put("crimeTypeList", this.crimeTypeManager.getCrimeTypeList(crimeCatId));
model.addAttribute("dbcriminals", myCriminalList);
.....
session.setAttribute("crimeRecNo", crimeRecNo);
return new ModelAndView("crime_registration");
}
4. Request For NEW Form
#RequestMapping(value = "crime_registration_new.htm", method = RequestMethod.POST)
public String loadNew(HttpServletRequest request,Model model,
HttpServletResponse response,SessionStatus status,HttpSession session) throws Exception {
status.setComplete();
return "redirect: crime_registration.htm";
//return new ModelAndView(new RedirectView("crime_registration.htm"));
}
Adding this to 4 did the trick
#RequestMapping(value = "crime_registration_new.htm", method = RequestMethod.POST)
public String loadNew(HttpServletRequest request,Model model,
HttpServletResponse response,SessionStatus status,HttpSession session) throws Exception {
status.setComplete();
model.addAttribute("crime", new Crime());
return "redirect: crime_registration.htm";
//return new ModelAndView(new RedirectView("crime_registration.htm"));
}
Related
In my project I have two pages first one is for entering the data and the second one is for showing the data to the user. When I refresh the result page data is dublicated. I tried to fix this but I am not familiar with PRG pattern. I want to prevent the duplication if the user refreshes the result page.
#RequestMapping(value = { "/display-form", "mainPage.html" }, method = RequestMethod.GET)
public ModelAndView displayForm() {
ModelAndView mv = new ModelAndView("mainPage");
mv.addObject("formData", new SampleModel());
return mv;
}
#RequestMapping(value = "/send-form-data", method = RequestMethod.POST)
public ModelAndView processForm(#Valid #ModelAttribute("formData") SampleModel formData, BindingResult res) {
ModelAndView mv = new ModelAndView();
fmv.validate(formData, res);
mv.addObject("formData", formData);
service.delete(1);
if(res.hasErrors())
{
mv.setViewName("mainPage");
}
else
{
mv.setViewName("result");
service.create(formData);
mv.addObject("list", service.findAll());
}
return mv;
}
Try to create the ModelAndView instance with redirection, so that when actions completes, you get a 3xx redirection (to the initial form, for example):
ModelAndView mv = new ModelAndView("redirect:/display-form");
// .. as before ..
My application has a method to update a conference. After doing so I have a modelandview with a redirect to the main conference list. This all works fine although the message which I add as an object to the modelandview does not display.
My method in my controller:
#PostMapping("/updateConference")
public ModelAndView updateConference(
#ModelAttribute("conference") #Valid ConferenceDto conferenceDto, BindingResult result) {
if(result.hasErrors()){
return new ModelAndView("updateConference","conferenceDto", conferenceDto);
}
try {
conferenceService.updateConference(conferenceDto);
} catch (ConferenceAlreadyExistException uaeEx) {
ModelAndView mav = new ModelAndView("updateConference","conferenceDto", conferenceDto);
mav.addObject("message", uaeEx.getMessage());
return mav;
}
ModelAndView mav = new ModelAndView("redirect:/teacher/configure"); // Problem is here
mav.addObject("message", "Successfully modified conference.");
return mav;
}
In my html I have the line:
<div th:if="${message != null}" th:align="center" class="alert alert-info" th:utext="${message}">message</div>
After updating the conference it goes back to configure.html although the message does not show. In the url I can see http://localhost:8080/teacher/configure?message=Successfully+modified+conference
I have looked at this thread although it did not help.
I tried to experiment by setting ModelAndView mav = new ModelAndView("configure") and the message displays but my conference list is empty and the url is http://localhost:8080/teacher/updateconference
Any tips is highly appreciated!
EDIT
I have tried to use RedirectAttributes as crizzis pointed out & this page and have this now:
#PostMapping("/updateConference")
public String updateConference(
#ModelAttribute("conference") #Valid ConferenceDto conferenceDto, BindingResult result, RedirectAttributes attributes) {
if(result.hasErrors()){
attributes.addFlashAttribute("org.springframework.validation.BindingResult.conferenceDto", result);
attributes.addFlashAttribute("conferenceDto", conferenceDto);
return "redirect:/teacher/updateConference";
}
try {
conferenceService.updateConference(conferenceDto);
} catch (ConferenceAlreadyExistException uaeEx) {
attributes.addFlashAttribute("conferenceDto", conferenceDto);
attributes.addFlashAttribute("message", uaeEx.getMessage());
return "redirect:/teacher/updateConference";
}
attributes.addFlashAttribute("message", "Successfully modified conference.");
return "redirect:/teacher/configure";
}
My get method:
#GetMapping(path = "/updateConference/{id}")
public String showUpdateConferenceForm(#PathVariable(name = "id") Long id, Model model){
Optional<Conference> conference = conferenceService.findById(id);
if (!model.containsAttribute("ConferenceDto")) {
model.addAttribute("conference", new ConferenceDto());
}
return "updateConference";
}
This works as intended and my message is shown on my configure.html . However, when I have an error in BindingResults the application goes to an error page and I get this in the console:
Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported]
Use RedirectAttributes which has addFlashAttribute method. You can set the success or failure message like you did and access that message through the key in the redirected page as you need.
when the error occurs you are redirecting to the same method instead of this you can just render the template in case there is error. I do this way.
I have the following controller method. A user submits a search form with 4 input fields and has to fill in at least one of the field. If all the fields are empty (using the validator) then an error will be displayed on top of the form (in the same page).
Otherwise it will use the service method to look for users and display the results at the bottom of the form (in the same page). That is why in the if statement I return the same page as well as the end of the method because whatever happens the user is directed to the same page
#RequestMapping(value="/search", method={RequestMethod.POST})
public ModelAndView searchUser(#ModelAttribute("searchUserDTO")SearchUserDTO searchUserDTO, BindingResult bindingResult, ModelMap modelMap){
validate(searchUserDTO, bindingResult);
List<BlueUser> users = new ArrayList<>();
if (bindingResult.hasErrors()) {
modelMap.put("searchUserDTO", searchUserDTO);
return new ModelAndView(VIEW_USERS, modelMap);
} else {
users = BlueUserService.findUsers(searchUserDTO.getMyName, searchUserDTO.getSSID(), searchUserDTO.getPostcode(), new Email(searchUserDTO.getMail()));
}
modelMap.put("searchUserDTO", users);
return new ModelAndView(VIEW_USERS, modelMap);
}
validator method
#Override
public void validate(Object target, Errors errors) {
SearchUserDTO dto = (SearchUserDTO)target;
if(dto.getMyName()==null && dto.getSSID() == null && dto.getPostcode() == null && dto.getMail()==null){
errors.reject(EMPTY, "Please fill in the form");
}
}
I use reject to return error in the global scope and not on specific field and the following test method:
public static final String BINDING_RESULT = BindingResult.class.getName() + '.' + "searchUserDTO";
#Test
public void searchUserPOST() throws Exception{
MultiValueMap<String, String> paramMap = mockMVCTestUtil.createParamMap("myName", null,
"ssid", null,
"postcode", null,
"mail", null);
MvcResult mvcResult = this.mockMvc.perform(
post("/search")
.params(paramMap))
.andExpect(model().attributeExists("searchUserDTO"))
.andExpect(model().attributeHasErrors("searchUserDTO"))
.andExpect(status().isOk())
.andExpect(redirectedUrl(VIEW_USERS))
.andExpect(forwardedUrl(VIEW_USERS))
.andReturn();
BindingResult bindingResult = (BindingResult) mvcResult.getModelAndView().getModel().get(BINDING_RESULT);
assertNotNull(bindingResult);
assertGlobalErrorMessage(bindingResult, "Please fill in the form");
}
When I run the test method it fails and i get the following error messages:
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: No errors for attribute 'searchUserDTO'
What am I doing wrong?
Using the redirectAttributes.addFlashAttribute("object",objectvalue);
Like this way it is successfully redirecting the object value to the next controller, but when we returned the view in the next controller it display the result in html page in browser. Then the problem starts when we refresh or reload the page then values disappears.
My code is
#RequestMapping(value = "/addRoom", method = RequestMethod.POST)
public String saveRoom(Room room,
ModelMap model, RedirectAttributes ra) {
amenitiesService.saveRoom(room);
Floor floor = amenitiesService.getFloorInfo(room.getFloorId());
String floorName = floor.getFloorName();
ra.addFlashAttribute(room);
ra.addFlashAttribute("floorName", floorName);
ra.addFlashAttribute("message","Room information is saved successfully.");
return "redirect:/redirectedUrl";
}
#RequestMapping(value = "/redirectedUrl")
public String redirecturl(Room room, ModelMap model) {
return ADMIN_VIEW + SAVE_ROOM;
}
please any one suggest me how to redirect the object values to next controller with permanent not temporary visible like flash attributes
use this it may be work
#RequestMapping(value = "/redirectedUrl")
public String redirecturl(Room room, ModelMap model, RedirectAttributes re) {
String name=(String)re.getFlashAttributes("floorName");
return ADMIN_VIEW + SAVE_ROOM;
}
How do I pass errors to a view file from a Controller implemented using Spring MVC? These errors are not form errors. Just business logic errors that will be shown inside a div in the "JSP" view.
Here is the controller action I have:
#RequestMapping(method = RequestMethod.POST)
public String processLoginForm(HttpServletRequest request, LoginForm loginForm,
BindingResult result, #SuppressWarnings("rawtypes") Map model)
{
loginForm = (LoginForm) model.get("loginForm");
String gotoURL = request.getParameter("gotoURL");
if (gotoURL == null || gotoURL == "")
{
String errorMessage = "No Redirect URL Specified";
return "loginerror";//loginerror is the view file I want to pass my error to.
}
model.put("loginForm", loginForm);
return "loginsuccess";
}
Thanks,
Change your method signature :
public String processLoginForm(HttpServletRequest request, LoginForm loginForm,
BindingResult result, ModelMap model)
You can put the error message in the ModelMap and forward it to the loginerror page.
if (gotoURL == null || "".equals(gotoURL))
{
final String errorMessage = "No Redirect URL Specified";
modelMap.addAttribute("errorMessage ", errorMessage);
return "loginerror";//loginerror is the view file I want to pass my error to.
}
You can fetch that in the div using EL.
<div>${errorMessage}</div>
Your method is
public String processLoginForm(HttpServletRequest request, LoginForm
loginForm, BindingResult result, #SuppressWarnings("rawtypes") Map
model)
The method #The New Idiot explained is
public String processLoginForm(HttpServletRequest request, LoginForm
loginForm,
BindingResult result, ModelMap model)
See that the Map model is replaced with ModelMap model
If you use this method, then you can use model.addAttribute to add error messages
You can use Spring support for exception handling..
HandlerExceptionResolver or #ExceptionHandler
#adarshr
Link
Hope it will be of some use.