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>
Related
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>
I wrote a filter to decide user landing page before it reach my welcome-file. The welcome-file is written in such a way that it takes input from the filter and navigate the user to a specific page.
My welcome-file tag is...
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
and my filter configuration is
<filter>
<filter-name>LandingPageFilter</filter-name>
<filter-class>com.mypack.test.filters.LandingPageFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LandingPageFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The above format is working good whilst every request is passing through this filter, which I want to avoid. When I hit http://localhost:8000/landing it should reach the filter for the first time only and later even if I access http://localhost:8000/landing/edit it should actually execute the relevant servlet bypassing the filter.
I tried this as well <url-pattern>/*/index.jsp</url-pattern> but no use. Why I use this because the context may vary but the app would be same.
Use
<url-pattern>/index.jsp</url-pattern>
instead of
<url-pattern>/*/index.jsp</url-pattern>
So your filter mapping part will become like this
<filter-mapping>
<filter-name>LandingPageFilter</filter-name>
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
Irrespective of the context this works because / represents the path after the context path.
For example if you have two context paths say a and b with two deployments of same application in your server and you are accessing them using the URLs
http://localhost:8000/a/
and
http://localhost:8000/b/
then / in the url-pattern represents / after context roots a and b. So your filter will be executed only for index.jsp.
The servlet config looks like this -
<servlet>
<servlet-name>smart</servlet-name>
<servlet-class>SuperSmart</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>smart</servlet-name>
<url-pattern>/dumb</url-pattern>
</servlet-mapping>
Its said that all these aliases are for security. I get that. But why do we have to map it to a servlet-name first and then to the servlet-class ? Why can't the server find the url pattern and directly map it to the servlet-class ?
The aim of this is that the servlet could be referenced by more than one mapping, so you can map one servlet to more than one url (or pattern) and not just one.
The name is sort of like and "ID" that tells the container which <servlet> part goes with which <servlet-mapping> part (as well as ties it to other parts of the XML config in container specific XML files)
You can have multiple url patterns tied to the same servlet name.
I agree it seems ugly, but it's an attempt to keep the servlet config DRY, as servlet-name can be used in filter-mappings as well as servlet-mappings.
In servlet spec 3.0 you can annotate the servlets themselves which is neater.
It was designed that way to allow other components, such as filters, can access it. Filters can either be associated with a Servlet by using the <servlet-name> style:
<filter-mapping>
<filter-name>Image Filter</filter-name>
<servlet-name>ImageServlet</servlet-name>
</filter-mapping>
The simple flow diagram of sitemesh (here) shows that they check whether its the first time the filter is being applied or not. I have seen this check in the code of other filters too. I am unable to understand a situation where the same filter can be applied twice for the same request. Please explain.
As of Servlet 2.4, filters can be applied to a request invoked via the request dispatcher also. If the filter is specified to run on includes, or forwards for example it could be executed multiple times. e.g.
<filter-mapping>
<filter-name>Logging Filter</filter-name>
<url-pattern>/products/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
So, for example, when a request is handled by a servlet and that servlet forwards the request somewhere else
httpServletRequest.getRequestDispatcher("/products/somewhereElse").forward(httpServletRequest, httpServletResponse);
, then the filter may run twice. Once for the original request and then again for the forward providing the URL path and dispatcher configuration allows.
This question already has answers here:
How to define servlet filter order of execution using annotations in WAR
(4 answers)
Closed 8 years ago.
Suppose I have following in my web.xml
<filter-mapping>
<filter-name>F1</filter-name>
<url-pattern>/XYZ/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>F2</filter-name>
<url-pattern>/XYZ/abc.do</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>F3</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
What will be the order in which the filters will be called if a request comes as /XYZ/abc.do and why?
In the order their mappings are defined in web.xml
If using annotations (#WebFilter) the order seems to be undefined - you still have to declare the <filter-mapping> entries in web.xml.
Section 6.2.4 of the Servlet specification 3.0:
When processing a <filter-mapping> element using the <url-pattern> style, the container must determine whether the <url-pattern> matches the request URI using the path mapping rules defined in Chapter 12, “Mapping Requests to Servlets”.
The order the container uses in building the chain of filters to be applied for a particular request URI is as follows:
First, the <url-pattern> matching filter mappings in the same order that these elements appear in the deployment descriptor.
Next, the <servlet-name> matching filter mappings in the same order that these elements appear in the deployment descriptor.
If a filter mapping contains both <servlet-name> and <url-pattern>, the container must expand the filter mapping into multiple filter mappings (one for each <servlet-name> and <url-pattern>), preserving the order of the <servlet-name> and <url-pattern> elements.
In short: they're applied in the order in which they appear in the XML file. It gets interesting if you hit an URL that's covered by both <url-pattern> and <servlet-name> bound filters, because then all URL-pattern bound filters are applied before all servlet-name bound filters. I've never been in this situation (haven't seen any servlet-name bound filters at all), but I reckon it could be quite confusing.