1

I want to map this url to one servlet:

http://localhost:8080/user/dynamic-user-name/edit

And this to another servlet:

http://localhost:8080/user/dynamic-user-name

where dynamic-user-name will change depending on which user enters.

I have tried the following but it seems like the /* will direct everything.

<servlet>
    <servlet-name>userservlet</servlet-name>
    <servlet-class>controller.UserServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>edituser</servlet-name>
    <servlet-class>controller.EditUserServlet</servlet-class>
</servlet>

 <servlet-mapping>
    <servlet-name>userservlet</servlet-name>
    <url-pattern>/users/*</url-pattern>
</servlet-mapping>
  <servlet-mapping>
    <servlet-name>edituser</servlet-name>
    <url-pattern>/users/*/edit</url-pattern>
</servlet-mapping>

Is it possible to map them separately in some way? I'm using a tomcat server.

Solution/workaround (not mapped to different servlets)

I solved it without web.xml and instead used getRequestUrl(); in the servlet with some regex, but I'm still looking for a more clean solution since this ends up with a lot of if-statements.

String uri = URLDecoder.decode( request.getRequestURI(), "UTF-8" ).toLowerCase();  
if(uri.matches("/users/(.*?)/edit")){
        Pattern pattern = Pattern.compile("/users/(.*?)/edit");
        Matcher matcher = pattern.matcher(uri);

        if (matcher.find())
        {
            String username = matcher.find(1);
            // Do stuff
        }
}
gugge
  • 918
  • 1
  • 11
  • 17
  • 1)Servlets are not designed to work in this way.2) It is really not a conventional way to use url path. Why do you want to do it ? – davidxxx Aug 16 '17 at 10:19
  • I used request.getRequestURI() to see which requests the users did earlier but it got kinda messy so I'm searching for a more elegant way to structure the code. @davidxxx – gugge Aug 16 '17 at 10:22

0 Answers0