Support for Dynamic path in URL with Nginx and Tomcat - java

The use case I am trying to implement.
Display different content based on the {{random_string}} in the URL path.
Users will see different content based on the {{random_string}} that the URL contains.
eg:
www.example.com/{{random_string}}/index.jsp
The URLS will look like these below. (
They include random characters before the JSP)
www.example.com/xc/index.jsp www.example.com/2b/index.jsp
www.example.com/43/index.jsp
My question
How do I setup nginx and tomcat to be able to support the {{random_string}} in the URL without throwing 404?
My Current Environment/Setup (this works fine)
Nginx along with Tomcat.
Requests that come to nginx are then redirected to tomcat to access ROOT.war
e,g - www.example.com/index.jsp

You shouldn't have to change anything in Nginx or Tomcat config. What you could do is to create a servlet that will intercept the requests and extract the {{random_string}} before forwarding to the JSP. Here are the basic steps:
1) Create a servlet with a URL pattern of /* so that all requests go to it.
2) In the servlet's doGet() method, use request.getPathInfo() to retrieve the URL path and parse it to extract the {{random_string}}.
3) Use request.setAttribute() to set attributes for the data you want to display in the JSP page.
4) Forward the request to the JSP using a RequestDispatcher, e.g.:
RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
5) In the JSP, use the request attributes that you have set in step 3 to display the content.

Related

Servlet url parameter

I’m working on Java Servlets web application. I have a html file “searchPage.html” in the WebContent folder. I have included the “searchPage.html” name in the welcome-file list of web.xml. Now whenever I run the servlet, the searchPage.html is run. The url is
http://localhost:8080/HeadersTest/ .
“HeadersTest” is the name of the web app. Now my question is, I would like to add some parameters in the url following the “HeadersTest”.The parameters shall appear after the web app is run. Do I need to add these parameters in the service methods (doGet, doPost etc.)? For example:
http://localhost:8080/HeadersTest?paramName1=paramValue1&paramName2=paramValue2.
I’m fairly new to servlet. If someone can point me in the right direction, that will be really helpful. I have attached the screenshot of my directory structure of my web application below:
Update:
As I have listed the "searchPage.html" in welcome-file list of web.xml, "searchPage.html" launches whenever I run the web application. I would like to add few parameters in the url when the web app launches.
Adding the parameters to the URL means this is a GET request.
just handle it in your servlet's doGet() method:
request.getParameter("paramName1");
When you want to show URL Parameters you could just go with
response.sendRedirect("url with parameters");
Generally, We pass parameters in url if you want to access those parameters in Servlet/Controller side.
If you want to use these parameters in your controller which is nothing but your MainServlet class then you should pass these parameters in url. You can access these using
request.getParameter("paramName1")
in your doGet() or doPost() method.

Jetty: set up redirecting to index page in java application except the specified url

I have a web application written in Java and Javascript - java part is responsible for REST API (jax-rs) and UI is written in javascript. I need to set up redirecting from any not existing URL in the domain e.g.
localhost:8080/blabla
Except the URLs which are reserved for REST(starting with "rest" in the app)
localhost:8080/rest
Is there any way to set this up in web.xml etc
Just use the standard path mapping rules to your advantage.
Example:
Setup your RestServlet on the <url-pattern>/rest</url-pattern>
Then setup a your SpecialRedirectServlet at the url pattern <url-pattern>/</url-pattern>.
If a request comes in at /rest or /rest/ then it goes to the rest servlet, all other requested paths will goto the default path mapping at /

404 with response.sendRedirect

I am using spring security login mechanism for my application and tested everything.Things were working fine.I have the following use case
If customer is not logged in , application will redirect customer to the login page.
On successful login, application will redirect customer back to same page from where they were redirected to the login page
this is the Java code used to redirect user to his original location
final SavedRequest savedRequest = this.requestCache.getRequest(request, response);
targetUrl = savedRequest.getRedirectUrl();
getRedirectStrategy().sendRedirect(request, response, targetUrl);
RedirectionStrategy being used here is DefaultRedirectStrategy, things were working fine. Application is now deployed on the Pre Production server and now this seems not working and I am getting 404 error.
When customer is being redirected to the home page,targetUrl is coming out as "/", I have a Spring controller named with this mapping
#RequestMapping("/")
public class HomePageController{ // home page code }
my application's current Pre-Prod urs is prepd-www.mysite.com so when sendredirect come in to action, webpage URL is getting changed to prepd-www.mysite.com/prepd-www.mysite.com
I am not sure what is causing this issue. is it because of the proxy server settings ?
Can any one suggest me about the possible root cause of this issue?
I have already tried it on all local machines and well on our QA but everything is working perfectly fine.
Current setup for the environment where this is happening is
We have 4 app server
We have one load balancer which is redirecting traffic to one of the app server.
Just a wild guess since you could not give the reverse proxy configuration, nor the exact URL used in pre prod and in developpement.
You say you are using DefaultRedirectStrategy from Spring security. This strategy has an option (contextRelative) that prepends the ServletContext path to the URL. If in your developpement system you were using the root context, that is if you were accessing home page at (for example) : http://localhost:8080/ the serlet context was empty.
But if now in preprod, the servlet context is no longer root but is say /myApp once translated by apache reverse proxy, when you redirect you get an URL of /myApp/myApp that could be translated back to what you gave.
You could try to control whether you have contextRelative as true in DefaultRedirectStrategy and if yes if you can set if to false and also control if you redirect to absolute or relative URLs.
If you are using apache in front check rewrite rule and redirect rules of apache config. Best way would be to ssh tunnel directly to application server(by skipping apache) and test. If it's working that means your application config is fine and it needs to be fixed in apache.
Are you using in preproduction tomcat or another application server?, normally if your war is calling foo and your commit to tomcat, the path for this war is
http://localhost:8080/foo/
So if you are using servlet you need specify in your web.xml that the main path is foo/*

In the context of Java Servlet what is the difference between URL Rewriting and Forwarding?

As a developer of Java web application, when do I need to use URL Rewriting and what is the difference between URL Rewriting and Forwarding?
I searched on other websites, I get contradictory information depending upon whom you are talking to like SEO people would answer this question differently.
AFAIK in both cases the client (browser) is not informed of the change and the end user sees exactly same URL that the client originally requested when the repose is returned from the server.
Please that this question is in the context of Java Servlet API in which forward method and sendRedirect methods are defined in which redirecting and forwarding are completely 2 different things. This question is about the difference between forward (as defined by forward method in the Servlet API's) and URL rewriting. The question clearly states that the answer should be in the context of Java servlet. Most importantly when do I need to use URL rewriting, again in the context of developing Java web application.
The term "forwarding" is ambiguous in this question. In JSP/Servlet world, "forwarding" is more known from the MVC concept that the request URL (as visible in browser address bar) effectively calls the servlet (as matched by its URL pattern in web.xml or #WebServlet) which acts as a controller to prepare the model and uses a JSP as view to present the model. That JSP in turn is been called by "forwarding". This is done by RequestDispatcher#forward():
request.getRequestDispatcher("/WEB-INF/foo.jsp").forward(request, response);
This does indeed not reflect the JSP's URL in the browser address bar. This takes place entirely server side. Basically, the servlet "loads" the JSP and passes the request/response to it so that it can do its job of generating the HTML stuff. Note that the JSP in the above example is hidden in /WEB-INF folder which makes it inaccessible for endusers trying to enter its full path in browser address bar.
In general web development world, the term "forwarding" is also known from "URL forwarding" which is essentially the same as URL redirection. This in turn indeed causes a change in the browser address bar. This is in JSP/Servlet world more formally known as "redirecting" (although most starters initially confuse it with "forwarding"). This is done by HttpServletResponse#sendRedirect():
response.sendRedirect("another-servlet-url");
Basically, the server tells the client by a HTTP 3nn response with a Location header that the client should make a new GET request on the given Location. The above is effectively the same as the following:
response.setStatus(302);
response.setHeader("Location", "another-servlet-url");
As it's the client (the webbrowser) who is been instructed to do that job, you see this URL change being reflected back in the browser address bar.
The term "URL rewriting" is also ambiguous. In JSP/Servlet world, "URL rewriting" is the form of appending the session ID to the URL so that cookieless browsers can still maintain a session with the server. You'll probably ever have seen a ;jsessionid=somehexvalue attribute in the URL. This is by default not done automatically, but most Servlet based MVC frameworks will do it automatically. This is done by HttpServletResponse#encodeURL() or encodeRedirectURL():
String encodedURL = response.encodeURL(url); // or response.encodeRedirectURL(url)
// Then use this URL in links in JSP or response.sendRedirect().
(Which in turn is -again- an ambiguous term. With "URL encoding" you'd normally think of percent encoding. There's no Servlet API provided facility for this, this is normally to be done by URLEncoder#encode() or, MVC-technically more correct, in the JSP by JSTL's <c:url> and <c:param> or any UI component provided by the servlet-based MVC framework, such as JSF's <h:outputLink>)
In general web development world (especially with Apache HTTPD / PHP folks), "URL rewriting" is more known as whatever Apache HTTPD's mod_rewrite is doing: mapping incoming URLs to the concrete resources without reflecting the URL change in the client side. In JSP/Servlet world this is also possible and it's usually done by a Filter implementation which uses RequestDispatcher#forward(). A well known implementation is the Tuckey's URLRewriteFilter.
I admit that this has also confused me for long when I just started with JSP/Servlet, for sure while having my roots in the Apache HTTPD / PHP world.
Rewriting is a layer (often before your servlet) that causes a URL to be handled like a different URL by modifying the URL before the request is served. The servlet responds through a single request as if the rewritten URL was requested, usually having never known the rewrite occured.
Forwarding (or redirection) is performed by the browser (typically automatically) when instructed by the server via some 3xx error codes (when redirection is allowed by the client). In this case two requests would be served (not necessarily both from your servlet); the first responding with an error code and a URL to redirect to, and the second serving the proper request after the client redirects.

java - Spring MVC: Redirect requests with old URLs to new URLs

I have changed URL style of one of my websites to RESTful:
**Old URLs** **New URLs**
/article/all.ab /articles
/article/read.ab?id=345 /articles/345/title-of-my-article
Until the search engines re-index my website with new URLs, people will continue to see old URLs on search engines. If they come to my site with an old URL, they will get a 404.
I want to create a mechanism (by writing a controller, error handler or whatever) that would:
catch a request whose mapping was not found
check if there is a new URL mapped for this request path.
If new URL was found, redirect to that URL.
Else show "404 Page not found" page.
How can this be done?
You could use a rewrite utility like this URL Rewrite Filter to rewrite your URLs before they are processed by your dispatcher servlet. We are using this approach a lot for user-friendly URLs in our web applications and this filter helps a lot. Its functionality is a lot like Apache's mod_rewrite.
Of course, it would require you to adjust your web application and redeploy it. But the ruleset is very easy using regex matches on URLs and would also allow to send redirects to the client (if desired).

Categories