Friendly URLs with Tomcat - java

I want to be able to have URLs going to servlets like http://host/Servlet/1 rather than http://host/Servlet?ID=1
Any suggestions for how this can be accomplished? Preferably with multiple levels too, so I could do something like http://host/Servlet/1/Files
Thanks

The HttpServletRequest exposes a method, getPathInfo(), which gives you information about the request URL after the servlet path itself. You could map your servlet to /Servlet/* and then get the ID with getPathInfo().

If you don't have a "must do using Tomcat alone" requirement, I suggest you set up an Apache layer in front of Tomcat where you can have such and other complex URL Rewrites set up.

One way to solve this could be to have your controller-servlet in front to dispatch to correct servlet in behind depending on the request URI from getRequestURI on the HttpServletRequest.

You can do this using Filter. Dispatch incoming URL by some rules and redirect to dispatched URL.

Related

how Filters handle Session

some of you advise me to handle sessions using filters. I studied a little about the filter following some guides found on the internet, and wrote a filter referring this guide.
I saw that the filter is called for every component of my page (css, images etc); is there a way to call it just when a jsp or a servlet is load? I need a method that can understand if jsp or a servlet is load, in order to make some stuff inside my filter.
Yes, you can do that. Just change the url-pattern for your session filter.
If you are using some web framework (spring mvc,...) with one dispatching servlet, you can map your filter only to this servlet using servlet-name and requests to other resources (js, css) will not be intercepted by this filter.
First off, please don't be misled by the purpose of the tutorial in the link you have specified. Session handling is always done through cookies, URL-rewriting (or for the more advanced, SSL). He's merely using filters to enhance application security, by ensuring the user is redirected to the login page, whenever he goes directly to an "avoid-url".
Think about a filter, a physical filter. Whether it be an excel filter or a physical gravel filter. It stands between one thing and another thing:
Java web filters can do the same thing:
Just like you can choose which water bottle to filter, you can decide which requests you want to filter. You do that using the filter-mapping element in web.xml. You can specify individual servlet names, or a url pattern.

Set Request Header and Forward to another application

I am writing a Java based Web application, which, in the actual production environment would be front-ended by another application which would set certain HTTP request headers before the request hits my application.
However, in the development environment I do not have the front-ending application, for which I need to create a mock web application that simulates the same behavior. i.e. this mock application should set the request headers and redirect or forward or whatever that I do not know :) to a certain page in my application.
How can I accomplish this?
The following articles may help you:
Adding Header Information to an existing HTTP Request
How to modify request headers in a J2EE web
application.
P.S.
I am sorry I provided only links, that was one of my early answer on SO ))
In case you don't want to modify your code as suggested by #user1979427 you can use a proxy server to modify headers or add headers on the fly.
For example in Apache HTTPD you would add something like below and proxy the
Header add HEADER "HEADERVALUE"
RequestHeader set HEADER "HEADERVALUE"
Refer to HTTPD doc
You should create a AddReqHeaderForFrowardWrapper request wrapper passing the headername and header values. And, override the request header related methods to return your custom header.
You can use Tracer to implement this.
There are frameworks available to support this implementation.
Spring has Sleuth, Zipkin, OpenTracing available.
I find OpenTracing to be easy to use without worrying about dependency conflicts.
Read more about it here: https://opentracing.io/guides/java/
Instead of writing a mock application, I used a browser add-on that allowed me to add custom headers!
For setting header in java, you can use:
request.setHeader(attributeName, attributeValue);
And for redirecting to another page, you can use:
request.sendRedirect(URL);

applet->servlet->a record file(on the server) : how do i do this?

To make a poll form using an applet, i wanted to know how can my applet communicate with a servlet . That servlet is meant to write the result to the text file on the server. I have no idea how can i do this.
You could use java.net.URLConnection for this.
Assuming that your servlet is mapped on an URL pattern of /myservlet and your applet is been served from the context root, then this should do:
InputStream servletResponse = new URL(getCodeBase(), "myservlet").openStream();
// ...
That's all. The getCodeBase() is inherited from Applet class and dynamically returns the applet's code base URL (from where the applet was been downloaded). The servletResponse will contain whatever you wrote to response.getOutputStream() or response.getWriter() in the servlet. For example just an "ok" string or an easily parseable format like XML or JSON. You could pass request parameters as a query string in the GET request URL, or in the POST request body.
See also:
Using java.net.URLConnection to fire and handle HTTP requests
https://stackoverflow.com/questions/9361399/how-to-send-list-of-objects-from-servlet-to-applet
The applet and the servlet is separate. There is no easy way you can use magic to make this easier.
A servlet is a snippet inside a web server which gets executed when a HTTP request is being made to the correct URL on the web server. Hence you need to make a HTTP request to the correct URL on the web server where your servlet is running.
This is done in the same way you do any other HTTP request from an applet, which is done in the same way that you do a HTTP request from a self-standing application.
Well you have several options for the applet/servlet communication....
http requests. (This may be the easiest). For this you can use Apache HTTP Components
Remote Method Invocation RMI. This may be more complicated than http requests but it depends on what you want to achieve.
Sockets. (I think http requests is flexible enough for your use case but just in case)
javascript. You can call a javascript function from your applet and let the javascript function submit the information to the servlet through ajax, websockets, etc.
Of course there are many other options but these are some ideas and remember that you may need to sign your applet.
If your question is about how to write to a file there are many tutorials. Here is a good one

Calling servlet from servlet

I would like to call a servlet from another servlet doing two things:
setting the content type to "multipart/form-data"
setting the method to "POST".
This is very easy to do from a form, but I need to do it from another servlet. Any ideas how?
You can use java.net.HttpUrlConnection or maybe Apache HTTP client to send a POST/GET request to the other servlet. You will basically be invoking the other servlet the same way a browser would.
It sounds like request forwarding or include is what you're looking for. What you actually do will depend on what you intend to do with the output of the target servlet. Are you going to display it somehow? Or are you simply discarding it? You may in some cases, need to be a bit more "creative" in how you invoke those methods (e.g., either creating your own request/response instances, or wrapping the current request/response so that state changes are isolated).
Alternatively, to keep things simple you may want to just open a network connection to your target servlet's mapped URL as Jeff suggested.
It sounds like you want to send an HTTP POST with java. I would recommend using apache HttpClient. Check out this question Add parameters to Apache HttpPost
You can also do this with pure java with (HttpUrlConnection)[ http://download.oracle.com/javase/6/docs/api/java/net/HttpURLConnection.html].

Calling Servlet Post from another Servlet

I need to call a servlets POST method from another servlet and pass a blob in the servlets parameters. Is this posible, if so how can it be done. PS: I cant use Apache HttpClient
You need to create and send a HTTP request yourself. You cannot make use of forward/redirect/include because you want to change the method from GET to POST and you want to send a multipart/form-data request.
As HttpClient (and other 3rd party library?) is apparently not an option, your best bet is to use the standard Java SE API provided java.net.URLConnection. Long story short: Using java.net.URLConnection to fire and handle HTTP requests At the bottom you can find a multipart/form-data example.
Please note that this problem is not specific to servlets. In other words, you must be able to execute this code in a plain vanilla Java application with a main() method. This allows for easier testing and finetuning. Once you get it to work, just let the servlet execute the same piece of code.
Unrelated to the problem, I have the impression that there's a major design failure somewhere, certainly if the both servlets runs in the same webapplication context. The other servlet where you want to send the POST request to is apparently too tight coupled and should be refactored.
You can get a dispatcher to another servlet in your application and forward it or include it as #Ryan suggests. The code should be something like this inside your first servlet:
ServletContext context = this.getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher("/otherurltoservlet");
// change your request and response accordingly
dispatcher.forward(request, response);
Do you mean call from your application to another web service? If so, then something like HttpClient is what you want. If you mean you want to programmatically invoke another servlet in your app, then you're looking to either forward to it or include it.

Categories

Resources