I have a Servlet that is mapped to the root directory "/":
<servlet>
<servlet-name>Main</servlet-name>
<servlet-class>com.motorola.triage.MainServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Main</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
In this servet there is a couple of small things that are done there, like authentication and retrieve of Google Plus information. After that, I'm doing a forward to a JSP file called "index.jsp"
req.getRequestDispatcher("index.jsp").forward(req,resp);
When I'm accessing "localhost:8080/" the static file "index.jsp" is loaded without passing through the servlet. For architecture reasons I can not change the name of index.jsp. I would like to ask if is there any way to change this behavior of the server and make it look to the servlet before look the index.jsp file.
This is occurring specifically because you used the name index.jsp.
This has been covered elsewhere, such as here and here and here.
I like to expose one JAVA method as a Web service that will accept POST ,strip the parameters out of it and reply accordingly. I read I have to use doPost(req,resp) , but How can I get to the servlet code? what should be in web.xml? there will not be a welcome-file ? After mapping the servlet, can I read it without the need for a index.html as start point?
create the doPost(req,resp) method in your servlet and map it to a url in web.xml
<servlet>
<servlet-name>HelloPost</servlet-name>
<servlet-class>packageName.HelloPost</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloPost</servlet-name>
<url-pattern>/post-url</url-pattern>
</servlet-mapping>
then you can post your request to /post-url .You don't need to use index.html.Any url can be put in welcome file to load for the url /
To set /post-url as landing page , use
<welcome-file-list>
<welcome-file>/post-url</welcome-file>
</welcome-file-list>
you can get started here https://developers.google.com/appengine/docs/java/gettingstarted/creating
If you want to know how to set the web.xml to start the servlet then may be this will help you.
Can I make the welcome-file of the website to be a servlet ? If yes , how ? I was trying something like :
<welcome-file-list>
<welcome-file>FilterForwarded</welcome-file>
</welcome-file-list>
<!-- FilterForwarded is a servlet -->
While deploying I do not see any error but when I try to open the website abc.com I get a message from the browser that it is unable to connect to this website.Why is it so ?
I want when anyone visits the website,I should be able to store the client's public IP. To do this I wrote a Filter which after taking the IP , passed it to the servlet (from there I could update the logs). After storing the IP , client be automatically redirected to index.jsp. Is there any way to achieve this ?
EDIT :
<servlet-mapping>
<servlet-name>FilterForwarded</servlet-name>
<url-pattern>/FilterForwarded</url-pattern>
</servlet-mapping>
This is the mapping defined in web.xml . When I use /FilterForwarded in welcome-file I get this message when I try to deploy : Bad configuration: Welcome files must be relative paths: /FilterForwarded
From the logs :
com.google.apphosting.utils.config.AppEngineConfigException: Welcome files must be relative paths: /FilterForwarded
at com.google.apphosting.utils.config.WebXml.validate(WebXml.java:125)
at com.google.appengine.tools.admin.Application.<init>(Application.java:150)
at com.google.appengine.tools.admin.Application.readApplication(Application.java:225)
at com.google.appengine.tools.admin.AppCfg.<init>(AppCfg.java:145)
at com.google.appengine.tools.admin.AppCfg.<init>(AppCfg.java:69)
at com.google.appengine.tools.admin.AppCfg.main(AppCfg.java:65)
If you map the filter to /* you should be able to intercept all requests and then log the IP from there.
Or is your requirement to only log Client IP for the landing page?
If so, you could change the default servlet for the Servlet container, but bear in mind this will change the default servlet for all requests that do not match mappings in your web.xml.
<servlet-mapping>
<servlet-name>FilterForwarded</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
A more complex, but potentially better solution, is to front your Java web container with a web server and use rewrite rules to proxy to your backend Servlets. This way will mean that you can control the Servlet that is accessed for your landing page without overriding the default servlet for all non-matching requests. This might be overkill for your problem though.
I've mapped the Spring MVC dispatcher as a global front controller servlet on /*.
<servlet>
<servlet-name>home</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
However, this mapping stops the access to static files like CSS, JS, images etc which are all in the /res/ folder.
How can I access them anyway?
Map the controller servlet on a more specific url-pattern like /pages/*, put the static content in a specific folder like /static and create a Filter listening on /* which transparently continues the chain for any static content and dispatches requests to the controller servlet for other content.
In a nutshell:
<filter>
<filter-name>filter</filter-name>
<filter-class>com.example.Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>com.example.Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>/pages/*</url-pattern>
</servlet-mapping>
with the following in filter's doFilter():
HttpServletRequest req = (HttpServletRequest) request;
String path = req.getRequestURI().substring(req.getContextPath().length());
if (path.startsWith("/static")) {
chain.doFilter(request, response); // Goes to default servlet.
} else {
request.getRequestDispatcher("/pages" + path).forward(request, response);
}
No, this does not end up with /pages in browser address bar. It's fully transparent. You can if necessary make "/static" and/or "/pages" an init-param of the filter.
With Spring 3.0.4.RELEASE and higher you can use
<mvc:resources mapping="/resources/**" location="/public-resources/"/>
As seen in Spring Reference.
What you do is add a welcome file in your web.xml
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
And then add this to your servlet mappings so that when someone goes to the root of your application, they get sent to index.html internally and then the mapping will internally send them to the servlet you map it to
<servlet-mapping>
<servlet-name>MainActions</servlet-name>
<url-pattern>/main</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>MainActions</servlet-name>
<url-pattern>/index.html</url-pattern>
</servlet-mapping>
End result: You visit /Application, but you are presented with /Application/MainActions servlet without disrupting any other root requests.
Get it? So your app still sits at a sub url, but automatically gets presented when the user goes to the root of your site. This allows you to have the /images/bob.img still go to the regular place, but '/' is your app.
If you use Tomcat, you can map resources to the default servlet:
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/static/*</url-pattern>
</servlet-mapping>
and access your resources with url http://{context path}/static/res/...
Also works with Jetty, not sure about other servlet containers.
Serving static content with appropriate suffix in multiple servlet-mapping definitions solved the security issue which is mentioned in one of the comments in one of the answers posted. Quoted below:
This was a security hole in Tomcat (WEB-INF and META-INF contents are accessible this way) and it has been fixed in 7.0.4 (and will be ported to 5.x and 6.x as well). – BalusC Nov 2 '10 at 22:44
which helped me a lot.
And here is how I solved it:
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
I've run into this also and never found a great solution. I ended up mapping my servlet one level higher in the URL hierarchy:
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
And now everything at the base context (and in your /res directory) can be served up by your container.
As of 3.0.4 you should be able to use mvc:resources in combination with mvc:default-servlet-handler as described in the spring documentation to achieve this.
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-static-resources
The reason for the collision seems to be because, by default, the context root, "/", is to be handled by org.apache.catalina.servlets.DefaultServlet. This servlet is intended to handle requests for static resources.
If you decide to bump it out of the way with your own servlet, with the intent of handling dynamic requests, that top-level servlet must also carry out any tasks accomplished by catalina's original "DefaultServlet" handler.
If you read through the tomcat docs, they make mention that True Apache (httpd) is better than Apache Tomcat for handling static content, since it is purpose built to do just that. My guess is because Tomcat by default uses org.apache.catalina.servlets.DefaultServlet to handle static requests. Since it's all wrapped up in a JVM, and Tomcat is intended to as a Servlet/JSP container, they probably didn't write that class as a super-optimized static content handler. It's there. It gets the job done. Good enough.
But that's the thing that handles static content and it lives at "/". So if you put anything else there, and that thing doesn't handle static requests, WHOOPS, there goes your static resources.
I've been searching high and low for the same answer and the answer I'm getting everywhere is "if you don't want it to do that, don't do that".
So long story short, your configuration is displacing the default static resource handler with something that isn't a static resource handler at all. You'll need to try a different configuration to get the results you're looking for (as will I).
'Static' files in App Engine aren't directly accessible by your app. You either need to upload them twice, or serve the static files yourself, rather than using a static handler.
The best way to handle this is using some kind of URL re-writing. In this way, you can have clean restful URLs, and NOT with any extensions i.e abc.com/welcom/register as opposed to abc.com/welcome/resister.html
I use Tuckey URL which is pretty cool.
It's got instructions on how to set up your web app.I have set it up with my Spring MVC web app. Of course, everything was fine until I wanted to use annotations for Spring 3 validations like #Email or #Null for domain objects.
When I add the Spring mvc directives:
< mvc:annotation-driven />
< mvc:default-servlet-handler />
.. it breaks the good ol Tuckey code. Apparently, < mvc:default-servlet-handler /> replaces Tuckey, which I'm still trying to solve.
I'd recommend trying to use a Filter instead of a default servlet whenever possible.
Other two possibilities:
Write a FileServlet yourself. You'll find plenty examples, it should just open the file by URL and write its contents into output stream. Then, use it to serve static file request.
Instantiate a FileServlet class used by Google App Engine and call service(request, response) on that FileServlet when you need to serve the static file at a given URL.
You can map /res/* to YourFileServlet or whatever to exclude it from DispatcherServlets' handling, or call it directly from DispatcherServlet.
And, I have to ask, what does Spring documentation say about this collision? I've never used it.
Add the folders which you don't want to trigger servlet processing to the <static-files> section of your appengine-web.xml file.
I just did this and looks like things are starting to work ok. Here's my structure:
/
/pages/<.jsp files>
/css
I added "/pages/**" and "/css/**" to the <static-files> section and I can now forward to a .jsp file from inside a servlet doGet without causing an infinite loop.
After trying the filter approach without success (it did for some reason not enter the doFilter() function) I changed my setup a bit and found a very simple solution for the root serving problem:
Instead of serving " / * "
in my main Servlet, I now only listen to dedicated language prefixes
"EN", "EN/ *", "DE", "DE/ *"
Static content gets served by the default Servlet and the empty root requests go to the index.jsp which calls up my main Servlet with the default language:
< jsp:include page="/EN/" />
(no other content on the index page.)
I found that using
<mvc:default-servlet-handler />
in the spring MVC servlet bean definition file works for me. It passes any request that isn't handled by a registered MVC controller on to the container's original default handler, which should serve it as static content. Just make sure you have no controller registered that handles everything, and it should work just fine. Not sure why #logixplayer suggests URL rewriting; you can achieve the effect he's looking for just adequately using Spring MVC alone.
I found a simpler solution with a dummy index file.
Create a Servlet (or use the one you wanted to respond to "/") which maps to "/index.html"
(Solutions mentioned here use the mapping via XML, I used the 3.0 version with annotation #WebServlet)
Then create a static (empty) file at the root of the static content named "index.html"
I was using Jetty, and what happened was that the server recognized the file instead of listing the directory but when asked for the resource, my Servlet took control instead. All other static content remained unaffected.
In Embedded Jetty I managed to achieve something similar by adding a mapping for the "css" directory in web.xml. Explicitly telling it to use DefaultServlet:
<servlet>
<servlet-name>DefaultServlet</servlet-name>
<servlet-class>org.eclipse.jetty.servlet.DefaultServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DefaultServlet</servlet-name>
<url-pattern>/css/*</url-pattern>
</servlet-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:default-servlet-handler/>
</beans>
and if you want to use annotation based configuration use below code
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
With regard to Tomcat, a lot depends on the particular version. There was a bug fix
https://bz.apache.org/bugzilla/show_bug.cgi?id=50026
which means the servlet-mapping (other than for '/') for the default servlet behaves differently in Tomcat 6.0.29 (and earlier) compared with later versions.
In section "12.2 Specification of Mappings" of the Servlet Specification, it says:
A string containing only the ’/’ character indicates the "default" servlet of the
application.
So in theory, you could make your Servlet mapped to /* do:
getServletContext().getNamedDispatcher("/").forward(req,res);
... if you didn't want to handle it yourself.
However, in practice, it doesn't work.
In both Tomcat and Jetty, the call to getServletContext().getNamedDispatcher('/') returns null if there is a servlet mapped to '/*'
I have a JavaEE 1.4 web application running on WebSphere Application Server 6.0. In web.xml, there is a servlet configured to intercept all server requests:
<servlet-mapping>
<servlet-name>name</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
This works fine until I try to request something ending with *.jsp. In this case, server tries to find JSP with this name and fails with the error:
java.io.FileNotFoundException: JSPG0036E: Failed to find resource /cfvct/search_criteria.jsp
at com.ibm.ws.jsp.webcontainerext.JSPExtensionProcessor.findWrapper(JSPExtensionProcessor.java:279)
at com.ibm.ws.jsp.webcontainerext.JSPExtensionProcessor.handleRequest(JSPExtensionProcessor.java:261)
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3226)
at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:253)
at com.ibm.ws.webcontainer.VirtualHost.handleRequest(VirtualHost.java:229)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:1970)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:120)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:434)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:373)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:253)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminaters(NewConnectionInitialReadCallback.java:207)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:109)
at com.ibm.ws.tcp.channel.impl.WorkQueueManager.requestComplete(WorkQueueManager.java:566)
at com.ibm.ws.tcp.channel.impl.WorkQueueManager.attemptIO(WorkQueueManager.java:619)
at com.ibm.ws.tcp.channel.impl.WorkQueueManager.workerRun(WorkQueueManager.java:952)
at com.ibm.ws.tcp.channel.impl.WorkQueueManager$Worker.run(WorkQueueManager.java:1039)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1475)
I need to have this request processed by the servlet, but seems server uses some JSPExtensionProcessor to process all paths ending with .jsp. Is there any way to change this behaviour?
Yes, you'll need to map your servlet to *.jsp in order to get *.jsp support redirected to your servlet.
<servlet-mapping>
<servlet-name>name</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
It is normally a bad idea to have jsps accessible directly, however. Placing them in WEB-INF in some directory, then mapping an appropriate url (.do, .action, etc) to a servlet that then redirects internally to that JSP is the better practice.
So instead of typing thisUrl.jsp, the user would type thisUrl.do or thisUrl.action, and it would then get hit by the servlet to redirect to thisUrl.jsp.