Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a URL in a servlet?

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?

like image 459
Agusti-N Avatar asked Dec 31 '22 03:12

Agusti-N


2 Answers

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.

like image 168
kgiannakakis Avatar answered Jan 11 '23 20:01

kgiannakakis


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.

like image 37
alexmeia Avatar answered Jan 11 '23 20:01

alexmeia