JSP & Servlets
1.0.0
1.0.0
  • Setting up
  • Pre-requisites
  • Servlet Part 1
  • Servlet Part 2
  • Understanding the servlet
  • Servlet XML Configuration
  • POST method and passing parameters
  • Passing more parameters
  • Understanding GET and POST
  • Request, Session and Context Part -1
  • Request , Session and Context Part - 2
  • Understanding init, service and ServletConfig
  • Hello JSP
  • Understanding JSP
  • JSP Page directives
  • HttpServletRequest Path Decoding
  • Scopes in JSP and the PageContext Object
  • Understanding MVC pattern
  • PART -1 Writing an MVC app
  • JSTL
    • For-each
  • CRUD-1
  • Project Work
    • Create a Simple Java Web Application Using Servlet, JSP/JSTL and JDBC/Transaction
  • Locale Filter
  • Action Plan
    • Schedule
    • Hit webservice
Powered by GitBook
On this page
  • Session Object vs Context Object :
  • Session Object :
  • Context Object :
  • Output:

Was this helpful?

Request , Session and Context Part - 2

PreviousRequest, Session and Context Part -1NextUnderstanding init, service and ServletConfig

Last updated 6 years ago

Was this helpful?

Session Object vs Context Object :

Session Object :

  1. One per user/machine

  2. Objects available across requests

  3. Perfect for login sessions and shopping carts

  4. Every request object has a reference to the session object.

Context Object :

  1. Across the entire application

  2. Shared across servlets and users

  3. Initialization code / Common bulletin board

  4. Use the Context object

How to create session ?

ServletContext context = request.getServletContext();
		if (userName != null) {
			httpSession.setAttribute("userName", userName);
			context.setAttribute("userName", userName);
		}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("Hello from Get method of XML servlet");
		response.setContentType("text/html");
		String userName = request.getParameter("userName");
		PrintWriter printWriter = response.getWriter();
		printWriter.println("Hello from GET method using request parameter " + userName);
		//getting session
		HttpSession httpSession = request.getSession();
		//getting context
		ServletContext context = request.getServletContext();
		if (userName != null) {
			httpSession.setAttribute("userName", userName);
			context.setAttribute("userName", userName);
		}
		printWriter.println("Hello from GET method using session parameter " + httpSession.getAttribute("userName"));
		printWriter.println("Hello from GET method using context parameter " + context.getAttribute("userName"));
	}

Output:

Session object is null for other user/browser