Sep 13, 2015

Servlet Part 03

HTTP CookieAn HTTP cookie (also called web cookie, Internet cookie, browser cookie or simply cookie, the latter which is not to be confused with the literal definition), is a small piece of data sent from a website and stored in a user's web browser while the user is browsing that website. Every time the user loads the website, the browser sends the cookie back to the server to notify the website of the user's previous activity. Cookies were designed to be a reliable mechanism for websites to remember stateful information (such as items in a shopping cart) or to record the user's browsing activity (including clicking particular buttons, logging in, or recording which pages were visited by the user as far back as months or years ago). more details about HTTP Cookie
A servlet can send an HTTP cookie, named JSESSIONID, to the client for session tracking. This cookie may be marked as HttpOnly, which ensures that the cookie is not exposed to client-side scripting code, and thus helps mitigate certains kinds of crosssite scripting attacks:

 SessionCookieConfig config = request.getServletContext().getSessionCookieConfig();  
 config.setHttpOnly(true);  

Alternatively, URL rewriting may be used by the servlet as a basis for session tracking. The ServletContext.getSessionCookieConfig method returns SessionCookieConfig, which can be used to configure different properties of the cookie. 

HTTP Session
The HttpSession interface can be used to view and manipulate information about a session such as the session identifier and creation time, and to bind objects to the session. A new session object may be created
 protected void doGet(HttpServletRequest request,HttpServletResponse response) {  
   HttpSession session = request.getSession(true);  
   //. . .  
 }  

The session.setAttribute and session.getAttribute methods are used to bind objects to the session.

Request Dispatcher
A servlet may forward a request to another servlet if further processing is required. You can achieve this by dispatching the request to a different resource using RequestDispatcher, which can be obtained from HttpServletRequest.getRequestDispatcher or ServletContext.getRequestDispatcher. The former can accept a relative path, whereas the latter can accept a path relative to the current context only
 prprotected void doGet(HttpServletRequest request,HttpServletResponse response) {  
   request.getRequestDispatcher("bank").forward(request, response);  
   //. . .  
 }  

In this code, bank is another servlet deployed in the same context.

The ServletContext.getContext method can be used to obtain ServletContext for foreign contexts. It can then be used to obtain a RequestDispatcher, which can dispatch requests in that context.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.