how to restric Servlet Mapping only for some extensions - java

I would like to use Cutome servlet only for url which are not having extensions like .jsp,jss,css and image extensions.
I tried like this but no use.
Web.xml :
<filter>
<filter-name>ControllerFilter</filter-name>
<filter-class>tut.controller.ControllerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ControllerFilter</filter-name>
<servlet-name>ControllerServlet</servlet-name>
</filter-mapping>
<servlet>
<servlet-name>ControllerServlet</servlet-name>
<servlet-class>tut.controller.ControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ControllerServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>FileServlet</servlet-name>
<servlet-class>tut.controller.FileServlet</servlet-class>
</servlet>
Filter :
String requestedUri = ((HttpServletRequest)request).getRequestURI();
System.out.println("requestedUri:"+requestedUri);
if(requestedUri.matches(".*[css|jpg|png|gif|js|jsp]*")){
//How to configure the default calling here
return;
}
else
{
// ControllerServlet for other requests
chain.doFilter(request, response);
}

Try with $ that represents The end of a line in regex pattern
requestedUri.matches(".*[css|jpg|png|gif|js|jsp]$")
If matched then follow the chain otherwise forward the request to the required Servlet, JSP or HTML.
if (uri.matches(".*[css|jpg|png|gif|js|jsp]$")) {
filterChain.doFilter(req, res);
}else{
// forward the request to Servlet/JSP/HTML
req.getRequestDispatcher("path").forward(req, resp);
}
web.xml:
use / as url pattern for filter to inspect all the request then based on uri forward it to Servlet/JSP/HTML in the filter itself.
<filter-mapping>
<filter-name>ControllerFilter</filter-name>
<servlet-name>/</servlet-name>
</filter-mapping>
Find a better solution here Servlet for serving static content

I don't think that Filter is a good mechanism for achieving what you want. If Filter gets a request for unwanted extensions, it's too late to deal with this.
You can modify your request and response in Filter to do pre-processing or post-processing, but it's probably not what you're looking for. You want those extensions not to be routed to the servlet at all, but rather be processed by a static content handler.
To do what you want you'll need to put your static content to a folder which is not under path that can match Servlet path, otherwise your servlet is going to get requests for the static content at which point you'll need to do something about those requests inside your servlet.

Related

what happens when I configure a servlet before a filter in tomcat's web.xml?

In tomcat for a certain url, I want to skip all the filters and execute a servlet and I thought placing the servlet before the filter will to as I expected but still the filters behind the servlet mappings are executing. Am I doing anything wrong?
For instance, this is my web.xml
<servlet>
<servlet-name>APIRedirection</servlet-name>
<servlet-class>com.test.APIRedirection</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>APIRedirection</servlet-name>
<url-pattern>/abc/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>filter</filter-name>
<filter-class>com.test.filter</filter-class>
</filter>
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
So when the incoming url contains "/abc/" I want my servlet to execute and skip the filters. I placed my servlet before all the filters but still the filters are getting executed when the incoming url contains '/abc/'.
There is no concept of servlet before filter.
If servlets url mapping qualify filters url mapping then filter is executed before servlet.
I got your requirement you just don't want to hit Filters for certain urls.
a. If your application is still in starting phase, you can configure as given below
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/filtered/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/filtered/servlet2</url-pattern>
</servlet-mapping>
...
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>/filtered/*</url-pattern>
</filter-mapping>
And the servlet url for which you want to bypass filter
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/unfiltered/servlet1</url-pattern>
</servlet-mapping>
2. If your application is already developed, and you configured a filter already with mapping /* then you can not skip that filter being executed. But you can add one more filter before that filter. Here filter order plays an important role,(reference for filter order) you can perform same functionality which you expected from a servlet. In your filter you just have to break filter chain and send response as given below
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,ServletException
{
//your business logic
// construct responseToSend
response.getOutputStream().write(responseToSend);
return;
}
For more information of breaking filter chain refer this question

About Welcome Page and Accessing Web Service Methods

I have a problem with configuration ( or basic understanding how things work at background). I create a JAVAEE project by checking Web application and ReSt api checkbox ( in intellij with glassfish 5.0). I have sample code below which web methods work but welcome page does not work. My web.xml and sample web service methods are below.
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>test</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
**<url-pattern>/ *</url-pattern>**
</servlet-mapping>
#Path("/RestTest")
public class TestString {
#Context
ServletContext context;
#GET
#Path("insertdb/{param1}/{param2}")
#Produces(MediaType.APPLICATION_JSON)
public Object writeToDb( #PathParam("param1") String param1
,#PathParam("param2") String param2){
try{
String password= context.getInitParameter("DbPassword");
Class.forName("org.mariadb.jdbc.Driver");
Connection dbCon = DriverManager.getConnection(
"jdbc:mariadb://xxx/testdb", "root", password);
PreparedStatement stmt=dbCon.prepareStatement(
"INSERT INTO TestTable VALUES(?,?)");
stmt.setString(1,param1);
stmt.setString(2,param2);
stmt.executeUpdate();
dbCon.close();
return "Success";
}catch(SQLException | ClassNotFoundException ex){
return ex.toString();
}
}
#GET
#Path("sum/{sum1}/{sum2}")
#Produces(MediaType.TEXT_HTML)
public String calculateSum(#PathParam("sum1") int param1
,#PathParam("sum2") int param2){
return ""+(param1 + param2);
}
If i change this line url-pattern "/*" to "/"
then welcome page is accessible but not methods.
Thus what i want is, having a welcome page which i will use for documentation for my web services(i dont want SOAP) and web methods must work by adding / to base url. How can i achieve that and what is difference between /* and /
See here for explanation of differences:
What is url-pattern in web.xml and how to configure servlet
Generally for a rest api it is best to use a path specific to all rest calls, for instance http://localhost/mywebapp/rest/...
Something like:
<servlet-mapping>
<servlet-name>jersey-servlet/servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
You only want jersey serving particular URLs when it is bundled in a WAR that also includes html pages.
To answer your question, difference between "/" and "/*"
A mapping that contains the pattern "/" matches a request if no other pattern matches. This is the default mapping. The servlet mapped to this pattern is called the default servlet. The default mapping is often directed to the first page of an application. Example :
Both requests will display same contents from index.jsp
http://myhost.com/index.jsp
and
http://myhost.com/
Now, a mapping that contains "/*" overrides all other servlets, including all servlets provided by the servlet container 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.
Possible solution for your issue
Change the URL pattern to specific instead of default pattern.
<servlet>
<servlet-name>webservice</servlet-name> //servlet name
<servlet-class>com.rest.MyRestServlet</servlet-class> //servlet class
</servlet>
<servlet-mapping>
<servlet-name>webservice</servlet-name> //servlet name
<url-pattern>/RestTest/*</url-pattern> //all webservice request
</servlet-mapping>
All the web service request are accessible through
http://myhost.com/RestTest/
You may also be interested to look
What is URL-pattern in web.xml and how to configure servlet
Basics of Java Servlet
Servlet configuration and url-pattern
As you highlighted, your problem revolves around those four lines:
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
As Jim Weaver mentioned, it's a matter of url-pattern.
Solution(s)
You may consider three solutions (from the most-preferred to least-preferred):
dedicated REST URL: the easiest way is to have a dedicated url-pattern such as /rest/* for your web services. You can benefit some assets such as url hierarchy or you can easily implement a security framework over it.
URL rewriting may be an option and this answer suggests some library. I haven't tested those libraries myself
Page redirection can be an option to go around REST filtering but in the specific case of having the url-pattern at /*, I have to say I'm not sure if it's working for the reason I'll explain in next section
now a bit of explanation of what happened
Why setting the url-pattern at /* prevent from accessing the welcome page?
Actually, it's not only the welcome page that is not accessible: it's all the resources under the defined url-pattern. Whatever get in touch with REST stays with REST... Here is the schema taken from JSR 339 Appendix C:
With a GlassFish 5.0, I guess you're using JAX-RS 2.1 (JSR 370) but the sections I'm quoting have the same content
Without entering into detail, it is visible that only ContainerRequest Filters are executed in the process. Especially, it's worthy to notice that after Request Matching, requests are not forwarded to any servlet in a sense that standard resources are not reachable, unless specified by the REST method.
It's also worthy to highlight the fact the servlet filters are executed beforehand (leveraging this point is absolutely vital for managing security for example). I did not find back the source proving this point but I know it's somewhere on the web ^^.
Request matching is defined at section 3.7.2. In a nutshell, it is in three steps where the first one is the most important for your question, especially at step D:
Identify a set of candidate root resource classes matching the request
c. ...
d. If [the set of classes whose path matches the request URL] is empty then no matching resource can be found, the algorithm terminates and an implementation MUST generate a NotFoundException (404 status) and no entity
e. ...
highlights are mine.
The two last steps are
Obtain a set of candidate resource methods for the request
Identify the method that will handle the request
TL;DR
What happened when you set <url-pattern>/*<url-pattern> and tries to access to your welcome page (or any page actually):
Your server receives the GET request
If there are filters (such those from a security framework), there are executed
REST enters the scene
Pre Match filters are executed (none if your case)
Fetch your root resources classes (in your example, all classes in the test package)
Find if one of those class match the request URL
None are found, a 404 status is returned
To avoid unnecessary URL conflicts, the best options would be having a dedicated URL for your REST methods
If you mention in web xml like following all the request receive by 'Jersey Web Application' servlet. so request to index.jsp also redirect to 'Jersey Web Application' servlet
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
To avoid this add some prefix to the url to separate rest request like following
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>rs/*</url-pattern>
</servlet-mapping>

Using URL pattern as /* in REST webservice?

<servlet-mapping>
<servlet-name>JAX-RS REST Servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
for my
<servlet>
<display-name>JAX-RS REST Servlet</display-name>
<servlet-name>JAX-RS REST Servlet</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
Servlet i.e the entry point of my app. In many examples I see everyone gives some path in the URL pattern but in my case I am just using /*. Is this ok? Or using some path in it has some benefits? Like faster URL matching? i.e the request if for the web service or so?
Firstly, it is not incorrect to have a /*.
If you have only one listener processing all incoming requests then what you have is absolutely fine. If you have multiple listeners/services processing different url patterns then of course, you will have different mappings for different url patterns.
I prefer to add a full url pattern like /path1/xyz/* if i know the pattern instead of /* so you i dont need to modify this mapping when i add another mapping/listener to process a different url pattern.

Trouble with web.xml url pattern

In my web.xml I have URL pattern for servlet like this:
<url-pattern>/*/myservice</url-pattern>
So I want to call it using blablabla/myservice also as anyWord/myservice.
But it doesn't work. It work only if I call it using this URL: /*/myservice (with asterisk in URL).
You can't do that.
According to the Servlet 2.5 Specification (and things aren't that different in other levels of the specification), chapter SRV.11.2:
A string beginning with a / character and ending with a /* suffix
is used for path mapping.
A string beginning with a *. prefix is used as an extension mapping.
A string containing only the / character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and
the path info is null.
All other strings are used for exact matches only.
Your case falls under the 4th bullet, so exact mapping is used.
To circumvent that, use a mapping of / (third case). Map all requests to go to a particular servlet, and have that servlet re-route requests to handlers of some sort (either other servlets, or some custom classes).
For example:
<url-pattern>/</url-pattern>
<servlet-name>MyServlet</servlet-name>
And then, within MyServlet's code, inspect the URL that you received in the request (using request.getPathInfo()) and use the value to forward the request to other handlers.
You could use a filter while your url pattern is /* and inside the filter decide which redirection you required.
<filter>
<display-name>MyFilter</display-name>
<filter-name>MyFilter</filter-name>
<filter-class>com.MyfilterClass</filter-class>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</filter>
What about two ULR-mapping sections?
<servlet-mapping>
<servlet-name>ModifyMemberSVL</servlet-name>
<url-pattern>/ModifyMember</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ModifyMemberSVL</servlet-name>
<url-pattern>/Administration/Add_Member/ModifyMember</url-pattern>
</servlet-mapping>

url pattern syntax (java servlet)

I want to do something like this:
localhost:7001/servlet/character?name=zombies
I tried doing this:
<servlet-mapping>
<servlet-name>zombies</servlet-name>
<url-pattern>/character?name=zombies</url-pattern>
</servlet-mapping>
but it doesn't work and giving me not found error. Any advice or solution on how to do it?
The ?name=zombies portion of your url-pattern should not be used in the web.xml. It is a query parameter that is not actually a part of the servlet mount point. You would need to access the variable name in your zombies servlet via request.getParameter("name").
you are trying to append query string the stuff followed by ? with your URL pattern.
URL pattern is meant to map your servlet class. if you can pass query string in the address bar itself.
If you want to pass a parameter to your servlet then do like this
<servlet>
<servlet-name>zombies</servlet-name>
<servlet-class>com.ZombiesDemo</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>zombies</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>zombies</servlet-name>
<url-pattern>/character</url-pattern>
</servlet-mapping>
This you can retrive in ZombiesDemo.java servlet as
public void init(ServletConfig servletConfig) throws ServletException{
String name = servletConfig.getInitParameter("name");
}

Categories