I created registration Controller. Everything works fine, user is create in database but then end service program doesnt go to successRegister view. I dont know why. If I return like String successRegister everything is ok.
#RequestMapping(value = "/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ModelAndView registerUserAccount(#RequestBody #Valid User accountDto,
BindingResult result, WebRequest request, Errors errors) {
if (result.hasErrors()) {
return new ModelAndView("successRegister", "User", accountDto);
}
User registered = userService.register(accountDto);
if (registered == null) {
result.rejectValue("email", "message.regError");
}
try {
String appUrl = request.getContextPath();
eventPublisher.publishEvent(new OnRegistrationCompleteEvent
(registered, request.getLocale(), appUrl));
} catch (Exception me) {
return new ModelAndView("successRegister", "User", accountDto);
}
return new ModelAndView("successRegister");
}
Problem was with AJAX. I changed location after success and then ModelAndView was not return.
Your problem is with this
produces = MediaType.APPLICATION_JSON_VALUE
You says produces a JSON response but thats not true, you want to return a ModelAndView, so try to remove that attribute
Related
I'm testing a MVC ASP.Net Web Application and using NUnit to test its controllers. I test the Create method in the controllers and there's a step that it save changes to a stored local database. But NUnit always skips the save changes step. Is there anyway can solve it?
This is the method I coded in the controllers
[HttpPost]
public ActionResult Create([Bind(Include = "CourseId,CourseName,CoursCategoryId,Credit")] COURSE course)
{
try
{
if (ModelState.IsValid)
{
db.COURSEs.Add(course);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CourseCategagoryId = new SelectList(db.CourseCategorys, "CourseCategoryId", "CourseCategoryId", course.CourseCategoryId);
return View(course);
}
catch(Exception e)
{
return RedirectToAction("Create", "COURSEs", new { id = 1 });
}
}
And this is the test method I used to test that method
[Test]
[TestCase("IT01", "Computer Science", "PRA", 4, "Index")]
public void AddCourseTest(string CourseId,
string CourseName, string CourseCategoryId, int Credit, string expected)
{
COURSE course = new COURSE
{
CourseCategoryId= CourseCategoryId,
CourseName= CourseName,
CourseCategoryId= CourseCategoryId,
Credit= Credit
};
COURSEsController = new COURSEsController ();
RedirectToRouteResult result = COURSEsController .Create(course ) as RedirectToRouteResult;
Assert.AreEqual(expected, result.RouteValues["action"].ToString());
}
As expected that the course I'll add hasn't existed in our database, so the result will redirect to "Index" page. But when I debug the test method, It seems that when it runs to the db.SaveChanges(), it threw exceptions and always return to "Create" page.
I'm having an issue with RedirectAttributes not saving (i think). This is my code:
#RequestMapping(path = "/job_offers", method = RequestMethod.POST)
public String createJobOffer(#Valid #ModelAttribute("jobOfferForm") JobOfferForm jobOfferForm,
final BindingResult binding, RedirectAttributes attr) {
attr.addFlashAttribute("org.springframework.validation.BindingResult.jobOfferForm", binding);
attr.addFlashAttribute("jobOfferForm", jobOfferForm);
return "redirect:/job_offers";
}
#RequestMapping(path = "/job_offers", method = RequestMethod.GET)
public ModelAndView jobOffers(#RequestParam(required = false, value = "skill_id") final Long skillId,
#ModelAttribute("jobOfferForm") JobOfferForm jobOfferForm, final BindingResult binding) {
ModelAndView mav = new ModelAndView("job_offers/index");
mav.addAllObjects(getJobOffersMap(skillId));
mav.addObject("jobOfferForm", jobOfferForm);
return mav;
}
If I print my binding in the POST method it has the error in it, but when I call the GET method via the redirect the binding comes empty! and Spring doesnt show the error feedback on forms because of that
Any ideas?
Thanks!
Try this:
In your POST
attr.addFlashAttribute("bindignResultForJobOfferForm", binding);
And in GET
if (model.asMap().containsKey("bindignResultForJobOfferForm"))
{
model.addAttribute("errors",
model.asMap().get("bindignResultForJobOfferForm"));
}
#RequestMapping("/insert")
public String insertEmpDetails(#ModelAttribute("employee") Employee emp) {
if (emp != null)
empService.insertEmpDetails(emp);
return "redirect:/getList";
}
Please tell me what to write in else part.I was trying for that but i am not getting
Make employeeId as a required param to serve the request by this RequestMapping then you don't need to write else part because Employee model will never be null in that case. It must have at least employeeId.
Note: Make it POST request.
Example:
#RequestMapping(value = "/insert", params = "employeeId", method = RequestMethod.POST)
public String insertEmpDetails(#ModelAttribute("employee") Employee emp) {
empService.insertEmpDetails(emp);
return "redirect:/getList";
}
In other way you can validate the model and redirect to form page back with validation error messages.
Sample:
#RequestMapping(value = "/insert", params = "employeeId", method = RequestMethod.POST)
public String insertEmpDetails(#Valid #ModelAttribute("employee") Employee emp, BindingResult result, ModelMap model) {
if (result.hasErrors()){
model.addAttribute("error", "Your custom error messages");
return "<<back to form page without redirection>>";
}else {
empService.insertEmpDetails(emp);
return "redirect:/getList";
}
}
Read more about Spring - Validation, Data Binding, and Type Conversion
Read a post on Spring MVC : How to perform validation ?
I want to redirect after a upload, and want to redirect "files" page. but after submit successfully, the url in browser doesn't redirect, I also use firebug to check if there is any redirect, but not happen.
I change the "redirect:/files" to "redirect:/files.jsp" also not help.
is there any mistake?
Here is my code:
#Controller
#RequestMapping({ "/files", "/files/" })
public class FileAdminController {
#RequestMapping(value = { "/upload/index", "/upload", "/upload/" }, method = RequestMethod.GET)
public String showUplaod() {
return "upload";
}
#RequestMapping(value = { "/index", "/index/", "/" }, method = RequestMethod.GET)
public String showFilePage() {
return "files";
}
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public #ResponseBody String handleFileUpload(
#RequestParam("jarName") String jarName,
#RequestParam("manifestName") String manifestName,
#RequestParam("files") MultipartFile file) {
try {
File file1 = new File("c:/uploads/");
file1.getParentFile().mkdirs();
file1.createNewFile();
BufferedOutputStream stream = new
BufferedOutputStream(
new FileOutputStream(file1));
stream.write(bytes);
stream.close();
return "redirect:/files";
} catch (Exception e) {
return "You failed to upload " + jarName + " => " + e.getMessage();
}
}
}
redirect: is a view name which gets resolved by the UrlBasedViewResolver. But with #ResponseBody you tell spring that this controller is not returning a view name. I.e. you will have to take care about the redirect by yourself, by injecting the HttpServletResponse.
I am trying to call a Spring MVC controller through an ajax call from JavaScript method.The javascript method is using Prototype library to make the ajax call.The controller throws JSP as output.
I am able to hit the controller as i can see in the log messages however the response seems to get lost.What could be the issue.Here is the code....
function submitNewAjxCall() {
alert('test');
new Ajax.Request('SimpleApp/home.htm',
{
method:'post',
parameters: $('formId').serialize(true),
onComplete: showresult
});
}
function showresult(resultdata) {
alert(resultdata.responseText); ****//this method is not called.....****
}
home.htm point to this controller
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out.println("HomeController : " + ++i);
return new ModelAndView("home");
} --- this throws home.jsp
Thanks for your help.
Check with Firebug (Net tab) if you get the Ajax response and and see what its content is.
Maybe it makes sense to not return the whole HTML page but a JavaScript specific JSON object that's telling something about what the controller just did. Maybe add a ajax GET property to your controller where you just output plain JSON to the Response Body instead of returning the ModelAndView. Try to use onSucess in Prototype. Maybe that might work then
function submitNewAjxCall()
{
new Ajax.Request('SimpleApp/home.htm?ajax=true',
{
method: 'post',
parameters: $('formId').serialize(true),
onComplete: function(transport)
{
alert(transport.responseText);
}
});
}
Edit: To write JSON directly (e.g. using Flexjson as the serializer) you can use this in your (annotated) Spring controller:
#RequestMapping(value = "/dosomething.do", method = RequestMethod.GET, params = "ajax=true")
public void getByName(
#RequestParam(value = "name", required = true) String name,
HttpServletResponse response
)
{
response.setContentType("application/json");
try
{
OutputStreamWriter os = new OutputStreamWriter(response.getOutputStream());
List<DomainObjects> result = this.domainObjectService.getByName(name);
String data = new JSONSerializer().serialize(result);
os.write(data);
os.flush();
os.close();
} catch (IOException e)
{
log.fatal(e);
}
}