6

I have a servlet called User.java. It is mapped to the url pattern

 <servlet-mapping> <servlet-name>User</servlet-name> <url-pattern>/user/*</url-pattern> </servlet-mapping> 

Inside the Servlet, the path following the slash in user/ is analyzed, data about that user is retrieved from the database, set in attributes, and then the page user_home.jsp is to be displayed. The code to make this happen is:

 User user = UserManager.getUserInfoById(userPath); request.getSession().setAttribute("user", user); request.getRequestDispatcher("resources/jsp/user_home.jsp").forward(request, response); 

The problem is, that rather than opening this user_home.jsp, the request is mapped once again to the same servlet User.java. It does nothing.

I've put output statements at the beginning of the doGet method, so I can see that the URL is

http://localhost:8080/myproj/user/resources/jsp/user_home.jsp 

so it seems the obvious problem is that it's mapping right back to the user/* pattern.

How do I get the Servlet to display this page without going through URL mapping, and properly display the jsp I need it to?

1
  • 1
    forward() does not change the URL. Are you sure you're being redirected from user_home.jsp to User.java ? if so, maybe you should "clean" the request from certain parameters. Commented Sep 5, 2014 at 2:54

2 Answers 2

5

If the path passed to request.getRequestDispatcher() does not begin with a "/", it is interpreted as relative to the current path. Since your servlet's path is /user/<something>, it tries to forward the request to /user/resources/jsp/user_home.jsp, which matches your servlet mapping and therefore forwards to the same servlet recursively.

On the other hand, if the path passed to request.getRequestDispatcher() begins with a "/", it is interpreted as relative to the current context root. So assuming that the resources directory is located at the root of your webapp, try adding a "/" at the beginning of the path, e.g.:

request.getRequestDispatcher("/resources/jsp/user_home.jsp").forward(request, response); 
Sign up to request clarification or add additional context in comments.

Comments

1

you don't want to use the * in your servlet mapping. simply because everytime that you have /user/ in your URL it will redirect back to the servlet.

the asterisk accepts every URL that has /user/ and redirect it based on servlet mappiing, so you might want to make it

<servlet-mapping> <servlet-name>User</servlet-name> <url-pattern>/user/User</url-pattern> </servlet-mapping> 

and use it in your action as action = user/User

4 Comments

What do you mean by action?
<form action = "user/User" ></form>
Ah ok. But there's form on the page
i mean so send the form to the servlet you may use the following user/User

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.