Best Practice of reading text file in spring mvc - spring

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.

Related

Is thera any ways to use html template in controller and then add it to a new ModelAndView?

I have one html template for multiple get requests. However, each request only have a piece of html code that is different from others. The code is a little complicated that does not proper to write with Java strings. So I try to make a template html file, then I will use Java to read the html file and replace the variables with new values. I don't know if there is some way to write values into a html file, and then read the html file to a String variable in Java, and then use ModelAndView to add the html String variable to views. The sample code is as follows:
// sample code in controller
ModelAndView mav = new ModelAndView("test.html");
String htmlTemplate = FileUtils.readToString(filepath);
String username = "xx";
htmlTemplate.replace("$username", username);
mav.addObject("usernameHTML", htmlTemplate);
return mav;
I don't know whether this way of coding is proper. Or how to solve this problem?

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.

RequestMapping doesn't redirect

#RequestMapping(value = "/{Id}", method = RequestMethod.GET)
public String searchCity( #PathVariable ("Id") Long Id) {
mymethod.something(id);
return "successpage";
}
When I'm trying to write some number it print me Eror 404 resource is not available, but when I write {Id} ("7DId7D" smthing like this) it redirects me to succespage, What is the problem? Help me please...
The information you provided conflicts with known behavior of Spring MVC
http://localhost:8080/MyCountryProject/7 should maps to searchCity fine
http://localhost:8080/MyCountryProject/%7Bld%7D should not even map to searchCity
I would check following to further isolate the problem:
Are you sure you're testing against the right controller? If your controller has #RequestMapping("myController") then your URL would be http://localhost:8080/MyCountryProject/MyController/7
Are you sure you're posting with the correct HTTP method? If you're HTTP form is POST, it wouldn't map to searchCity method
The conversion from string into Long is done by Spring MVC builtin property editor, did you install your own property editor? If so debug this

Spring + Ehcache - can #Cacheable be used to cache the output of a jsp view

Basically, is it possible to do this:
#Cacheable(cacheName="default")
#RequestMapping("getContent/{name}")
public String getContentByNameHandler(#PathVariable String name, Model model) {
ContentService contentService = domainService.getContentService();
model.addAttribute("model",contentService.getContentByName(name));
return RESOURCE_FOLDER + "content";
}
When I try this, the view is cached, but the only the plain content of the jsp is returned from the cache, not the jsp view after the simple jsp view rendering logic has completed. I'm on spring 3.0.7, so still using the ehcache-spring-annotations (http://code.google.com/p/ehcache-spring-annotations)
#Cacheable works by simply forming a key based on all input parameters, and putting the return value under that key.
So it won't store the processed view - it will simply store the view name.
Normally, you'd use browser caching for that instead of server-side caching. And since rendering the view is supposed to be less consuming than generating the content, you'd put #Cacheable on the service method.

passing data in querystring when using tiles

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;

Resources