meljun_cortes_jedi slides web programming chapter03 advanced servlets

Upload: meljun-cortes-mbampa

Post on 06-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    1/51

    Advanced Servlets

    Web Programming

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    2/51

    Response Redirection

    2Web Programming

    There are cases when we want our servlet only to do someinitial processing and leave the generation of actual contentto some other entity. In these cases, it would be better forthe servlet to redirect output generation.

    Two methods that a developer can use to performredirection:

    Through the use of a RequestDispatcher object.

    By using the sendRedirect() method found in the

    HttpServletResponse object.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    3/51

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    4/51

    include and forward

    4Web Programming

    Both methods take in the content produced by the specifiedlocation and make it a part of the servlet's response to theuser.

    Main difference: forward makes the target the entity with sole responsibility of

    generating response.

    include only incorporates the contents of the target.

    Using include, we could add other content to the response, possibly evenincluding another target.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    5/51

    include

    5Web Programming

    public DispatchServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    response.setContentType("text/html");

    PrintWriter out = response.getWriter();

    out.println("Error occurred during login request processing");

    RequestDispatcher rd = request.getRequestDispatcher("/login.html");

    rd.include(request, response);

    }

    }

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    6/51

    forward

    6Web Programming

    public DispatchServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    response.setContentType("text/html");

    PrintWriter out = response.getWriter();

    out.println("Error occurred during login request processing");

    RequestDispatcher rd = request.getRequestDispatcher("/login.html");

    rd.forward(request, response);

    }

    }

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    7/51

    include and forward

    7Web Programming

    Both of the servlets defined above make use of a web pagenamed login.html to form the basis of its output.

    Login Page

    User name :

    Password :

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    8/51

    include

    8Web Programming

    On running the first servlet, the one making use of theinclude method, the following output was generated:

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    9/51

    forward

    9Web Programming

    Running the second servlet though, yields the followingresults:

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    10/51

    include and forward

    10Web Programming

    Given the virtually identical codes, we have two differentoutputs:

    Using the include method, the String message we output to the userprior to calling the method is displayed. Using the forward method,

    the message we added into the response prior to calling the methodis not part of the output.

    With the forward method, all contents in the response buffer arecleared prior to the method call, after which the response isimmediately committed; no further content can be added. With theinclude method, all contents placed in the response buffer are keptbefore and after the method call.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    11/51

    include

    11Web Programming

    Using the include method, it is possible for our servlet topresent as a whole the output of several different sources.

    It also allows us to append messages to otherwise staticcontent.

    Since the include method only adds content from anothersource and does not commit the response after its call, wecan use it repeatedly. By using this principle, theLoginServlet that follows is able to create a response

    containing three different pages.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    12/51

    12Web Programming

    public LoginServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    RequestDispatcher rd = null;// retrieve user parameters from formString loginName = request.getParameter("loginName");String password = request.getParameter("password");

    User user = null;// create the JavaBean implementing authentication functionalityUserService service = new UserService();

    user = service.authenticateUser(loginName, password);

    if (user == null) {// generate error message

    response.setContentType("text/html");PrintWriter out = response.getWriter();out.println("User does not exist with given login and/or password");

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    13/51

    13Web Programming

    // return user to login pagerd = request.getRequestDispatcher("/login.html");

    rd.include(request, response);out.close();} else {// store the User object into session scope

    HttpSession session = request.getSession();session.setAttribute(ApplicationConstants.USER_OBJECT, user);

    // build the response from multiple HTML components

    rd = request.getRequestDispatcher("/header.html");rd.include(request, response);

    rd = request.getRequestDispatcher("/mainContent.html");rd.include(request, response);

    rd = request.getRequestDispatcher("/footer.html");rd.include(request, response);

    }}

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    14/51

    sendRedirect

    14Web Programming

    The other way of redirecting output to an entity outside theservlet is the sendRedirect method:

    public void sendRedirect(String relativePath)

    Can be found in the HttpServletResponse object.

    The String parameter it takes in represents the path to the target wewant to redirect the user to. Calling this method effectively instructsthe browser to send in another HTTP request, this time to thespecified target.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    15/51

    sendRedirect

    15Web Programming

    The target is the sole entity responsible for generating thecontent. However, the re-sent request presents severalpractical differences compared to the forward method:

    The URL in the browser bar reflects the target specified.

    Data stored in the previous request object is discarded. Can befound in the HttpServletResponse object.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    16/51

    Response Redirection:

    Summary

    16Web Programming

    It is recommended then that:

    The include method be used to allow for multiple output sources.

    The forward method be used if redirecting to a component whichgenerates dynamic content.

    The sendRedirect method be used when redirecting to staticcontent.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    17/51

    Scope Objects

    17Web Programming

    The servlet specification allows us four scopes in which toplace data, in order to share them among our components.They are, in increasing scope:

    Page

    The scope encompassing a single JSP page.

    Variables declared within the page are visible only within that page.

    The object associated with this scope is a PageContext object.

    Request

    The scope encompassing a client's single request.

    Data that is stored within this scope is visible to all web components handling theclient's request.

    The object associated with this scope is the HttpServletRequest object.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    18/51

    Scope Objects

    18Web Programming

    (Scope continued)

    Session

    The scope encompassing a single session with the client.

    Data within this scope is visible to all web components the client makes use of

    during the session. Data from one user session, however, is not visible fromwithin another user's session.

    The object associated with this scope is the HttpSession object. An instance ofthis can be retrieved by using the getSession() method in the HttpServletRequestobject.

    Application

    The scope encompassing the whole of the application.

    Data stored within this scope is visible to all components regardless of whichuser request or client session they are handling and last until the application isterminated.

    The object associated with this scope is the ServletContext object.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    19/51

    Storing and Retreiving Data

    from Scope

    19Web Programming

    To store date within a scope object:

    public void setAttribute(String key, Object value);

    The String parameter that this method takes will store the Objectunder that value.

    To retrieve the data later, pass the same key as theparameter:

    public Object getAttribute(String key);

    Null is returned If there is no object that can be retrieved.

    Since the return type is Object, it would be up to the developer tocast the Object to the appropriate class and perform type-checking.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    20/51

    Storing and Retreiving Data

    from Scope

    20Web Programming

    To remove an attribute from the scope object simply call onthe removeAttribute() method and pass the key to theattribute as its parameter.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    21/51

    Storing and Retreiving Data

    from Scope

    21Web Programming

    Sample Scenario

    We want our application to be able to display the details about aperson given their personalID. This personalID will be provided bythe user. To promote maintainability, we separate the componentthat will retrieve the personal details and the component that willdisplay the information to the user. These two components thencommunicate using the data storage and retrieval facilities availablein request scope.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    22/51

    22Web Programming

    public PersonalDataRetrievalServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws

    ServletException, IOException {

    // retrieve user supplied parameterString personalID = request.getParameter("personalID");

    // create business object that handles implementation of retrieving data given id.

    DataService service = new DataService();

    // retrieve the person object that contains the details we need

    Person person = service.retrievePersonalDetails(personalID);

    // store the data into request scope using a constant key

    request.setAttribute(ApplicationConstants.PERSON, person);

    // forward the request into the component that will display the details

    RequestDispatcher dispatcher = request.getRequestDispatcher("/DisplayServlet");

    dispatcher.forward(request, response);

    }

    }

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    23/51

    23Web Programming

    public DisplayServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws

    ServletException, IOException {

    // retrieve the Person object that contains the detailsPerson person = (Person) request.getAttribute(ApplicationConstants.PERSON);

    // construct the response based on the infoStringBuffer buffer = new StringBuffer();buffer.append("Personal Info");buffer.append("Details :
    ");

    buffer.append("Name : ");buffer.append(person.getName());buffer.append("
    Address : ");buffer.append(person.getAddress());buffer.append("");

    // display the responseresponse.setContentType("text/html");

    PrintWriter out = response.getWriter();

    out.println(buffer.toString());out.close();

    }

    }

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    24/51

    Storing and Retreiving Data

    from Scope

    24Web Programming

    (Sample Scenario continued)

    A couple of notes regarding the example:

    First, the second servlet was able to retrieve the data from request scopebecause it is still part of the same request. If we had used the sendRedirect wayof redirecting control to the servlet the getAttribute method would have returnednull, since sendRedirect would have made the browser issue another request.This effectively ends the lifetime of the request object storing the data.

    Second, it is recommended that the keys used for storing and retrieving data bemade available to the application as constants, as in the example. This makessure that the exact same key is used for storage and retrieval, reducing thepossible amount of errors that can be encountered during development.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    25/51

    Session Tracking and

    Management

    25Web Programming

    Recall that HTTP is designed as a connected, statelessprotocol.

    A problem is presented for web applications: how tomaintain state for a particular user's web transaction?

    A solution for this problem is for the server to maintain theconcept of a "user session".

    While in a session, the server will be able to recognize a client over

    multiple requests.

    There are 3 typical solutions to the problem:

    Cookies

    URL-rewriting

    Hidden form fields

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    26/51

    Traditional Methods for

    Maintaining Session State

    26Web Programming

    Cookies

    Small data structures used by a web server to deliver data to a clientbrowser.

    This data is stored by the browser, and in some circumstances the browserreturns the data back to the web server.

    Using cookies, servlets can store "session IDs" that it can use toidentify the user as participating in a particular session.

    After the ID is generated, it is stored in a Cookie object, and sent back to the

    client browser for storage. This cookie object can then be retrieved from therequest object each time to determine if the user is in a session.

    To be able to retrieve the right map containing session data, servlets would thenretrieve the cookie containing the session ID, and, using that as a key, obtain theappropriate HashMap.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    27/51

    27Web Programming

    ...// generate new session ID for userString sessionID = generateSessionID();

    // create new map object that will be used to store data to be maintained in sessionHashMap map = new HashMap();

    // retrieve a map that serves as a container for all session info.HashMap containerMap = retrieveSessionMaps();

    // add the newly created map object into the map containing all session infocontainerMap.put(sessionID, map);

    // create the cookie that will be stored in the browserCookie sessionCookie = new Cookie("JSESSIONID", sessionID);

    // add the cookie to the response and ask the browser to store it

    response.addCookie(sessionCookie);

    ..

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    28/51

    Traditional Methods for

    Maintaining Session State

    28Web Programming

    (Cookies continued)

    While cookies are a good solution for session tracking, its usagerequires developers to handle a lot of details:

    Generating a unique session id for each user.

    Retrieving the appropriate cookie from the browser that contains the session ID.

    Setting an appropriate expiration time for the cookie .

    Another problem with cookie usage is that some users disablecookie support for their browser for security concerns.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    29/51

    Traditional Methods for

    Maintaining Session State

    29Web Programming

    URL Rewriting

    The client browser appends a unique session ID to the end of eachrequest it makes to the end of each request it makes to the server.

    This is another good solution, and one that works even if the userhas disabled the use of cookies. However, there are two problemsassociated with this approach:

    The server must make sure that each session ID it gives out is unique.

    The entire application must be written such that the session ID is appended to all

    links / URLs pointing to the application. Any request that does not include thesession ID would be not be considered part of the session and will not haveaccess to session specific information.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    30/51

    Traditional Methods for

    Maintaining Session State

    30Web Programming

    Hidden form fields

    A hidden form field is introduced to HTML forms, with the valuebeing set to a particular session ID.

    This method is very limited due to the fact that it can only be usedwhen there is a form in the page the client is using.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    31/51

    Session Tracking in Servlets

    31Web Programming

    HttpSession API

    A high-level API by the servlet specification to provide access tosession tracking.

    Session ID recognition, cookie manipulation details, and URL-

    information extraction details are abstracted from the developer.

    The developer is provided a convenient location in which to storedata for a user session.

    Correct usage allows your application to automatically switch to theURL-rewriting method if it detects that cookie support in the client

    browser is disabled.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    32/51

    Session Tracking in Servlets

    32Web Programming

    Obtaining an instance of the HttpSession object

    The HttpSession object representing session data associated for agiven client request can be obtained by calling the getSession()method in the HttpServletRequest object.

    By passing in a boolean value to the the getSession() method (i.e.,getSession(true) ) we can specify to the server whether a newHttpSession object should automatically be created in case the useris not currently participating in any session.

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

    ....

    HttpSession session = request.getSession();

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    33/51

    33Web Programming

    public class GetParameterValuesServlet extends HttpServlet {

    public void doGet(HttpServletRequest request,

    HttpServletResponse response) throws ServletExceptionm IOException{

    String paramValues[] = request.getParameterValues("sports");

    StringBuffer myResponse = new StringBuffer();

    PrintWriter out = response.getWriter();

    out.println("Your choices");

    out.println("Your choices were : ");

    for (int i = 0; i < paramValues.length; i++) {

    out.println("
    ");

    out.println(paramValues[i]);

    }

    }

    }

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    34/51

    Session Tracking in Servlets

    34Web Programming

    Storing and retrieving data in a session

    With the HttpSession API, developers no longer have to explicitlymanage objects to store data that need to be maintained within auser session. All that is needed is to call on either of the followingmethods:

    public void setAttribute(String key, Object value)

    public Object getAttribute(String key)

    These are the same methods we have encountered during our discussion of thethe different object scopes. Actually, the HttpSession object that we are workingon now represent the session scope previously discussed.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    35/51

    35Web Programming

    public class LoginServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    User user = authenticateUser();

    ...HttpSession session = request.getSession();

    session.setAttribute("userObject", user);...

    }}

    public class InfoServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    HttpSession session = request.getSession(); User user = (User)session.getAttribute("userObject");

    // perform necessary operations on user object here}

    }

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    36/51

    Session Tracking in Servlets

    36Web Programming

    Removing data stored in session

    To remove data placed in session scope, call on theremoveAttribute() method, and pass in as a parameter the String keyassociated with the data.

    public class InfoProcessingServlet extends HttpServlet {public void doPost(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {HttpSession session = request.getSession();

    session.removeAttribute("tempData");

    // pass control on to the next web pageresponse.sendRedirect("next.html");

    }}

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    37/51

    Session Tracking in Servlets

    37Web Programming

    Terminating the session

    Automatic termination through timeout

    Sessions are automatically terminated after a predefined maximum interval. Thisinterval can be found and configured in the application's deployment descriptor.

    ...30

    ...

    The value of 30 in the session-timeout element tells the server to wait for aninactive period lasting 30 minutes before terminating the session. At this point, allobjects placed inside session will be removed from scope, and the HttpSessionobject becomes invalid.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    38/51

    Session Tracking in Servlets

    38Web Programming

    (Terminating the session continued)

    Programmatic termination

    A session can be terminated programatically by calling on the invalidate() methodin the HttpSession object.

    For situations where the user no longer needs to be part of a session. Resources are freed up quicker.

    Ensures that any sensitive data stored in the session is removed immediately.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    39/51

    39Web Programming

    public class LogoutServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException {

    HttpSession session = request.getSession();

    // perform other log out activities here

    //invalidate user sessionsession.invalidate();

    // send user back to the login page of our applicationresponse.sendRedirect("login.jsp");

    }}

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    40/51

    Session Tracking in Servlets

    40Web Programming

    Performing URL-Rewriting

    By default, the HttpSession API makes use of cookies to tracksessions. However, we should develop our web applications suchthat it can work equally well on browsers not supporting cookies byadding support for URL rewriting.

    We can add this support for URL rewriting by making use of theencodeURL() method found in the HttpServletResponse object. Thismethod takes in a String representing a path or URL as itsparameter. It then determines whether cookie support is enabled onthe target browser. If it is enabled, it returns the given String as is.

    However, if cookies are disabled, it enables URL rewriting byappending the session ID to the given URL.

    ...String encodedURL = response.encodeURL("/welcome.jsp");out.println("Click here to continue");...

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    41/51

    Filters

    41Web Programming

    Advanced web components introduced since the Serlvet 2.3Specification.

    Stand between a client request and a particular resource.

    Any attempts to retrieve the target resource has to go through the

    filter.

    The resource can be any static or dynamic source of content (HTML,JSP, GIF, ...).

    Intercept client requests and exist as part of a chain.

    There is a defined sequence of filters that a request passes throughbefore finally arriving at the target resource.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    42/51

    Filters

    42Web Programming

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    43/51

    Filters

    43Web Programming

    Useful components since they provide the developer aneasy way of including additional processing beforeresources within the web application are accessed.

    This kind of functionality is possible using only servlets and

    response redirection. This is more difficult to implement though, andrequires that each level servlet be aware of the location of the nextservlet in the sequence.

    Filters have no such limitation; it is the servlet container thatmanages the sequence of components that are called before therequest ever reaches the endpoint, and not the developer.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    44/51

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    45/51

    Creating a Filter

    45

    Web Programming

    (javax.servlet.Filter methods continued)

    void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException

    Contains all of the functionality of the Filter class.

    If the Filter is participating in a web environment (as is commonly the case), thedeveloper may choose to cast the request and response objects to instances ofHttpServletRequest and HttpServletResponse, respectively, so that they canretrieve HTTP-specific information.

    Like a servlet, the container creates only one instance of aFilter object and uses multi-threading to allow it to handle

    multiple concurrent client requests. This means that thismethod MUST be defined to be thread-safe.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    46/51

    46

    Web Programming

    public LoggingFilter implements Filter {private FilterConfig config;

    public void init(FilterConfig config) {

    this.config = config;}

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws ServletException, IOException {// retrieve the ServletContext object which we will use to perform the logging operationServletContext context = config.getServletContext();

    // create as a log entry the URL accessed by the user during request processing.String logEntry = request.getServerName() + ":" + request.getServerPort();logEntry += "/" + request.getContextPath() + "/" + request.getPathInfo();

    logEntry += "--> accessed by the user on " + new java.util.Date();

    // use the logging facilities built-in into the ServletContext objectcontext.log(logEntry)

    // call on the next filter in the chainchain.doFilter(request, response);}public void destroy() {}

    }

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    47/51

    Filter Chains

    47

    Web Programming

    Allow Filters to be applied in a certain sequence for aparticular resource.

    Represented by a FilterChain object.

    Without this ability, a Filter is functionally the same as aServlet.

    Allow a clean separation between different processinglayers.

    The sequence of the filter chain is determined by a filter's

    location in the deployment descriptor and follows inascending order the ordering of elementsthat represent the mapping of each filter.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    48/51

    Filter Chains

    48

    Web Programming

    doFilter method in the FilterChain object

    The only access a developer has to the sequence of Filters.

    Calls the next Filter in the sequence, or the target resource if thecurrent Filter is the last in the sequence.

    Only requires the current ServletRequest and ServletResponseobjects as parameters.

    If a developer fails to call on this method, the rest of the filters in thechain (as well as the target resource), will NOT be called.

    public class SecurityFilter implements Filter {i t Filt C fi fi

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    49/51

    49

    Web Programming

    private FilterConfig config;

    public void init(FilterConfig config) {this.config = config;}

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws ServletException, IOException {HttpServletRequest httpRequest = (HttpServletRequest) request;HttpServletResponse httpResponse = (HttpServletResponse) response;HttpSession session = httpRequest.getSession();

    User user = (User) session.getAttribute("userObject");if (user != null) {// if the user passes the conditions, allow access to the resourcechain.doFilter(request, response);

    } else {PrintWriter out = response.getWriter();out.println("Welcome. Please log in before continuing with the application.");

    RequestDispatcher rd = request.getRequestDispatcher("login.jsp");rd.include(request, response);}

    public void destroy() {}}

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    50/51

    Filter Configuration

    50

    Web Programming

    Given that web.xml files are very particular about theordering of its elements, it is best to make sure that the filterelement entries are defined before any servlets, but onlyafter any context-param entries. Also, all filter-mapping

    entries should be located after any filter definition. By default, Filters are not applied towards web components

    (other servlets, JSP) that are the target of include or forwardcalls from an RequestDispatcher object. They are appliedonly to requests that are directly made by the client. This

    behaviour can be changed however by adding one or moredispatch elements to a filter's mapping.

    Dispatch elements have one of the following values: REQUEST,INCLUDE, FORWARD, and ERROR.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter03 Advanced Servlets

    51/51

    51

    Web Programming

    ...LoggingFilterjedi.filters.LoggingFilter

    LoggingFilter/*REQUESTINCLUDE