I'm working on a web application using Java code, I had changed my code by making each page start from a servlet class.
Java code in servlet "indexServlet":
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DataGathering dBConnector = new DataGathering();
List<Long> lstDetailVewOID;
lstDetailVewOID = dBConnector.getDetailVewOID();
request.setAttribute("detailVewLst", lstDetailVewOID);
// pass the list to jsp page.
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
Since then the CSS code stopped working, and it gives me this error :
Resource interpreted as Stylesheet but transferred with MIME type
text/html: "http://localhost:8080/firstApplication/Style-Sheet/Template-Style.css".
When tracing the code, I found that by running the doGet() method inside the servlet class, it's call the page and run it, then get back to the servlet again to close the method, I guess the error because of this procedure but am not sure and I can't solve it.
When searching through the internet i figured that the type should be text/css but i already did that, and the same CSS file was working find before changing the code.
calling the CSS file inside the jsp page:
<link href="Style-Sheet/Template-Style.css" rel="stylesheet" type="text/css">
Edit:
web.xml mapping:
<servlet>
<servlet-name>Index</servlet-name>
<servlet-class>com.Teklabz.Servlets.IndexServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Index</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
I'm think you return static resources like css and images through your servlet. This is bad itself, but if you do, you need set right mime type in response headers. Actually i'm think you should change servlet-to-url mapping from /* to somewhat like /*.jsp, so, all other static resources will be handled by your tomcat/jetty, they do it right.
<web-app>
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/*.jsp</url-pattern> <!-- right here! -->
</servlet-mapping>
</web-app>
Related
I am new in Servlets and web.xml content. I would like to set a condition/dependency on two different servlets.
Consider I have below two servlets:
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>com.my.app.Servlet1</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>servlet2</servlet-name>
<servlet-class>com.my.app.Servlet2</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
And I would like to invoke servlet2 only in case servlet1 encounters an error or fails. As to be a scenario: Assume servlet1 is my main authenticator and the user login failed due to missing parameter in URL in servlet1. In that case I would like to try the second authenticator servlet2 that contains different set of checks...
Can I achieve this by modifying web.xml only?
If not, what would be an alternative solution to accomplish this need?
Note: I do have the source code of servlet1 but not the servlet2 (only built jar)...
Thanks in advance.
You could do this using reuqestDispatcher and forward the request to the other servlet2 like following in Servlet 1s doPost method.
//Here URL is path to servlet 2
RequestDispatcher rd = request.getRequestDispatcher(“url”);
rd.forward(request,response);
I am working on a Dynamic Web Application with simple Java, Eclipse, and Tomcat 7.
Until I made the below changes, everything worked perfectly.
I recently added a home page Servlet Home.java and home page jsp Home.jsp and mapped the servlet to the URL / in the web.xml like
<servlet>
<display-name>Home</display-name>
<servlet-name>Home</servlet-name>
<servlet-class>my_proj.servlets.Home</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Home</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
The Servlet Home.java looks like:
public class Home extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Servlet \"Home\" doGet working");
System.out.println("PathInfo: " + request.getRequestURL());
//If logged in, go to home page
request.getRequestDispatcher("/resources/jsp/home.jsp").forward(request, response);
//If not, go to login/register page
// TODO
}
}
And the Home.jsp is quite long, but everything is working except the resources like CSS, images, etc. They are not being loaded by the page. I am referencing them with
<link href="/my_proj/resources/css/custom.css" rel="stylesheet">
The Cause
Because of the code I put in the doGet method above, I can see that the requests to find the CSS page are actually ending up at the Home servlet. For instance this is part of what I see in the console
Servlet "Home" doGet working
PathInfo: http://localhost:8080/my_proj/resources/css/custom.css
So my question is, how to I properly map my pages so as to not to cause this confusion? Or how do I separate my CSS from relying on this mapping system? I don't want web.xml to handle the mapping to these files.
Please give your directory structure, for example If your directory structure like :
Project Name\WebContent\css then just add following line to include css on your page :
<link href="css/fileName.css" rel="stylesheet">
That's it, No need to provide full path : like Project Name\WebContent\css\fileName.css
<link href="/css/fileName.css" rel="stylesheet">
I have a simple servlet which renders different content based on different geo locations
for example:
example.com/us
example.com/de
example.com/uk
example.com/..
so actually the servlet should supports all geo locations as url-pattern. So thats why I defined the rule below in my web.xml file:
<servlet-mapping>
servlet-name>MyServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
this is how the servlet look like:
public class MyServlet extends HttpServlet{
String showPage = "/pages/show.jsp";
public void doGet(HttpServletRequest request, HttpServletResponse response){
System.out.println("servlet initiated... ~> "+request.getRequestURI());
...
request.getRequestDispatcher(showPage).forward(request, response);
}
}
As soon as I try to forward the page, the servlet starts again and again; it tries to also handle the request /page/show.jsp.
So I get such an ouput when I try to access example.com/us:
servlet initiated... ~> /us
servlet initiated... ~> /page/show.jsp
Exception...
servlet initiated... ~> /page/show.jsp
Exception...
servlet initiated... ~> /page/show.jsp
...
It throws an exception because my servlet is not expecting such a url-pattern /page/show.jsp but it triggers because I have define /* url-pattern in my web.xml file.
Any idea? how can I skip or exclude the unwanted requests like the one above? Thanks.
I could not find a specific reference but I believe that "/*" root url pattern conflicts with the default mapping in the the global web.xml which could be contributing to your problem.
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- The mapping for the default servlet -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
try adding explicit jsp servlet tag and servlet mapping to avoid processing the jsp through the default mapping which is created with the "/" root url pattern. I'm not sure that this will solve your problem.
<servlet>
<servlet-name>showpage</servlet-name>
<jsp-file>/pages/show.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>showpage</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>
Another more explicit solution would be to create a url pattern that differentiates all of the country geo requests.
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/geo/*</url-pattern>
</servlet-mapping>
So example.com/geo/us etc will map explicitly
I attempted the same global setting and had a similar problem where it recursively attempted the request and threw an exception over and over until I stopped the Tomcat server. The problem was resolved when used more specific url pattern.
Bart answer gave me the clue. Actually there are many ways to handle this, one is to use Filters and the other one is to define all the static routes in web.xml and instead of the /* I have used /.
So to resolve the issue I change the url-pattern as below:
<!-- static assets -->
<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>
<!-- my servlet -->
<servlet-mapping>
servlet-name>MyServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
You also don't need to define the pattern for org.apache.catalina.servlets.DefaultServlet its already there by default.
So After above changes everything works fine.
When resolving pages/show.jsp the container will match on the longest path first then look at the file extension (.jsp) afterwards. So pages/show.jsp matches /* and therefore the container loads the Servlet again and doesn't initiate the JSP engine servlet.
Are all your jsps in a pages directory? Maybe you can add that mapping to your web.xml
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>/pages/*</url-pattern>
</servlet-mapping>
Per the servlet specification (2.5 here, but it should be the smae for newer version) :
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 match the longest path-prefix. 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.
If neither of the previous three rules result 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.
(source : servlet-spec-2.5)
So for your case, it should be sufficient to add a more precise mapping (as said by Si Kelly) :
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>/pages/show.jsp</url-pattern>
</servlet-mapping>
I am redoing the URL mapping structure within my Java web application. I am trying to find the most efficient and proper way to map the servelets and resources to their proper URLs.
There are two strategies that I have been able to create, but I am not sure which is more efficient.
Mapping All urls to one Servlet which Handles the requests
In this case I have a Servlet named "URL", with the following servlet mapping:
<servlet-mapping>
<servlet-name>url</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
The url Servlet is set up like such as an example and works fine:
String task = request.getRequestURI().substring(request.getContextPath().length());
if ("/home".equals(task)){
RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/home.jsp");
dispatcher.forward(request, response);
}
The problem I initially had with this that all the static resources such as JS, Images, etc... weren't served. I had the option to create separate directories for the static content as a solution, but off the top of my head I switched to mapping it all directly in the web.xml.
Mapping it all directly in the web.xml.
In this case the url patterns are directly mapped to the JSPs and Servlets like so:
<servlet>
<servlet-name>home</servlet-name>
<jsp-file>/jsp/Home.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
Example:
localhost:8080/home <- home.jsp
localhost:8080/about <- about.jsp
localhost:8080/login <- doLogin servlet
Are these bad? Which would be a more efficient and proper way to map the urls to their intended JSP files and Servlets?
I use a combination of both, I define all the static pages in web.xml and right at the end of the web.xml, I create a catch-all that will handle dynamic pages.
So home, about, login, etc are all static pages, define them in web.xml
Something like account/abc and blog/some-random-article is handled dynamically.
<servlet>
<servlet-name>NotFound</servlet-name>
<servlet-class>com.site.PageNotFoundServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NotFound</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
If in your servlet code, if you don't know how to handle the url, in other words the url is something like /asdfadfasdf which you don't handle, throw a 404 back, if the url starts with /blog (from /blog/random-article), go to the blog page with the random-article as the content.
The case of "home.jsp" is not same here
RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/home.jsp")
and
<servlet>
<servlet-name>home</servlet-name>
<jsp-file>/jsp/**Home.jsp**</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
Is there a way to call a Java Servlet on click of hyperlink without using JavaScript?
Make the hyperlink have a URL that you have a servlet mapping defined for in the web.xml file.
The servlet-mapping element defines a mapping between a servlet and a URL pattern. The example below maps the servlet named myservlet to any URL that starts with /foo:
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>com.stackoverflow.examples.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/foo/*</url-pattern>
</servlet-mapping>
For this example, a hyperlink such as Click Me would invoke the servlet.
you declare your servlet in web.xml by setting its name, class and url-pattern
(let's say your url-pattern is /myServlet)
write mylink
override the doGet(..) method of the servlet to do whatever you want
Think that you've defined a servlet "callme" and web.xml has been configured for this servlet. Use the following syntax to call it using hyperlink
web.xml
<servlet>
<description>callme Functions</description>
<display-name>callme</display-name>
<servlet-name>callme</servlet-name> <servlet-class>com.test.Projects.callme</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>callme</servlet-name>
<url-pattern>/callme</url-pattern>
</servlet-mapping>
in JSP:
Call the servlet
What exactly do you mean with "call a Java Servlet? The most normal (i.e. without any JavaScript magic) browser behaviour for clicking on a link is to send a HTTP request to fetch the document at the URL specified in the link and display it - and Servlets exist to respond to HTTP requests.
So you don't have to do anything special at all. Just have a regular HTML link and make sure that the servlet you want to "call" corresponds to that link's URL. Of course the next question is what that Servlet returns and what you want the browser to do with it.