passing data in querystring when using tiles - spring

I am using tiles2 and spring in my project. When i am redirecting from spring controller to a jsp(the jsp page is mapped in tiles.xml file) page using query string like:
return "showRes.jsp?subSucc=ok";
it shows me:
javax.servlet.ServletException: Could not resolve view with name 'showRes.jsp?subSucc=ok'
I think this is wrong way to passing data using query string.
Please tell me how can i do this.
Thanks
Shams

The Problem is that return "showRes.jsp?subSucc=ok"; statment should return the name of a jsp and it is NOT a URL.
The normal Spring way to pass values is a jsp is to use a Model Map (of course there are some other ways, but this is the easysest to describe one).
Have a look at the ModelAndView and Model class. Create an instance of it, set the view name and add your parameter, and then return it instead of the String.
Model model = new Model();
model.addAttribute("subSucc","ok");
ModelAndView modelAndView = new ModelAndView("showRes.jsp", model);
//may without ".jsp" postfix - this depends on your configuration
return modelAndView;

Related

Pass #ModelAttribute to href Spring MVC

I'm attempting to pass a calculated URL from server-side via #ModelAttribute and sometimes the href attribute in html (where I allocate this #ModelAttribute) appears to be empty and need to do multiple ctrl-f5 for finally set the URL.
My controller has something like that:
#Controller
....
String calculatedURL = calculateURL(request, user);
if(StringUtils.isBlank(calculatedURL)){
throw new Exception("Error calculating URL");
}
model.addAttribute("calculatedURL",calculatedURL);
return "myPage";
And in my JSP:
myLink
The problem is that sometimes this href value is "".
I tried to evaluate if calculatedURL is null or blank in my controller and throw exception if is it. This never happens and calculatedURL allways is passed with value.
Thanks in advance and so sorry for my English.
David.

Command object automatically added to model?

I have a controller method like this:
#RequestMapping("/hello")
public String hello(UserForm user) {
return "hello";
}
It receives some request parameters in the UserForm command object. But I have not written any code to add the object to the Model. Still, in the view hello.jsp, I'm able to access the data, like this:
Hello, ${userForm.name}!
Does it mean that Spring MVC adds command objects to the Model automatically?
You don't need #ModelAttribute just to use a Bean as a parameter.
You'll need to use #ModelAttribute or model.addAttribute() to load default data into your model - for example from a database.
Most of the Spring controllers in the real world accept a lot of different types of parameters - Path variables, URL parameters, request headers, request body and sometimes even the entire HTTP Request object. This provides a flexible mechanism to create APIs. Spring is really good at parsing these parameters in to Java types as long as there is an ObjectMapper (like Jackson) configured to take care of the de-serialization.
The RequestMappingHandlerAdapter makes sure the arguments of the method are resolved from the HttpServletRequest.
Spring model data created prior to (or during) the handler method
execution gets copied to the HttpServletRequest before the next view
is rendered.
By now, Spring has processed the HTTP request and it creates the ModelAndView object from the method’s return value. Also, note that you are not required to return a ModelAndView instance from a controller method. You may return a view name, or a ResponseEntity or a POJO that will be converted to a JSON response etc.
ServletInvocableHandlerMethod invocableMethod
= createInvocableHandlerMethod(handlerMethod);
if (this.argumentResolvers != null) {
invocableMethod.setHandlerMethodArgumentResolvers(
this.argumentResolvers);
}
if (this.returnValueHandlers != null) {
invocableMethod.setHandlerMethodReturnValueHandlers(
this.returnValueHandlers);
}
The returnValueHandlers object is a composite of HandlerMethodReturnValueHandler objects. There are also a lot of different value handlers that can process the result of your method to create ModelAndViewobject expected by the adapter.
Then, it has to render the HTML page that the user will see in the browser. It does that based on the model and the selected view encapsulated in the ModelAndView object.
Now, at this stage, the view gets access to the userForm (as in your example above) from the request scope.

Best Practice of reading text file in spring mvc

What is the best way to read HTML content from a text file and display the content in JSP? I have placed the text file in the resource folder using spring mvc 3. Normally I do this kind of stuff with Apache commons in struts but believe spring must have provided some utility for this.
I am thinking about reading it in a tag file. What utility should i use for that?
Ignoring the question of why you would want to do this. The return value from a Spring MVC controller method is usually used to resolve a view. The resolved view then becomes the response body. However, you can use the #ResponseBody annotation to make the raw return value the response body.
You can do it in the #RequestMapping method. The Key is the return type ModelAndView.
You read your text file and get the html that you need, after this, adding the html to the model and then return the a new ModelAndView Object.
Here's a sample:
#RequestMapping(value = "siteWithResHtml", method = RequestMethod.GET)
public ModelAndView loadSiteWithResHtml(Model model)
{
String resourceHtml;
// do your stuff for reading file and assign it to the String
model.addAttribute("resource_Html", resourceHtml);
return new ModelAndView("yourJSP", "model", model);
}
and in the jsp you can read the value from the model that you forwarded to the jsp, like this:
<div>${model.resource_Html}</div>
please take notice that the names are match.

ModelAndView Model objects not emptied on re-creation

My question is related to
Spring mvc interceptor addObject
At some point my application needs to know what the previousUrl is that has been visited, so in some occasions the previousUrl is stored in the ModelAndView and 'previous' can be called.
In another case I want to do a redirect and I don't want a previousUrl showing up in the URL bar of my browser. But when I try to initialize a new ModelAndView that old previousUrl object is still there. How is this possible?
The code
if (requestEmployee == null) {
LOGGER.warn("User [" + requestEmployeeName + "] not found.");
model = new ModelAndView(AbstractController.VIEW_REDIRECT_OVERVIEW, null);
return model;
}
should create a new ModelAndView without model objects so why is the previousUrl object still added to the URL as path variable in the browser?
This might depend on what your handler method signature is.
Spring's RequestMappingHandlerAdapter is actually adding model attributes from the returned ModelAndView to the existing model attributes. If you have Model as one of your handler method argument and you are adding some attributes there, they will get merged.

Handle url pattern that has user name as part of the url

Suppose I have 3 url patterns that needs to be handled by Spring MVC as follows:
1) www.example.com/login (to login page)
2) www.example.com/home (to my home page)
3) www.example.com/john (to user's home page)
I would like to know what is the best practice way of handling the url pattern that has username as part of the url (real world example is facebook fanpage www.faceboo.com/{fanpage-name})
I have come up with my own solution but not sure if this is the clean way or possible to do it.
In my approach, I need to intercept the request before it being passed to Spring MVC's dispatchservlet, then query the database to convert username to userid and change the request URI to the pattern that Spring MVC can recognize like www.example/user/userId=45.
But I am not sure if this is doable since the ServletAPI does not have the setter method
for requestURI(it does have the getter method for requestURI)
Or if you have a better solution please share with me. Thank in advance :-)
Spring MVC should be able to handle this just fine with PathVariables.
One handler for /login, one handler for /home, and one handler for /{userName}. Within the username handler you can do the lookup to get the user. Something like this:
#RequestMapping(value="/login", method=RequestMethod.GET)
public String getLoginPage() {
// Assuming your view resolver will resolve this to your jsp or whatever view
return "login";
}
#RequestMapping(value="/home", method=RequestMethod.GET)
public String getHomePage() {
return "home";
}
#RequestMapping(value="/{userName}", method=RequestMethod.GET)
public ModelAndView getUserPage( #PathVariable() String userName ) {
// do stuff here to look up the user and populate the model
// return the Model and View with the view pointing to your user page
}

Resources