Session Object vs Context Object :
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"));
}