When trying to set Context attributes like so:
void init()
{
String testing = new String();
testing = "This is a test";
getServletContext().setAttribute("test", testing);
}
In one servlet, and getting the attribute like so:
String testing = (String) getServletContext().getAttribute("test")
In a second servlet, testing is null.
Does this mean my servlets are in separate contexts? If so, how could I access the context attributes of the first servlet? Please provide a reference for this as I am relatively new to java/servlets.
I am using Netbeans with Glassfish 3.
EDIT: They are both in the same webapp and are both defined in the same WEB-INF/web.xml
If both servlets are in the same webapp, by default the order of initialization is undefined. So it may be, your "second" servlet is initialized before the "first" (according to the order in the web.xml). You may fix it by adding a load-on-startup tag to the servlet tag:
<servlet>
<servlet-name>first<servlet-name>
...
<load-on-startup>1<load-on-startup>
</servlet>
<servlet>
<servlet-name>second<servlet-name>
...
<load-on-startup>2<load-on-startup>
</servlet>
I believe the two servlets need to be in the web application, i.e. packaged in the same war file, for this to work.
Context == WAR == webapps
Both servlet has to live under the same webapp to share context. Check if both servlet classes are under same WEB-INF/classes.
Related
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.
Imagine a war-file which you can't change. The .war-file's web.xml defines servlets with a set of init-param elements (not: servlet context parameters).
Using Tomcat 7, is there a way to override some of these parameters?
(beside changing the extracted web.xml from the war-file)
It's called init-parameter for a reason. So, you can't.
But you can change values at runtime, that's no problem.
After reading the init parameters put them as attributes of the ServletContext (ctx.setAttribute("name", value))
Create a small (password-protected) page that lists all attributes of the ServletContext and gives the ability to change them.
I am trying to implement a servlet that gets raw requests, and decide either to process them, or forward them to another backend server. It is similar to a load-balancer, where a received request is forwarded to one of the (in my case 2) destinations. One of the destination is remote (on another host). Furthermore, the requests could come to the root (http://mycompany.com/).
Since I want to get raw requests, I implemented my own servlet (subclassing HttpServlet), and that works great. My servlet looks like:
public class MyProxyServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
processOrForward(req, resp);
}
// also doGet(), doHead(), ...
}
Since the service I want to process may send requests to the root, I would like to map my servlet to be the default servlet, thereby receiving any request that does not have an explicit servlet mapping. Assume my servlet's name is "myservlet", and is running along side of another servlet "foo", I expect all requests in the form of http://mycompany.com/foo/... to be delivered to foo, and everything else (e.g., /, /bar/..., /myservlet/...) to "myservlet". Looking at earlier posts (eg., root mapping here and here, or url rewriting here), I thought I figured it out, but it does not work.
Here is my web.xml:
<web-app>
<servlet>
<servlet-name>ProxyServlet</servlet-name>
<servlet-class>com.mycompany.MyProxyServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ProxyServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
In the above web.xml, for url-pattern I tried
"/" and "/*" and empty (i.e., <url-pattern></url-pattern>), all behave the same -->
Requests to root (/)goes to tomcat's default servlet
Requests to /myservlet/... are handled by "myservlet"
Requests to /fubar/... are always 404
Is there a way of turning my servlet to be the default. I.e., any request that does not map specifically to a servlet comes to mine (it is even acceptable to receive all requests, since I can deploy this servlet in its own container). In case it matters, I am using Tomcat 7.0.30 on Ubuntu 12.10.
This should be useful to you.
From the Java™ Servlet Specification Version 3.1 (JSR 340)
Chapter 12. Mapping Requests to Servlets
12.2 Specification of Mappings
In the Web application deployment descriptor, the following syntax is used to define mappings:
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.
The empty string ("") is a special URL pattern that exactly maps to the
application's context root, i.e., requests of the form http://host:port/<contextroot>/.
In this case the path info is / and the servlet path and context path is
empty string ("").
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.
As an addition, read this nice explanation with short examples from the book Head First Servlets & JSP: Passing the Sun Certified Web Component Developer Exam (2nd edition) (quote):
The THREE types of <url-pattern> elements
1) EXACT match
Example:
<url-pattern>/Beer/SelectBeer.do</url-pattern>
MUST begin with a slash (/).
Can have an extension (like .do), but it’s not required.
2) DIRECTORY match
Example:
<url-pattern>/Beer/*</url-pattern>
MUST begin with a slash (/).
Always ends with a slash/asterisk (/*).
3) EXTENSION match
Example:
<url-pattern>*.do</url-pattern>
MUST begin with an asterisk (*) (NEVER with a slash).
After the asterisk, it MUST have a dot extension (.do, .jsp, etc.).
IMPORTANT NOTE:
The URL patterns represent logical / virtual structure, i.e. the patterns (paths) specified does not need to exist physically.
UPDATE
If you want, as you say in your comment,
I want host:port to hit my servlet, not the default tomcat servlet
then see the solution here:
How do I make my web application be the Tomcat default application
In other words, what you want is a path without application context, which implies the application context of the Tomcat default application.
Quote from the above link:
In a standard Tomcat installation, you will notice that under the same
directory (CATALINA_BASE)/webapps/, there is a directory called ROOT
(the capitals are important, even under Windows). That is the
residence of the current Tomcat default application, the one that is
called right now when a user calls up
http://myhost.company.com[:port]. The trick is to put your
application in its place.
I am not sure did I understood what you want but probably intercept 404 is what you want to do, then redirect where you want.
I've came here to forum because I have strange problem with tomcat 7, mine is doing just what you want ;)
This is only one way how I can have root, EMPTY
<servlet-mapping>
<servlet-name>Default</servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>
That way : anything is redirected to this servlet, including images, etc, for example, I open another page, this show this one, root, then I can see in log 4 more request to same page, 3 for css and one for image.
<servlet-mapping>
<servlet-name>Default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
How would I go about passing a reference to the initialization of a servlet?
So, let's say I have something like this in my web.xml:
<servlet>
<servlet-name>RestTestServlet V3.1</servlet-name>
<servlet-class>com.xxx.servlet.RestTestServlet</servlet-class>
<init-param>
<param-name>serviceConsumerKey</param-name>
<param-value>com.xxx.oauth.ConsumerKey</param-value>
</init-param>
</servlet>
When I try to get the parameter, of course I just get the literal string value ("com.xxx... etc).
The com.xxx.oauth.ConsumerKey is a string bean I pull from JNDI, but I'm not sure how to get the servlet to be aware of it. I'm using Spring.
Is there a way to do this via the web.xml? If not, how would you go about doing what I'm trying to do?
The normal Spring approach would be to not write your own servlets, but rather use the Spring WebApplicationCOntext together with a DispatcherServlet. I.e., your servlet would be replaced by a spring bean, configured to handle certain requests and injected with the JNDI object.
When using Restlets, how can I read configuration parameters passed in through web.xml? With servlets, context-param can be used. How do I read context parameters from within a Restlet?
From the mailing list:
the init parameters are available in the application's context:
getApplication().getContext().getParameters().
In web.xml:
<context-param>
<param-name>my.context.param</param-name>
<param-value>Hello World</param-value>
</context-param>
In a Restlet's represent method, use:
// => "Hello World"
String result =
getApplication().getContext().getParameters().getFirstValue("my.context.param");
ServerServlet adds all the init parameters from both the servletConfig and from the servletContext to the application context.
So depending on your need, you could either examine the source code for ServerServlet, and read the configuration parameters in the same way, or simply obtain the values from your restlet, or your restlet's application's context.