Is requestMapping needed for each page in Spring MVC - java

I read a big part of spring documentation, and I think that I missed this part.
Do I need requestMapping for each page in my webapp? Even for those static ones? For example if I have a page with few sites:
home
about me
contact
articles
SomeStaticPage
Do i need requestMapping in my controller for all of those pages?
For example if I want to go to the contact page, I have to add requestMapping for path /contact in my controller ? Or if I will have contact.jsp in my /WEB-INF/views, Spring will detect it automaticly without defining RequestMapping for it?
Or maybe in href property I should just add static path to /contact.jsp ?
Also, I am aware of that, if for example for articles page, I will want to have articles taken from database, I will have to add request mapping which will put that article list object in Model object.
I'm asking mainly for static pages.

Or if I will have contact.jsp in my /WEB-INF/views, Spring will detect it automaticly without defining RequestMapping for it
I don't think that Spring can do that for you. And you can't access anything that is in WEB-INF directly via URL either.
What you could do is this:
1: Place the pages (HTML, JSP, ...) you want to access directly (without creating controllers for them) for example in src/main/webapp/pages (this location assumes that you are using Maven) and configure Spring to serve these pages directly.
You could do this using this XML configuration:
<mvc:resources mapping="*.html" location="/pages/" />
2: you could use <mvc:view-controller /> tag in your Spring configuration to define mappings for your views. In this case you would still have to define mappings for each view as with #RequestMapping, but in this case it is just a single line of code.
Additional benefit of this solution is that you could keep your URLs consistent with the rest of the application.
<mvc:view-controller path="/" view-name="home" />
Java configuration alternatives to both examples are in the documentation mentioned below.
Sources and additional information
Configuring view controllers
Configuring static resources

Related

What means these mvc:resources mapping tags declared into the servlet-context.xml of a Spring MVC application?

I am pretty new in Spring and I am working on a Spring MVC application.
Into the servlet-context.xml configuration file I found these lines:
<!-- resources exclusions from servlet mapping -->
<mvc:resources mapping="/assets/**" location="classpath:/META-INF/resources/webjars/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/img/**" location="/img/"/>
<mvc:resources mapping="/js/**" location="/js/"/>
The comment say resources exclusions from servlet mapping.
What exactly means these lines? I know that this servlet-context.xml should contain the DispatcherServlet configuration that handle the MVC behavior (and it is pretty clear for me) but what exactly does the previous lines?
Can you explain me in details the meaning and the previous syntax?
If you consider a spring mvc configuration where all the requests are mapped to a DispatcherServlet, you can categorize those requests as requests for static and dynamic resources.
The requests for dynamic resources are matched by what you program inside your controller methods, and they are the subject of the typical framework processing such as path matching, content negotiation, validation, binding, conversion, formating, argument resolving.
The requests for static resources are the requests for .js, .css, or some other resources that are not getting created rather already exist deployed with your application. They are not handled by the programmatic controller methods rather by the ResourceHttpRequestHandler, simply because they have a completly different set of processing actions comparing to dynamic request (apart from path matching). You can define the location of static files for the given mapping (this can be the classpath, some other webapp folder or a file system), caching strategy for the resource, transformations (such as modyfing links in css, tranforming LESS to CSS)
So its not really that you don't want the static resources to be handled by the servlet, in fact you can get a lot of possibilities and flexibility by doing so, check for example handling static web resources it is just that static and dynamic requests are a subject of different kind of actions, and by using mvc:resources tag, you designate by mappings which requests are to be handled as static requests
As resources like images, css, javascript etc. are not supposed to be handled by servlet and to be specific by Dispatcherservlet, spring provides a way to specify them using
mvc:resources
tag. If such resource is not mapped using above tag, requested path will be used by dispatcher servlet to find a controller with matching request mapping.
But with the tag, spring looks into location attribute of tag to find and return the resource and if the resource is not found, HTTP status code 404 is returned.
Other helpful answers
Nice explanation of location attribute of the tag here
spring-3-mvc-resources-and-tag-mvcresources

How to override AutoConfiguration in Spring?

I have followed the Spring example Serving Mobile Web Content with Spring MVC and got it working.
Now I would like to replace greeting.html with a simple static page (and replace Thymeleaf with a simpler view handler).
What is the easiest approach in this particular case?
I am new to Java, the probable solutions in web use web.xml, whereas this example does not use web.xml and it does not seem to be the recommended approach in Spring Boot documentation either. So, use #EnableAutoConfiguration with some overriding? How?
All you have to do is put the static HTML file in a place where Spring Boot will automatically look for static resources. This part of the documentation provides all the details.
So for example you can place your greeting.html under /src/main/resources/static/ and you will be able to access it at http://localhost:8080/greeting.html (that's if you have not configured a different port of the root path of the servlet context)

Runtime loading of Controllers for Spring MVC and dynamically mapping requests/URLs

We are starting a new project using Spring MVC, and we would like to move away from annotation-driven request/url mapping. We wish to implement the following use case:
Use Case A
User enters a URL.
The request mapping handler retrieves a list of mappings (e.g. from the DB), and based on this dynamic list of mappings, it calls the relevant controller.
This is because we want to be able to do the following as well:
Use Case B
We want to load a new Controller (perhaps a new reports module) into the web app without having to redeploy or do a server restart.
We will map this new Controller to a URL and persist it somewhere (most likely the DB).
We would like the Controller to be registered in the Spring app context (managed by Spring).
We would then like to use this new Controller in the request mapping.
We've taken an initial look at the different ways we can implement this, but we are unsure of the best architecture/method to go about this route. A couple of questions:
For Use Case A, how do we implement this within the Spring MVC framework (or if it's possible)?
For Use Case B, is there a good framework or way to be able to do dynamically loading and registering of this for web applications? We've taken a cursory look at OSGI but it seems to be advisable for use in non-web applications.
For Use case A :
Instead of DB you can keep the url mappings in a property file and then use property place holder to initialize beans using xml configuration on context up. This way remaining inside the spring framework, you can avoid annotations.
For Use Case B :
Tomcat supports dynamic reloading of classes but that to of only non structural changes in class file. But this has memory leaks as well as it doesnt cleans up old instance of class loader rather it creates a new instance.
Its quite achievable using spring-mvc-router API.
Please check below link
url-action mapping & routing in Spring MVC 3.0
Here the URL can be configured to controller.method using .conf file, but this can be achievable using java configuration, and i haven't tried so far.
Also if xml configuration chosen, then check out the property 'autoReloadEnabled', but its not adviceable for production use.
Hope this helps!!!

Web application URL access java

I am trying to understand how the requests works. Unfortunately I was thrown at coding first and only then at understanding.
I wrote some really basic webapplication in java few years ago and it did work as expected. On its main web-page(.jsp) I had following as one of the menu buttons:
<p>test</p>
I am currently writing new webapp and forgot a lot. This time I am doing it with Spring MVC and properly. I can't really understand why this snippet no longer brings me to the home.jsp in current webapplication and why at first I did use it in old app.
Apache gives: The requested resource () is not available.
It is not that I need that sort of direct interaction, it is just I am trying to understand whether resources are accessible via URL? Does Spring MVC brings me extra security, where only servlet handled requests can result in a view? Am I missing something really trivial?
Moreover in that same old web app menu I had direct link to the servlet, but currently I can't make such direct reference to the servlet in the new webapp. I can make relevant request which will be captured by the servlet, but not by the name of it.
Apache gives: The requested resource () is not available.
Reference to servlet from menu:
<% if((String) session.getAttribute("passengerFound") != null){ %>
<img style="border:0" src="menuButtons/My Trips.png" alt="My Trips"/> <%} %>
Thanks, I bet it is really simple. I really want to understand, please help.
I know that it has something to do with Front Controller(dispatcherServlet), but I can't form logical and firm explanation in my head.
it is just I am trying to understand whether resources are accessible
via URL
In short, no. The default behavior and recommended configuration when using Spring MVC is to map the Spring DispatcherServlet to the / url pattern, meaning ALL requests are sent to the DispatcherServlet. Out of the box, the dispatcher-servlet will NOT service any requests for static resources. If this is desired, the two main options are
Map the DispatcherServlet to another pattern than root, effectivly isolating the Spring MVC portion to a sub-context
Add a resource-mapping to your spring context (your applicationContext.xml).
<mvc:resources mapping="/res/**" location="/res/" />
This above would tell spring mvc to treat all request to /res/** as requests for static resources (like images etc) and that those resources are physically located in the /res/ folder in the application root.
You might just be missing a "/" as in "/home.jsp" instead of "home.jsp"

Spring MVC REST : static files unaccessible because of url-pattern

My Spring Dispatcher servlet url-pattern is /* (as spring MVC REST suggests)
Now all the request are resolved by this Servlet. even CSS/JS/Images also get resolved and handled by servlet..
So, Spring MVC tries to find controller.. :(
How to bypass this? Is there any standard way out of this problem??
& Don't want to change url-pattern to /rest/* (so, other static resources get accessed by /css/ or /js etc.)
You can map your controllers to a smaller set of URLS (i.e. /app/*), and then rewrite the URLs that your users actually see so that they don't even know about. Have a look at the mvc-basic webapp sample, particularly web.xml and urlrewrite.xml to see how this is done.
Map the Spring dispatcher to some subsection of the URL space, and use Tuckey to rewrite URLs the user deals with.
http://www.example.org/app/controller/action -> http://www.example.org/controller/action
Just a heads-up update on this: the default rewrite configuration as defined in the Spring sample did not work out of the box for me. The rewrite rules for stylesheets, scripts, etc. were still processed to the /app/* rule, and subsequently handled by the DispatchServlet, which is not desirable.
I had to add the last="true" attribute to the styles/scripts/images rules to indicate that other rules should not apply, and I had to use the FreeMarker Spring URL macro in any CSS/JS include paths.
Just in case someone encounters the same problem.

Categories