My Servlet show product details by slug
#WebServlet("/*")
public class ProductDetails extends HttpServlet {
for example :
mywebsite.com/product-name
But they can't load css, js and img files because it detect the pathInfo for a slug.
How can I exclude them to not be loaded in the servlet?
Unfortunately the Servlet spec does not define exclusion rules for URL pattern mappings. Also, matched paths take precedence over matched suffixes (see Servlet 4 spec, paragraphs 12.1 & 12.2). The mapping on this Servlet will match anything in the application's context path, including static resources.
What can you do:
You can split the logic to handle static resources in that servlet. I would not go for it, it will probably complicate the code and hurt the separation of concerns.
If your static resources are inside a specific directory and no slug will match it (e.g. all JS, CSS, HTML, image files under assets/), you can have another Servlet that serves the static content under this directory (e.g. #WebServlet("/assets/*")). The longest path mapping that matches the request takes precedence. You still need to write code for sending a file back to the client; this code is fairly easy, you get a chance to customize the headers of the static files (e.g. caching), and, in comparison to the previous solution, the code that handles static files lies in it's own Servlet, so nice separation of concerns.
If you do not want to bother with serving static files yourself (I wouldn't blame you), you can move the logic from your Servlet to another class. Then introduce a Servlet filter that will first check if the request is a GET for a static resource and, if so, simply calls filterChain.doFilter(request,response) and lets the application server handle the static file. If not, it calls your logic and sends the response that your Servlet would have sent.
Finally, if you make your Servlet the default Servlet by #WebServlet("/") (not "/*"). It will pick up any request that other Servlets do not. The application server should have a Servlet installed for static content that will serve any existing CSS, JS, etc files from your application. Anything else will end up in your default Servlet.
If you could find a way to separate static content from dynamic content, e.g. all static content under assets/, all dynamic content under the virtual path content/ it would be much easier to change the mapping of your Servlet to /content/* and be done with it.
Related
I'm using Spark's (http://sparkjava.com/) static file routing, set up via:
externalStaticFileLocation('.../public');
for serving, amongst others, the index.html page placed in the public directory. So effectively, when you hit the server's URL, you get your index.html back. So far so good...
However, I would like to override this behavior when the request contains a specific Accept header, e.g., application/rdf+xml (basically different from the default text/html). In that case I would like to return some specific data rather than the index.html page.
Is there a simple way of achieving this in Spark? I couldn't find any solution to this in the documentation... Thanks for any tips!
Due to the change in the behavior you'd like to make, the content you want to serve now is no longer static, but dynamic.
You'll need to remove index.html from the static content directory and move it to resources directory (typically src/main/resources/templates).
Then, you'll need to create a route for the root of your domain name (/) and using a template engine serve the content.
When using a template engine you usually inject the dynamic data into a static template. Typically you do it using some sort of map.
In the case of text/html your map will be empty, and then it's like before -
serving a static page. If it's application/rdf+xml you'll fill the map with the relevant data and then serve the resulting dynamic page.
Example:
get("/", (request, response) -> {
if (isTextHtml(request)) {
// serve the index.html template as is (empty map, not null though)
// In this case index.html functinos as a static page
} else {
// use a map to have all relevant data for the index.html template
// In this case index.html functinos as a "real" template
}
});
The familiar code:
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
My understanding is that /* maps to http://host:port/context/*.
How about /? It sure doesn't map to http://host:port/context root only. In fact, it will accept http://host:port/context/hello, but reject http://host:port/context/hello.jsp.
Can anyone explain how is http://host:port/context/hello mapped?
<url-pattern>/*</url-pattern>
The /* on a servlet overrides all other servlets, including all servlets provided by the servletcontainer such as the default servlet and the JSP servlet. Whatever request you fire, it will end up in that servlet. This is thus a bad URL pattern for servlets. Usually, you'd like to use /* on a Filter only. It is able to let the request continue to any of the servlets listening on a more specific URL pattern by calling FilterChain#doFilter().
<url-pattern>/</url-pattern>
The / doesn't override any other servlet. It only replaces the servletcontainer's built in default servlet for all requests which doesn't match any other registered servlet. This is normally only invoked on static resources (CSS/JS/image/etc) and directory listings. The servletcontainer's built in default servlet is also capable of dealing with HTTP cache requests, media (audio/video) streaming and file download resumes. Usually, you don't want to override the default servlet as you would otherwise have to take care of all its tasks, which is not exactly trivial (JSF utility library OmniFaces has an open source example). This is thus also a bad URL pattern for servlets. As to why JSP pages doesn't hit this servlet, it's because the servletcontainer's built in JSP servlet will be invoked, which is already by default mapped on the more specific URL pattern *.jsp.
<url-pattern></url-pattern>
Then there's also the empty string URL pattern . This will be invoked when the context root is requested. This is different from the <welcome-file> approach that it isn't invoked when any subfolder is requested. This is most likely the URL pattern you're actually looking for in case you want a "home page servlet". I only have to admit that I'd intuitively expect the empty string URL pattern and the slash URL pattern / be defined exactly the other way round, so I can understand that a lot of starters got confused on this. But it is what it is.
Front Controller
In case you actually intend to have a front controller servlet, then you'd best map it on a more specific URL pattern like *.html, *.do, /pages/*, /app/*, etc. You can hide away the front controller URL pattern and cover static resources on a common URL pattern like /resources/*, /static/*, etc with help of a servlet filter. See also How to prevent static resources from being handled by front controller servlet which is mapped on /*. Noted should be that Spring MVC has a built in static resource servlet, so that's why you could map its front controller on / if you configure a common URL pattern for static resources in Spring. See also How to handle static content in Spring MVC?
I'd like to supplement BalusC's answer with the mapping rules and an example.
Mapping rules from Servlet 2.5 specification:
Map exact URL
Map wildcard paths
Map extensions
Map to the default servlet
In our example, there're three servlets. / is the default servlet installed by us. Tomcat installs two servlets to serve jsp and jspx. So to map http://host:port/context/hello
No exact URL servlets installed, next.
No wildcard paths servlets installed, next.
Doesn't match any extensions, next.
Map to the default servlet, return.
To map http://host:port/context/hello.jsp
No exact URL servlets installed, next.
No wildcard paths servlets installed, next.
Found extension servlet, return.
Perhaps you need to know how urls are mapped too, since I suffered 404 for hours. There are two kinds of handlers handling requests. BeanNameUrlHandlerMapping and SimpleUrlHandlerMapping. When we defined a servlet-mapping, we are using SimpleUrlHandlerMapping. One thing we need to know is these two handlers share a common property called alwaysUseFullPath which defaults to false.
false here means Spring will not use the full path to mapp a url to a controller. What does it mean? It means when you define a servlet-mapping:
<servlet-mapping>
<servlet-name>viewServlet</servlet-name>
<url-pattern>/perfix/*</url-pattern>
</servlet-mapping>
the handler will actually use the * part to find the controller. For example, the following controller will face a 404 error when you request it using /perfix/api/feature/doSomething
#Controller()
#RequestMapping("/perfix/api/feature")
public class MyController {
#RequestMapping(value = "/doSomething", method = RequestMethod.GET)
#ResponseBody
public String doSomething(HttpServletRequest request) {
....
}
}
It is a perfect match, right? But why 404. As mentioned before, default value of alwaysUseFullPath is false, which means in your request, only /api/feature/doSomething is used to find a corresponding Controller, but there is no Controller cares about that path. You need to either change your url to /perfix/perfix/api/feature/doSomething or remove perfix from MyController base #RequestingMapping.
I think Candy's answer is mostly correct. There is one small part I think otherwise.
To map host:port/context/hello.jsp
No exact URL servlets installed, next.
Found wildcard paths servlets, return.
I believe that why "/*" does not match host:port/context/hello because it treats "/hello" as a path instead of a file (since it does not have an extension).
The essential difference between /* and / is that a servlet with mapping /* will be selected before any servlet with an extension mapping (like *.html), while a servlet with mapping / will be selected only after extension mappings are considered (and will be used for any request which doesn't match anything else---it is the "default servlet").
In particular, a /* mapping will always be selected before a / mapping. Having either prevents any requests from reaching the container's own default servlet.
Either will be selected only after servlet mappings which are exact matches (like /foo/bar) and those which are path mappings longer than /* (like /foo/*). Note that the empty string mapping is an exact match for the context root (http://host:port/context/).
See Chapter 12 of the Java Servlet Specification, available in version 3.1 at http://download.oracle.com/otndocs/jcp/servlet-3_1-fr-eval-spec/index.html.
Suppose I have two Spring webapps deployed to the same Tomcat server instance:
A:
ROOT.war, context = /
#Controller
class TestController {
#RequestMapping("/api/someMethod")
public String someMethod() {
//..
}
#RequestMapping("/api/v1/someMethod")
public String someMethod() {
//..
}
}
B:
api#v1.war, context = /api/v1/
#Controller
class TestController {
#RequestMapping("/someMethod")
public String someMethod() {
//..
}
}
Which web application will be used to process the following HTTP requests?
GET http://<hostname>/api/someMethod
GET http://<hostname>/api/v1/someMethod
GET http://<hostname>/api/v1/nonexistentMethod
As you can see the second HTTP request matches both apps. I have tried to find answer in Tomcat docs, but found none. Where is specified how context path matching works?
According to Servlet 3.0 Specification
10.1 Web Applications Within Web Servers
A Web application is rooted at a specific path within a Web server.
For example, a catalog application could be located at
http://www.mycorp.com/catalog. All requests that start with this
prefix will be routed to the ServletContext which represents the
catalog application.
A servlet container can establish rules for
automatic generation of Web applications. For example a ~user/
mapping could be used to map to a Web application based at
/home/user/public_html/
12.1 Use of URL Paths
Upon receipt of a client request, the Web container determines the
Web application to which to forward it. The Web application selected
must have the longest context path that matches the start of the
request URL. The matched part of the URL is the context path when
mapping to servlets. The Web container next must locate the servlet
to process the request using the path mapping procedure described
below. The path used for mapping to a servlet is the request URL from
the request object minus the context path and the path parameters.
The URL path mapping rules below are used in order. The first
successful match is used with no further matches attempted:
The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the
servlet.
The container will recursively try to ma tch the longest path-pre fix. This is done by stepping down the path tree a directory at a
time, using the ’ / ’ character as a path separator. The longest
match determines the servlet selected.
If the last segment in the URL path contains an extension (e.g. .jsp ), the servlet container will try to match a servlet that
handles requests for the extension. An extension is defined as the
part of the last segment after the last ’ . ’ character.
Versions of this specification prior to 2.5 made use of these mapping techniques as a suggestion rather than a requirement,
allowing servlet containers to each have their different schemes for
mapping client requests to servlets.
If neither of the previous three rules re sult in a servlet match, the container will attempt to serve content appropriate for the
resource requested. If a "default" servlet is defined for the
application, it will be used. Many containers provide an implicit
default servlet for serving content.
Also Tomcat Request Process Flow might be useful
I have seen this answer
but it does not help my case.
I have a class that implements an HttpServlet. Now I want to place a URL inside it so that it has the following pattern: resource/identifier/resource.
For example, I want to make this REST call: http://example.com/owners/1234/dogs
I tried to place a URL like this in the servlet: http://example.com/owners/*/dogs, but the call never reached the servlet and was not handled.
If I understood well you want your servlet to be mapped to something like /owners/*/dogs.
Well, unfortunately Servlets can only use wildcards at the beginning or end of the mapping. So you would have to map it to /owners/* and then using request.getPathInfo() parse the rest of the url to extract the path info.
Your best options are to use the standard JAXRS or Spring MVC, both of which support path variables.
I am facing a task to add a dependent jar application to an existing one. The existing one does not use to much of locale benefits and so on, but my new one should.
So like I have now: localhost:8080/old-app
I want to have also: localhost:8080/[en|fr|...]/new-module
Could anyone point me the direction, because even if I think I get the idea of filters, filter-mapping, I cannot manage to solve it.
I would like to keep the old one and also have access to the new one.
Deploy new-module as ROOT.war (or set path in /META-INF/context.xml to /). Use Tuckey's URLRewriteFilter to rewrite specific URL's and transform the language part to a request parameter so that it's available by request.getParameter(). It's much similar to Apache HTTPD's mod_rewrite.
An alternative to URLRewriteFilter is to homegrow a custom filter which does like the following in doFilter() method.
String uri = request.getRequestURI();
if (uri.matches("^/\\w{2}(/.*)?$")) {
request.setAttribute("language", uri.substring(1, 3));
request.getRequestDispatcher(uri.substring(3)).forward(request, response);
} else {
chain.doFilter(request, response);
}
Map this on an url-pattern of /*. The language will be available by request.getAttribute("language") on the forwarded resource.
If you dont want the applications name as context root e.g. localhost:8080/appname but under / directly you have to put it into the tomcat/webapps/ROOT folder. To get more sophisticated URL mappings working have a look at http://ocpsoft.com/prettyfaces/