Simple servlet with annotations in java (image folder) - java

i have a folder with images on webContent/images.
I Just wanna to know how to provide this folder on the web.
In my project i have just one servlet with annotations:
#WebServlet(urlPatterns = { "/" })
public class IndexCtrl extends HttpServlet {
Every time i try to get a image this servlet get priority and send a index page.
How can I provide images folder on the web?
What I'm doing wrong?

Just don't map the servlet to /. That makes it the default servlet, which catches all the requests. Map it to the URL it must handle (like /index.html for example).

Related

How to prepend front controller servlet mapping to urls in jsp

I have a simple java web application running in Tomcat.
In it, FrontController.java servlet has mapping #WebServlet("/controller/*"). So, in order to fire the servlet, I need my every url to start with /controller/. I need to be able to display images on pages images are stored outside container, so that I write them to OutputStream). But if I write my src urls like ${pageContext.request.contextPath}images/picture.jpg then the resulting url will be obviously localhost:8080/rootFolder/images/picture.jpg and not the localhost:8080/rootFolder/controller/images/picture.jpg.
To load these files I can either manually prepend controller/ after every ${pageContext.request.contextPath} which is bad or I can follow the advice found here append dispathcer servlet mapping to url and add line request.setAttribute("frontControllerMapping", "controller/"); to every method which processes request and then code urls like this ${pageContext.request.contextPath}${frontControllerMapping}images/picture.jpg which is better.
My questions are how to prepend the controller mapping to every url which must be processed by servlet and how to do it right? Is the second option the correct way to do so?
Instead of adding the complete URL for each resource you can use relative URLs. If that is not an option, than you could simply map all requests to your servlet like this:
#WebServlet("/*")
Then you don't need to worry about adding the controller path to all URLs.

How to call servlet from JSP which is in a subpackage

How to call servlet from JSP which is present inside a subpackage?
The servlet is present inside Source Packages" folder. Name of servlet is:
servlets.io.registration.servlet1.java
Now i want to call this servlet from JSP page,
<form name="admin-form" action="/*Path of servlet goes here*/">
But this is not working.
It's simple, for Servlets you can give them an address relative to your context root.
With any J2EE container with the Servlet 3.0 API (for instance Glassfish 4) you can annotate servlets with #WebServlet("path"), setting their path, for instance #WebServlet("/someservlet"). You can even use subpaths, like #WebService("path/sub/someservlet").
So assuming your J2EE application is called "Registration", running on port 8080 and you put this on top of your Servlet class: #WebServlet("/someservlet"), you can set the action to http://yourserver.com:8080/Registration/someservlet
Use WebRequest annotation on your servlet to configure whatever path you like:
#WebServlet(urlPatterns="/myservletpath")
public class MyServlet extends HttpServlet
{
...
http://docs.oracle.com/javaee/6/api/javax/servlet/annotation/WebServlet.html

How to make more specific urlPattern override broader pattern with annotations

I currently have a main controller servlet with the following annotation:
#WebServlet(name="ControllerServlet", urlPatterns={"/", "/home"})
I have .js and .css files under the /resources dir in my project that my .jsp files reference and the links are getting sent to my main controller which I don't want. I made a second servlet to handle the .js .css files with nn annotation of:
#WevServlet(name="ResourceServlet", urlPatterns={"/resources"})
hoping that it would pick up the requests coming from my .jsp files but ControllerServlet is still picking them up. How can I make /resources urls get directed to my ResourceServlet?
The url pattern / matches anything that isn't matched by the other mappings. If you have
#WebServlet(name="ResourceServlet", urlPatterns={"/resources"})
then a request to, eg. localhost:8080/context/resources will be handled by your ResourceServlet, but a request to localhost:8080/context/resources/somescript.js won't because it doesn't match ResourceServlet's url pattern. Therefore, ControllerServlet will handle it.
You need to change your ResourceServlet mapping to
#WebServlet(name="ResourceServlet", urlPatterns={"/resources/*"})

Make all requests to mysite.com/user/specified/path run the same JSP

I want to allow users to create groups in my application and access them via URL. For example, if you made a group called "sweethatclub," you could access it at http://mysite.com/sweethatclub. Of course, the same code will run for /sweethatclub and /drillteam and even /students/yearbook
I'm running in a Java servlet environment, and can't quite get the paths to align for this. I can write a filter that intercepts all requests and adds information to the request by parsing the URL, but then I want to run the code of an index.jsp. I don't want to map index.jsp to all URLs, because, for example, /images/smiley.jpg still needs to respond the with appropriate file instead of index.jsp.
Is there a way to send all requests to a servlet, unless the request is matched by a plain-old file? Or, is there some other way to accomplish what I want here?
Please let me know if I need to supply more information. I'm new to this environment.
The URL patterns in the web.xml are not supposed to be smart enough to figure out target URL's nature. If you can tolerate it, the easiest way would be to place all the user specified paths under a a well known root... someplace separate from the static files. So you end up with user specified paths like http://mysite.com/sites/sweethatclub.
Alternatively, you can move all your static content under http://mysite.com/static/, and set up the servlet mappings or filters to treat anything starting with 'static' different from the dynamic URL space.
If you are in a Unix invironment, you could just create all the "group sites" as virtual directories that just point to your default one.
Map the servlet on a specific URL pattern
<url-pattern>/groups/*</url-pattern>
Put all static content in a common folder, e.g. /static and fix all URLs in the pages to point to that URL instead.
Create a filter which is mapped on
<url-pattern>/*</url-pattern>
and does the following job in doFilter() method
String uri = ((HttpServletRequest) request).getRequestURI();
if (uri.startsWith("/static/")) {
chain.doFilter(request, response); // Goes to default servlet.
} else {
request.getRequestDispatcher("/groups" + uri).forward(request, response);
}
No, this does not end up with /groups in browser address bar URL. It's fully transparent. You can if necessary make "/static" and/or "/groups" an <init-param> of the filter so that it's externally configureable.

Accessing Tomcat Context Path from Servlet

In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying.
It would be possible to do the minify as part of the install process but I would like to do it on Servlet startup to reduce the implementation cost.
Does anyone know of a method for getting the context directory so that I can load and write files to disk?
This should give you the real path that you can use to extract / edit files.
Javadoc Link
We're doing something similar in a context listener.
public class MyServlet extends HttpServlet {
public void init(final ServletConfig config) {
final String context = config.getServletContext().getRealPath("/");
...
}
...
}
In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying
You can also access the files in the WebContent by ServletContext#getResource(). So if your JS file is for example located at WebContent/js/file.js then you can use the following in your Servlet to get a File handle of it:
File file = new File(getServletContext().getResource("/js/file.js").getFile());
or to get an InputStream:
InputStream input = getServletContext().getResourceAsStream("/js/file.js");
That said, how often do you need to minify JS files? I have never seen the need for request-based minifying, it would only unnecessarily add much overhead. You probably want to do it only once during application's startup. If so, then using a Servlet for this is a bad idea. Better use ServletContextListener and do your thing on contextInitialized().
I was googling the result and getting no where. In JSP pages that need to use Java Script to access the current contextPath it is actually quite easy.
Just put the following lines into your html head inside a script block.
// set up a global java script variable to access the context path
var contextPath = "${request.contextPath}"
Do you mean:
public class MyServlet extends HttpServlet {
public void init(final ServletConfig config) {
final String context = config.getServletContext();
...
}
...
}
Or something more complex?

Categories

Resources