Dynamic content in all page in Spring MVC - spring

I am developing my site in Spring MVC with Sitemesh.
Dynamic content is changed oon every page, Menu and Footer I can include in template definition. But there comes a problem. On every site below the dynamic content there should be a news list with loaded some news from my DB. I created my #Controller and it loads 5 latest news, but how to add this on my template? What request mapping should implement my news controller?

I don't kwow how Sitemesh works, but I solved problems like that by using interceptor:
create a class that extends : HandlerInterceptorAdapter
Override the method postHandle and populate the modelAndView Object like this :
modelAndView.addObject("newslist",myNewsList);
So you will have a variable $newslist injected into all your views.
Don't forget to declare bean in your mvc-congig.xml :
<bean id="newsListInterceptor" class="mypackage.NewsListInterceptor"/>
As the interceptor is executed for each request I also use ehcache to store the result and avoid during a select in database for each call.

Related

Is there a way to retrieve data from redis in my jsp pages?

I am creating a spring boot server, and I would like the initial page (index.jsp) to be a datatable with information coming from the redis database. Anyone know how to do this with javascript or inside jsp pages?
First of all JSPs are outdated technology so I recommend you to go for thymeleaf which is a perfect choice with spring boot instead of JSP.
JAVA approach :
Just create a mapping with / base url and fetch Redis data using normal approach and use it in UI.
GetMapping("/")
public String index(){
//Fetch Redis data here add into model attributes
return "index";
}
JavaScript/inside JSP approach :
You can create a mapping method with some url like above and make an AJAX call on page load from the JSP page and get the JSON format data and use it.
Don't forget to put #ResponseBody annotation on top of the method which will return the data(JSON) instead of the page.
Refer call ajax to spring controller

Spring: How can I keep routes in sync with URLs on the page?

How can I keep links in my UI templates (e.g. Thymeleaf templates) in sync with the corresponding request mappings in my Spring application?
I've seen that e.g. the Play framework uses the #router-Object within its templates. How is it solved by Spring?
One example:
Spring Controller - simple
#Controller
public class UserController {
#GetMapping("/users/{username}")
public String getUser(#PathParam String username) {
// do some stuff....
return "user";
}
}
HTML-Page
<body>
User details
</body>
Now I want to change "/users" to "/accounts". I'm pretty sure that I've got to update every html page by hand to update the link. Is there an easier solution for this?
As far as I know, there is no simple way to do this with built-in tools from Spring. However, I don't think that this would be too hard to build. You would need the following:
A YAML file with all of your URL templates defined
A Properties Spring bean that contains your URL mappings (read from the YAML file)
All of your #RequestMapping annotations would have to be prop values; i.e.
#GetMapping("${urls.users.byUsername}")
A custom tag that knows about the Properties bean and can create URLs from the templates that were defined in your YAML file.

Spring MVC Load page automatically

I have a quick question about how to use the Spring MVC.
I just started with it and i was used to have pages that always had their data loaded calling some controller that you setted ON THE PAGE.. calling some methods on controllers to load objects at the page at load time.
Is it the same in Spring MVC? Cuz what im seeing so far is that if you want to load a page with data, you always have to use a modelandview object which is loaded by a method that you must call before... and them you return the modelandview object with its destination to the view that you want.
What im trying to know is if there is a way that the page requests some data from the controller before it gets loaded... automatically...
Dont know if im making my self clear... thanks anyway for the help!
in spring mvc, using Controllers, it is always Request->Controller(populates model and chooses view)->Response.
you could use ajax to load data from any resource (even Controllers) or jsp:useBean to explicitly call some business logic or jsp:include to include a certain fragment or a custom jsp tag.
I also face the same situation.
check the below link for getting the data from the controller before view(JSP) load.
how to load the data into index page

Spring MVC 3.0 - restrict what gets routed through the dispatcher servlet

I want to use Spring MVC 3.0 to build interfaces for AJAX transactions. I want the results to be returned as JSON, but I don't necessarily want the web pages to be built with JSP. I only want requests to the controllers to be intercepted/routed through the DispatcherServlet and the rest of the project to continue to function like a regular Java webapp without Spring integration.
My thought was to define the servlet-mapping url pattern in web.xml as being something like "/controller/*", then have the class level #RequestMapping in my controller to be something like #RequestMapping("/controller/colors"), and finally at the method level, have #RequestMapping(value = "/controller/colors/{name}", method = RequestMethod.GET).
Only problem is, I'm not sure if I need to keep adding "/controller" in all of the RequestMappings and no matter what combo I try, I keep getting 404 requested resource not available errors.
The ultimate goal here is for me to be able to type in a web browser "http://localhost:8080/myproject/controller/colors/red" and get back the RGB value as a JSON string.
You are not correct about needing to add the entire path everywhere, the paths are cumulative-
If you have a servlet mapping of /controller/* for the Spring's DispatcherServlet, then any call to /controller/* will be handled now by the DispatcherServlet, you just have to take care of rest of the path info in your #RequestMapping, so your controller can be
#Controller
#RequestMapping("/colors")
public class MyController{
#RequestMapping("/{name}
public String myMappedMethod(#PathVariable("name") String name, ..){
}
}
So now, this method will be handled by the call to /controller/colors/blue etc.
I don't necessarily want the web pages to be built with JSP
Spring MVC offers many view template integration options, from passthrough to raw html to rich templating engines like Velocity and Freemarker. Perhaps one of those options will fit what you're looking for.

How to use annotated Spring controllers with Freemarker to return custom ajax respones

I primarily use annotated controllers that return ModelAndView object used by Spring and Freemarker to render and return pages to browsers - works great. I'd now like to respond to ajax gets and posts that return html fragments as payload inside an XML message.
The problem I'm having not returning a ModelAndView objects seems to confuse Spring WRT to #ModelAttribute (s) and session objects that support data to / and from forms.
I've had to hack the freemarker template to support i18n messages, etc. I'm finding that simply rendering an FTL file while also trying to utilize Spring's object rendering from froms is becoming quite a rabbit hole.
I'm trying to manually (guess what and) do the things that get done behind the scenes and it's not working optimally. To edit an object I'm manually placing the object in the session on rendering the edit form. When the post comes back there are residual/different values in the object I get back out of the session AND the ModelAttribute that Spring rendered for me.
Bottom line? Questions about Spring, Freemarker and custom non-ModelAndView responses that are rendered by Freemarker.
Add another instance of FreeMarkerViewResolver that only that has viewNames ='*.frg'. The viewClass should be your own class that renders the template the way you want by overriding the processTemplate method.

Resources