Dynamic url mapping has important role in showing the dynamic content because Users want some web address for their data.

Example :
facebook page of sodhanalibrary.com
>  There is no static page for sodhanalibrary
>  Here facebook showing  sodhanalibrary on the dynamic url https://www.facebook.com/sodhanalibrary
             
we need get uri what user has entered. By using below code we can get users information.
if user entered url is https://www.facebook.com/sodhanalibrary
     1. domain name https://www.facebook.com
     2. uri is sodhanalibrary


protected void doGet(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {
          String requri = request.getRequestURI().substring(
                               request.getContextPath().length() + 1);
          System.out.println(requri);

 }

in general java people will save files in WEB-INF folder. The files in WEB-INF are not available to users. We have to forward the request from servlet to file in WEB-INF folder.

Scenario :
1. User enters http://web.com/srinivas
2. System has to show profile page of srinivas which is in WEB-INF/srinivas-profile.html


import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Sample extends HttpServlet {
 public Sample() {
  super();
 }

 protected void doGet(HttpServletRequest request,
               HttpServletResponse response) 
               throws ServletException, IOException {
      String requri = request.getRequestURI().substring(
    request.getContextPath().length() + 1);
      System.out.println(requri);
      if (requri.equals("srinivas")) {
  request.getRequestDispatcher("/WEB-INF/srinivas-profile.html")
     .forward(request, response);
      }
 }

 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
 }

}

In the above code if the uri is "srinivas" then it will forward the request to /WEB-INF/srinivas-profile.html.

In this way we can map our URL



dynamic url mapping in java with filter :

Here filter will take care of all url mapppings.The filter extracts URI from URL and forwards the request to specified resource.Let me explain with example.

Steps of dynamic url mapping ::
1. Client sends request "web.com/user/srinivas" to server
2. Filter identifies the request as Profile request because the URI starts with "user/"
3. Filter forwards the request to "/Profile" servlet with user-id as attribute.
4. Profile servlet reads the user-id and it extracts specific information related to that user-id and it will set those info to userpojo class
5. Profile forwards the request to "profile.jsp"
6. Profile.jsp will show profile information of the user


create web.xml like below
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<filter>
    <display-name>MyFilter</display-name>
    <filter-name>MyFilter</filter-name>
    <filter-class>sri.MyFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/MyFilter</url-pattern>
  </filter-mapping>
  <servlet>
    <description></description>
    <display-name>Profile</display-name>
    <servlet-name>Profile</servlet-name>
    <servlet-class>sri.Profile</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Profile</servlet-name>
    <url-pattern>/Profile</url-pattern>
  </servlet-mapping>
</web-app>

MyFilter.java which cares about all url mappings
package sri;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class MyFilter implements Filter {

    public MyFilter() {
    }

 public void destroy() {
 }

 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  String requri = ((HttpServletRequest) request)
                                .getRequestURI().substring(
                                    ((HttpServletRequest) request)
                                     .getContextPath().length() + 1);
  System.out.println(requri);
  //if request uri starts with user/ then system will forward the request to Profile servlet
     if (requri.startsWith("user/")) {
         //get userid from request uri
      String userid=requri.substring(5);
      System.out.println(userid);
      
      //set attribute "user" with userid value
      request.setAttribute("user", userid);
   
      //forward the request to Profile servlet
      request.getRequestDispatcher("/Profile")
        .forward(request, response);
     } else {
      chain.doFilter(request, response); 
     }
 }

 public void init(FilterConfig fConfig) throws ServletException {
 }

}

Profile.java which will extracts user info and forward it to profile.jsp
package sri;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Profile extends HttpServlet {

 public Profile() {
        super();
    }

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  //get user id from "user" attribute
  String userid = (String)request.getAttribute("user");
  
  //pojo for user prfile information
  UserPojo userpojo=new UserPojo();
  //get user info from database and set those info into userpojo
  
  //set userpojo as request attribute
  request.setAttribute("userpojo", userpojo);
  
  //forward the request to profile.jsp
  request.getRequestDispatcher("/WEB-INF/profile.jsp")
       .forward(request, response);
  //display user info which was stored in userpojo by profile.jsp 
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 }

}


5 comments:

  1. have you tried using JAX-RS for this? I think it would look really sexy, or you can use Spring MVC right?

    ReplyDelete
  2. In Spring Web MVC, you can dynamically map the URL like this:

    @RequestMapping("/users/{userId}")
    public String handler(@PathVariable String userId) {
    }

    ReplyDelete
  3. If the url http://web.com/srinivas is called then how does the server recognizes that the call has been made for the servlet sample.java. Please note here, the url http://web.com/srinivas can even be http://web.com/prashant.

    ReplyDelete
    Replies
    1. You need to compare Srinivas or Prasant or any other name in filter, then forward it to Sample.java. Check whether database entry is there or not in Profile for Srinivas or Prasant, If it is there then forward it to Sample.

      Delete

Blogroll

Popular Posts