How to implement complicated servlet mapping in web.xml descriptor - java

I faced with next task: I have an host, for example host.com and web-application on it.
Application written on Java (JSP/Servlets+Struts2).
I need to implement such HTTP-request to servlet mapping: if user enters address in browser like http://host.com/admin.action, where admin.action - existing action, defined in struts.xml, then render those struts2 action for user. If user enters something like http://host.com/abra-kadabra, (action abra-kadabra notdefined in struts.xml), then pass this request to some servlet or struts action.
Can somebody advice how to do such thing?
Thank you!

You could use Tuckey's very powerful URLRewriteFilter. i.e.
<rule>
<from>^/abra-kadabra$</from>
<to>/admin.action</to>
</rule>
This rule would forward all browser requests on "/abra-kadabra" to "/admin.action" transparent to the user.

Servlet specification doesn't give you many options. You can map your servlet to specific path (/some/specific/path), to all paths under some hierarchy (/dir/*) or to some extension (*.action). Best what you can do is to map your servlet to *.action, and then determine action to be executed based on request.getRequestURI() or request.getServletPath().

Related

Forward appspot domain to my domain

Is there an easy way to forward my appspot domain to my domain. Basically redirect myappid.appspot.com to myappid.com. If people somehow find the appspot domain I don't want them using it.
I am already showing the same application at both domains. I just don't want users to be able to use the application at myappid.appspot.com.
What you need is a Servlet Filter to redirect. This thread gives you the details: How to use a servlet filter in Java to change an incoming servlet request url?
Just so the answer is here to easily find. I added the code below to a filter that runs on every page request.
if(((HttpServletRequest) req).getServerName().contains("appspot.com")){
((HttpServletResponse) resp).sendRedirect("http://"+((HttpServletRequest) req).getServerName().replace("myappid.appspot.com", "myappid.com") + ((HttpServletRequest) req).getRequestURI());
}

How servlet filter will dispatch error message on request page?

I have written a servlet filter which is configured to be invoked for each url (/*). On the basis of some condition, if the condition is passed, I want to proceed normal execution by chain.doFilter(request,response), I also want to open same request URL with error message..
"say value entered in particular textbox is incorrect". Is this possible?
Do I have to use response.sendRedirect(request.getURL())? I hope I wont end up in infinite loop as I have configured filter on each URL. I am doing validation check on request parameter.
Just do the same as you'd do in a servlet: perform a forward.
request.getRequestDispatcher("/WEB-INF/some.jsp").forward(request, response);
A filter is by default not (re)invoked on a forward. Additional advantage is that the JSP reuses the same request and thus you can just set the validation error messages as a request attribute without the need for session or cookie based workarounds/hacks.
Unrelated to the concrete problem, this isn't entirely the right approach. Form-specific validation job should be performed in a servlet, not in a filter. If you'd like to keep your servlet(s) DRY, then look at the front controller pattern or just adopt a MVC framework which already offers a front controller servlet and decent validation out the box, such as JSF or Spring MVC.

What is a right way to use servlets?

I'm studying EJB3.
I have a session bean which provides services to create/update customer accounts.
This session bean offers services on the lines of:
public void addCustomer(Customer c);
public void updateCustomer(Customer c);
Ideally I'd like to have a single servlet: CustomerServlet and it would invoke the session beans that I have listed above.
Problem is that I have two JSPs: UpdateAccount.jsp and CreateAccount.jsp. Both of these JSPs have a form with a method POST and action "CustomerServlet".
How can I distinguish in a customer servlet which operation I should carry out: createAccount or updateAccount?
I guess the alternative is to have a separate servlet for each operation...
Thank you
I'm not really certain about the best practice for this but I have a couple of suggestions that might work:
If your form is being submitted using a submit button, you could distinguish the request on the basis of the value of the <button-name> parameter. So if your buttons had the values Update and Create and were named account-submit, by checking the value you get with request.getParameter('account-submit'), you'd be able to tell which button was clicked to generate this request. If you named them differently, you could also just check which of the two parameters was not null and you'd know which form submit you were handling.
Note that if you have only a single text field in your form and the user hits Enter instead of clicking the button, you'll get a null in your servlet! See my blog post about this behaviour.
Check the Referer header - I wouldn't really recommend this since you wouldn't always know the context of the deployed app, this value may not always be present and it can be easily spoofed.
Add another mapping for your servlet so that it's accessible at both http://myapp.example.com/context/create and http://myapp.example.com/context/update. You can then check the ServletPath (request.getServletPath()) to see what 'servlet' the request came in for. I'd probably go with this one since it seems the most robust to me but you might also want to add the other two checks just to make sure. In your web.xml, you'd want something like
<servlet>
<servlet-name>CreateUpdateServlet</servlet-name>
<servlet-class>my.package.CustomerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CreateUpdateServlet</servlet-name>
<url-pattern>/create</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>CreateUpdateServlet</servlet-name>
<url-pattern>/update</url-pattern>
</servlet-mapping>
JSPs are Servlets, just in a different source code form, there is no reason to POST to a different Servlet, you can just POST back to the same JSP.
You don't need the servlet. JSPs (or Facelets) can talk directly to the beans via EL.

A servlet or filter that dynamically maps /xxx/yyy/zzz to class XxxYyyZzz.java

I want to write a servlet or filter that automatically maps the url /xxx/yyy/zzz to class XxxYyyZzz.java.
For example the following URLs will map to the following java classes:
/comment/add --> CommentAdd.java
/comment/delete --> CommentDelete.java
/comment/view --> CommentView.java
/search --> Search.java
/viewposts --> Viewposts.java
In addition the servlet or filter must comply with two extra requirements:
The servlet or filter should have a servlet mapping of "/*", I dont want a prefix with several servlets "/comment/*", "/search", etc.
Maybe difficult, but having a servlet mapping of /* should not allow it to override the JSP processing. Meaning, if a class is not found, it should check if a jsp page exists and run it.
I want to know how can this be done using the Servlet API. Please don't refer me to any framework that does the job. Just show me the code.
The classes that are mapped to will follow the command pattern or could be a subclass of the HttpServlet. In both cases, a method should exist like "execute(HttpServletRequest request, and HttpServletResponse response)". This method will be automatically executed once the URL is accessed and the java class is figured out possibly using a single servlet or filter.
I'm not sure, if I got what you mean. In case I did:
You need nothing special, write a single Servlet mapped to "/", so it gets everything. Parse the PATH_INFO (don't know now how it gets called in Java), use Class.forName (or use a pre-filled Map), and call its method execute.
Here is a http://www.tuckey.org/urlrewrite/ filter implementation that might help you. Check it out. I have not used it myself though.
You can use Stripes framework with its default NameBasedActionResolver config.

Modify the filter chain - Or select servlet to respond to request using filter

I am trying to use a filter to map requests. I am trying to do this for two reasons, firstly to dynamically generate URI's and have them mapped to the appropriate servlet and secondly to catch URI's which are not registered and handle them appropriately.
So I'm using a catch-all filter to process the URI and determine the response. I would like some way of modifying the filter chain, or some way to set the servlet which responds to the request from within the filter. I have been unsuccessful using filterConfig.getServletContext().getRequestDispatcher().forward() to send to jsp, ideally though I would like to map to a servlet but can't figure out how.
The reason I am not doing this from within a servlet is that I have some URIs which are fixed within web.xml and if I use a catch-all servlet those URIs do not get mapped. Is this possible, is it clean or it going to get really messy?
I don't think this is the right way to do it.
If you look at what web MVC frameworks do, they have a front controller servlet that maps URLs to controllers, which themselves can accept HTTP requests and return HTTP responses. I think that's a design worth emulating, not your filter idea.

Categories

Resources