Spring MVC not showing message from model - spring-mvc

I wrote a Spring MVC 3.1.1 controller to do stuff then return showing "Done".
My controller:
#Controller
public class HomeController {
#RequestMapping(value = {"/"}, method = RequestMethod.GET)
public String home(Model model) {
return "home";
}
#RequestMapping(value = {"/dostuff"}, method = RequestMethod.GET)
public String doStuff(ModelMap model) {
doStuff();
model.addAttribute("message", "Done");
return "redirect:/";
}
}
My home.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html><body>
${message}
</body></html>
PROBLEM: When I load http://localhost/myapp/dostuff the page does not show "Done", it is just empty. Also, the URL becomes http://localhost/myapp/?message=Done instead of going back to a clean http://localhost/myapp/. What did I do wrong?

Related

Spring validation messages are not displaying in JSP using internal resource view resolver

MVC controller, facing issue in validation message in JSP:
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String registerSuccess(#Valid #ModelAttribute Registerbean register, Model model, Errors error) {
if (error.hasErrors()) {
return "Registration";
} else {
return "home";
}
}

Spring MVC - Request Return Value in Browser

I imported the Getting Started - Securing a Web Application in STS and added a controller for navigation, the request gets called and the return value instead of redirecting gets displayed in the browser. Any idea why it does this and how to fix it?
Here is the code:
#RestController
public class BetController {
#RequestMapping("/")
public String username(Model model) {
System.out.println("Test");
model.addAttribute("username", WebSecurityConfig.getUsername());
return "statpage";
}
The page start page is registered in this manner:
#Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("startpage");
registry.addViewController("/login").setViewName("login");
}
All I get in the browser is a blank page with "startpage" on it, looking at the page's source there is no html just "startpage"
Returning ModelAndView instead of a String in the RequestMapping method solved the problem:
#RequestMapping("/")
public ModelAndView username(Model m) {
ModelAndView mav = new ModelAndView();
mav.addObject("username", WebSecurityConfig.getUsername());
mav.setViewName("betting");
return mav;
}
Another solution is changing #RestController to #Controller and making sure all the names match

Can we get HttpRequest Object in Controller in Spring MVC

Is it possible that I can get HttpRequest object in my Controller class in Spring MVC ?
#Controller
public class ContactController {
#Autowired
private ContactService contactService;
#RequestMapping("/login")
public String displayLoginPage(#ModelAttribute("login") Login login, BindingResult result) {
return "login";
}
}
#RequestMapping("/login")
public String displayLoginPage(HttpServletRequest request, #ModelAttribute("login") Login login, BindingResult result){
return "login";
}

How should I add attribute after redirect to a controller

I am just a newbie about Spring.
I am now using #ExceptionHandler to handle all the exception for my web application. And after I catch the exception, it will go to and error.jsp page displaying the error message.
I have a ParentController and in that, I have:
#org.springframework.web.bind.annotation.ExceptionHandler(PortalException.class)
public ModelAndView handle(PortalException e, HttpServletRequest request) {
ModelMap map = new ModelMap();
map.addAttribute("message", e.getMessage());
return new ModelAndView("/error", map);
}
and I have a ErrorControllerextends the ParentController to add the attributes:
#Controller
public class ErrorController extends ParentSecureController {
#RequestMapping(value = "/error", method = RequestMethod.POST)
#ResponseBody
public String errorHandler(Model model, HttpServletRequest request) {
model.addAttribute("excetpion.message", request.getParameter("message"));
return "/error";
}
}
In the error.jsp:
<p>Excpetion is: ${exception.message}</p>
When I run my application, I can catch the exception and jump to error.jsp, but no exception message is display.
Anyone can help me to figure out how to solve it.
Please try use:
#Controller
public class ErrorController extends ParentSecureController {
#RequestMapping(value = "/error", method = RequestMethod.POST)
#ResponseBody
public String errorHandler(Map<String, Object> map, HttpServletRequest request) {
map.put("excetpion.message", request.getParameter("message"));
return "/error";
}
}
UPDATE
Map you get it messae from #Controller to View in this case error.jsp
I hope these helped! :)

How to pass complex type using json to ASP.NET MVC controller

I have a View that allows a user to enter/edit data for a new Widget. I'd like to form up that data into a json object and send it to my controller via AJAX so I can do the validation on the server without a postback.
I've got it all working, except I can't figure out how to pass the data so my controller method can accept a complex Widget type instead of individual parameters for each property.
So, if this is my object:
public class Widget
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
I'd like my controller method to look something like this:
public JsonResult Save(Widget widget)
{
...
}
Currently, my jQuery looks like this:
var formData = $("#Form1").serializeArray();
$.post("/Widget/Save",
formData,
function(result){}, "json");
My form (Form1) has an input field for each property on the Widget (Id, Name, Price). This works great, but it ultimately passes each property of the Widget as a separate parameter to my controller method.
Is there a way I could "intercept" the data, maybe using an ActionFilterAttribute, and deserialize it to a Widget object before my controller method gets called?
Thanks Jeff, that got me on the right path. The DefaultModelBinder is smart enough to do all the magic for me...my problem was in my Widget type. In my haste, my type was defined as:
public class Widget
{
public int Id;
public string Name;
public decimal Price;
}
Notice that the type has public fields instead of public properties. Once I changed those to properties, it worked. Here's the final source code that works correctly:
Widget.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Widget.aspx.cs" Inherits="MvcAjaxApp2.Views.Home.Widget" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
<script type="text/javascript">
function SaveWidget()
{
var formData = $("#Form1").serializeArray();
$.post("/Home/SaveWidget",
formData,
function(data){
alert(data.Result);
}, "json");
}
</script>
<form id="Form1">
<input type="hidden" name="widget.Id" value="1" />
<input type="text" name="widget.Name" value="my widget" />
<input type="text" name="widget.Price" value="5.43" />
<input type="button" value="Save" onclick="SaveWidget()" />
</form>
</asp:Content>
HomeController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace MvcAjaxApp2.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Title"] = "Home Page";
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
ViewData["Title"] = "About Page";
return View();
}
public ActionResult Widget()
{
ViewData["Title"] = "Widget";
return View();
}
public JsonResult SaveWidget(Widget widget)
{
// Save the Widget
return Json(new { Result = String.Format("Saved widget: '{0}' for ${1}", widget.Name, widget.Price) });
}
}
public class Widget
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
Note that (in MrDustpan's solution) the parameter name widget in the MVC Action method must match with the prefix used in the name attribute in the ASPX file.
If this is not the case then the Action method will always receive a null object.
<input type="text" name="widget.Text" value="Hello" /> - OK
<input type="text" name="mywidget.Text" value="Hello" /> - FAILS
Phil Haack has a good blog post about model binding that might be helpful. Not 100% what you're talking about here, but I think it might give you a better overall understand about the DefaultModelBinder.
What you want to do is structure your javascript form object in the same way your backend object is structured:
{ Id : "id", Name : "name", Price : 1.0 }
Then use the toJSON plugin to convert it into the above string. You send this string to your backend and use something like the JayRock libraries to convert it to a new Widget object.

Resources