views:

390

answers:

4

Hi, i want to know how to generate a url in a servlet. I have a login servlet, and every time that add a user i want to gen. a url for each user profile. Can anyone help me please?

+1  A: 

It sounds like you might want to look into REST technologies. There is a tutorial here you might want to have a look at.

krosenvold
+5  A: 

The easiest way is to declare a servlet mapping like the following:

  <servlet-mapping>
    <servlet-name>UsersSelvlet</servlet-name>
    <url-pattern>/Users/*</url-pattern>
  </servlet-mapping>

Now, whenever you get a request for MyApp/Users/UserId you read the request path, get the userId and check if the user exists. If not you return 'Not found'. Otherwise you return the user's page.

This is a quick and dirty implementation of a RESTful service.

kgiannakakis
if the user's page does not exist, how i will return the user's page ?
Agusti-N
You will generate the user's page "on the fly", whenever it is requested.
kgiannakakis
A: 

Do you need URL rewriting? Something like this, perhaps, but instead of RMI generate your own user id

Yardena
A: 

I think the solution of kgiannakakis is very good. I just want to add some details, because reading the comment of Agusti-N I have the suspect that may be he is missing something.

Let's say that you have the UsersServlet described by kgiannakakis, a jsp called showUserProfile.jsp and an userBean that has all the properties of the user's profile needed to be shown in the jsp.

When a new user registers to your application, you need to do nothing more than you already do now. Just register a new user in the db, and forget the login servlet.

Now suppose that I registered to your app with my username alexmeia.

When someone digit the url yourApp/Users/alexmeia the UsersServlet is called. This servlet gets the username alexmeia from the request url, checks in the DB if this username exists and if exist load all the properties of this user in the userBean.

After that, forward to showUserProfile.jsp, which shows the user profile reading it from the userBean.

Obviously, if the user alexmeia is not in the Db, you can redirect to a generic userNotFound.jsp, or go to home page and show a message and so on...

This works for all the registered users in the same way. You don't need to really create a real new url for every new user.

alexmeia
thanks alexmeia, this answer are very helpful for me.
Agusti-N