Servlets Assignments

#1. Develop below html and Java Servlet files, which performs the below specified functionality
login.html
Servlet1.java
WelcomeServlet.java
Servlet2.java
logout.java

When successfully logged in, forward to Welcome Servlet. When failed to login, include login.html.
WelcomeServlet need to start a new session, and store username in Session attribute.
Display username(from session) in all Servlets.
Provide hyper links to display a Servlet from any other Servlet.
Destroy session, when logout link is clicked. logout link need to be displayed in all Servlets.

If you try to open any servlet directly from url, without logging in, it need to display a message, “login to continue”.

#2. In the above problem, try to add session time out functionality, i..e when user does not send a request for 3 mins, session need to be timed out, and automatically destroyed.

#3. In Servlets RequestDispatcher, from processing servlet try to include two other resources separately, ensure that response received by Browser has output from Processing Servlet, and other two included resources as well.

#4. Try to retrieve Servlet Context initialization parameter values( from the deployment descriptor, web.xml) and print them. In the same web app, try creating another servlet, which can access same Servlet Context initialization parameters.

#5.In Servlet RequestDispatcher, from Processing Servlet, forward the request to some other Servlet, and this some other servlet need to include another resource(an HTML or Servlet)

#6.Use HttpSession to find number of seconds spent by user on each page. Update the details in database table.

#7.Use Cookie and display html page to user, and let user select his/her own back ground color, from drop down options provided in the html page. When user visits the page again later, the background of html page need to be the color which has been selected by user, in earlier session. Validity period of cookie can be one week.

#8. Write a Filter for a Servlet or JSP, which removes Parameters with certain name in the request.

#9. Write a Servlet1, which forwards request to other Servlet2. Servlet1 need to adds few parameters which can be retrieved and displayed by Servlet2.

#10. Write a Servlet, which has login and signup functionality. MySQL database can be used, to store login details. User Account need to get locked for 1 day after three unsuccessful login attempts due to wrong password.

#11. Write a Servlet, and using HttpSessionListener try to get total number of currently logged in to the site.

#12. Use JSP/Servlet to develop Shopping Cart.

#13.Use JSP/Servlet to develop simple Payment Gateway.

#14. Generate PDF Bill using JSP

#15.Use AJAX to validate each field in Signup Form, and display error if an entered value is invalid, and display error beside respective field if its value is invalid.

You may also like to read:
object-oriented-assignments
core-java-assignments
applet-or-swings-assignments
basic-java-assignments

How to manage Sessions in Servlets

As known, HTTP Protocol is stateless, that means it does not store any session related information during the interaction between Web Browser and Web Server. HTTP Protocol just sends a request to Web Server, and receives response HTML page. But HTTP does not itself maintain any session information such as which user is currently browsing, etc…

Generally, a new session need to be created when user successfully logs in, and this user specific session data is being maintained, through out user interaction with various web pages. Finally when user logs out, the session need to be destroyed.
So it is responsibility of Server side program(like Java Servlets) to maintain session related information.

In case of Java, Servlets or JSP facilitates, to create, destroy, set and get values of Session. For this purpose javax.servlet.http.HttpSession class has been provided.

Why and when session is required

A session stores user specific data, when user is interacting with the web site. Not all the Servlets need sessions. Generally all Web sites with User login facility need to maintain session.

http-session
http-session

How to create a session: Session can be created by invoking
getSession() method in HttpServletRequest class. Below are two overloaded methods of getSession()
1.getSession(): This method has no parameters, and is always used to create new session.
2.getSession(boolean ):This method need to be invoked with true, to create a new session, and false to retrieve existing session which is in progress, and session which has been already created in previous servlets.

Below is description of few methods declared in javax.servlet.http.HttpSession
Once the session is created, below operations can be performed
1.void setAttribute(String attr_name, Object obj); is invoked to set an attribute name and value, so that this value can be retrieved[by invoking getAttribute(String attr_name) method] in other servlets

2.
Object getAttribute(String attr_name); is invoked to retrieve a value which has already been set to the session, by invoking setAttribute(String attr_name, Object obj);

Any User’s data can be stored in session, You can set and get any object in the session.
But be aware that, saving huge data in the session, may adversely affect your Web Application’s performance.
By default, session data is stored temporarily during web application’s execution and session data does not get stored persistently.
Though session data is stored on server side, it is good practice not to store confidential data in session.

3.session.removeAttribute(“attribute_name”); removes or deletes an attribute’s object from the session. You can use this method, when a specific attribute is more required. Other attributes remains intact in the session.

How to set session idle timeout

3.When no methods of session are invoked for certain period, automatically session gets destroyed.
setMaxInactiveInterval(int interval); interval in seconds

How to Destroy a session

4.When user tries to log out, invalidate() method of HttpSession is invoked to destroy the session which is in progress. After the session is destroyed, no session data is available.

Below are simple snippets, showing on how to create/destroy sessions, and how to get and put values into HttpSession.

Below is an HTML page, which invokes HttpSessionDemo servlet, when submitted.

<html>
    <head>
        <title>Session Demo</title>
    </head>
    <body>
        <form action="HttpSessionDemo">  
Name:<input type="text" name="userName"/><br/>  
<input type="submit" value="go"/>  
</form> 
    </body>
</html>

Below Servlet receives userName submitted by above html form, then creates a new session, then sets the username to uname attribute. Also provides an hyper link Visit, when clicked HttpSessionDemo1 Servlet is displayed

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
  
public class HttpSessionDemo extends HttpServlet {  
  
public void doGet(HttpServletRequest request, HttpServletResponse response){  
        try{  
  
        response.setContentType("text/html");  
        PrintWriter out = response.getWriter();  
          
        String n=request.getParameter("userName");  
        out.print("Welcome "+n);  
          
        //create new session
        HttpSession session=request.getSession();
        
        //set the attribute uname to the session
        //which can be further retrieved, in other servlets
        //as long as session is valid
        //Attribute value can be of any type, since Object is expected parameter
        session.setAttribute("uname",n);  
        
        //setMaxInactiveInterval(int interval), 
        //container invalidates session, if no requests from client, for a certain time(in seconds)
  
        out.print("visit");  
                  
        out.close();  
  
                }catch(Exception e){System.out.println(e);}  
    }  
  
}  

Below Servlet is processed, when Visit hyper is clicked, this servlet gets the existing session, also gets uname attribute from session, then displays uname value. Finally destroys session and it’s data by invoking sesison.inValidate()

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
public class HttpSessionDemo1 extends HttpServlet {  
  
    @Override
public void doGet(HttpServletRequest request, HttpServletResponse response)  
{
        try{  
  
        response.setContentType("text/html");  
        PrintWriter out = response.getWriter();  
          
        //retrieve existing session, hence false parameter is sent
        HttpSession session=request.getSession(false); 
        
        //retrieve the attribute uname, from the session
        String n=(String)session.getAttribute("uname");  
        out.print("Hello "+n);  
  
        //invoke removeAttribute() if you want to remove any attribute
        //stored in the session
        //session.removeAttribute("attribute_name");
        
        //use invalidate method to completely destroy current session
        //so that it doesn't exist any more
        session.invalidate();      
        
        out.close();  
  
                }catch(Exception e){System.out.println(e);}  
    }  
      
  
}  

However, for database backed sessions, may be more useful when a web application is deployed across multiple servers, and client requests are managed by Load Balancer.

You may also like to read:

How to use multiple Servlet Filters
How many implicit java objects are there in JSP
Servlet Life Cycle

Difference between ServletContext and ServletConfig

A Web application can have any number of Servlets. ServletConfig is specific to a single Servlet, where as ServletContext is common to all servlets in a Web application.

Similarities of ServletContext and ServletConfig

1.Both ServletContext and ServletConfig belong to javax.servlet package.
2.Both are required to provide Initialization Parameters to a Web application or Servlet. Initialization parameters need to be provided thru Deployment Descriptor file i..e web.xml
3.Both provide getInitParameter(“parameter-name”) method, to get Initialization parameter.

Difference between ServletContext and ServletConfig

1.Both differ in scope. ServletContext is common to entire Web Application, where as ServletConfig is specific to a servlet.
2.As shown in Servlet Life Cycle ServletConfig is received as parameter to init() method of Servlet Life Cycle. Also, getServletConfig() method can be invoked to get an object of ServletConfig.
3.getServletContext() method can be invoked, to get an object of ServletContext.
4.As shown in below examples, <context-param> element specifies ServletContext initialization parameters. But <init-param> with in <servlet> , specifies ServletConfig initialization parameters.

Why to use Servlet initialization parameters

Instead of hard-coding that parameter in java source code, declaring it in web.xml has the advantage of being able to change it from time to time.

In general the same is true for all settings, for example timeouts, database username, password, database host,etc…

Another advantage of init parameters in web.xml is, all such values are available in a single file, web.xml making maintenance easier.

ServletContext example

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
    <param-name>blogname</param-name>
    <param-value>java652.com</param-value>
</context-param>

    <servlet>
        <servlet-name>NewServlet</servlet-name>
        <servlet-class>NewServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>NewServlet</servlet-name>
        <url-pattern>/NewServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;

public class NewServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            ServletContext sc = getServletContext();
            
            String nam = sc.getInitParameter("blogname");
            PrintWriter pw = response.getWriter();
            
            pw.println("Parameter Value is: "+nam);
    }
}

ServletConfig example

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>NewServlet1</servlet-name>
        <servlet-class>NewServlet1</servlet-class>
        
        <init-param>
        <param-name>myParam</param-name>
        <param-value>xyz</param-value>
        
        </init-param>
        
        <init-param>
        <param-name>myParam1</param-name>
        <param-value>abc</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>NewServlet1</servlet-name>
        <url-pattern>/NewServlet1</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

public class NewServlet1 extends HttpServlet {

	public void init(ServletConfig config)
	{
            System.out.println("Am from Init method...!");
            String param_val = config.getInitParameter("myParam");
            System.out.println("Param Val:"+param_val);

            String param_val1 = config.getInitParameter("myParam1");
            System.out.println("Param Val1:"+param_val1);

            //to get enumeration of parameters
            Enumeration enm = config.getInitParameterNames();
	}
    

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        //another way of getting ServletConfig
        ServletConfig sc = getServletConfig();
    }

}

In Servlet 3.0 version Annotations can also be used in java source code to set init parameters, as shown below

@WebServlet(name = "HelloServlet" , urlPatterns = { "/HelloServlet" }
    , initParams = { @WebInitParam(name = "city" , value = "New Delhi") })

In case the value is fixed forever, and it need not be changed, declaring it in java source code, also can be an option.

You may also like to read:
Java Servlet Life Cycle
How many Filters can be used for a Servlet
How many implicit objects in JSP

Java Servlet and Life Cycle

A Servlet is a Java Program, which runs on any Web Server(Tomcat Server, Glass Fish Server, Web Logic, Web Sphere). Servlet receives request from Web Browser on Client Machine. Below are Life cycle methods for a Servlet.

public void init(ServletConfig config);
This method is invoked when Servlet instance does not exist, and on receiving first request from Web Browser. init() method is not invoked, for each and every request. Constructor of Servlet is executed before init() method.

public void service(ServletRequest request, ServletResponse response);
This method is invoked, whenever a request is received from Web Browser. This method processes, and provides response to the Request. This method further invokes doGet() or doPost() method, based on GET or POST HTTP Request.

public void destroy();
This method is invoked, when Servlet instance gets destroyed, which may occur, when no requests, or when Web Server is shutdown, or garbage collection, to reclaim memory,etc…

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LifeCycle extends HttpServlet
{

	public LifeCycle()
	{
		System.out.println("Am from default constructor");
	}

	public void init(ServletConfig config)
	{
		System.out.println("Am from Init method...!");
	}

        public void doGet(HttpServletRequest req,HttpServletResponse res)
                throws ServletException,IOException
        {
            System.out.println("Am from doGet method...!");
            PrintWriter out = res.getWriter();

            out.println(" from doGet()
"); } public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { System.out.println("Am from doPost method...!"); PrintWriter out = res.getWriter(); out.println(" from doPost()
"); } public void destroy() { System.out.println("Am from Destroy methods"); } } Output(on Server Console, when request is sent to Web Server): INFO: Am from default constructor INFO: Am from Init method...! INFO: Am from doGet method...!

It is required to be aware of Servlet Life Cycle methods, to develop efficient Java Servlets.

You may also like to read:
Purpose of Filter in Servlets
How many implicit objects are in JSP
Program to send HTTP Request to Web Server

Can we have multiple Servlet Filters?

As already briefed in Servlet , a Servlet is a Server Side Java Program, which runs on Web Server or Application Server, and provides HTTP response to the HTTP request received from a Web Browser, such as Filter does Preprocessing and post processing

A Servlet Filter is used to perform pre processing and post processing a request to a servlet.

How Servlet Filter can be used

Below are few scenarios where Filters can be used
1. To decrypt a request(received , and to encrypt response(before sending to client/browser)
2. For profiling purpose, how much time server takes to process a request, and respond.
3. To log client IP address, in a file or to a database table.
4. To block requests from certain range of IP address.

struts2 is dependent on servlet Filter concept, this shows how powerful Servlet Filter concept is.

Filter interface
Methods in Filter interface, which need to be implemented.

Deployment Descriptor web.xml

Multiple filters can be configured

Advantages of Servlet Filter

Filters are dynamically pluggable.
They can be plugged in, plugged out , without any source code changes.
Filter
Plugging and need not go through development cycle, and hence

How to configure Filter in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

    <filter>
    <filter-name>MyFilter

Filter example

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;

public class MyFilter implements Filter{

public void init(FilterConfig arg0) throws ServletException
{
    System.out.println("init() in MyFilter");
}

public void doFilter(ServletRequest req, ServletResponse resp,
    FilterChain chain) throws IOException, ServletException {

    PrintWriter out=resp.getWriter();

   //Do not process request from local host
    if(req.getRemoteAddr().equals("127.0.0.1"))
    {
        out.print("Your IP addr is blocked. Retry later");
        return;
    }

    out.print("<br>myfilter is invoked before");
    chain.doFilter(req, resp);//sends request to next resource

    out.print("<br>myfilter is invoked after");

    System.out.println("doFilter() in MyFilter");
    }

public void destroy() {
    System.out.println("destroy() in MyFilter");
    }
}

servlet code

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

public class NewServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.print("<br>welcome to servlet<br>");
    }
}

struts2 is dependent on servlet Filter concept, this shows how powerful Servlet Filter concept is.

How to configure multiple Filters to a Servlet?

Yes, it is possible to have multiple Filters, which need to be configured in Deployment Descriptor(web.xml). The order in which these filters get invoked is the order in which they are configured in web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

        <filter>
        <filter-name>MyFilter</filter-name>
        <filter-class>MyFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>NewFilter</filter-name>
        <filter-class>NewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>NewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>NewServlet</servlet-name>
        <servlet-class>NewServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>NewServlet</servlet-name>
        <url-pattern>/NewServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Below is an example of Web.xml, which has below two Filters

1. MyFilter.java - Logs Clients IP Address to Server Console, similarly,

Below is source code of NewFilter.java


Below is source code of MyFilter.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;

public class MyFilter implements Filter{

public void init(FilterConfig arg0) throws ServletException
{
    System.out.println("init() in MyFilter");
}

public void doFilter(ServletRequest req, ServletResponse resp,
    FilterChain chain) throws IOException, ServletException {

    PrintWriter out=resp.getWriter();


    if(req.getRemoteAddr().equals("127.0.0.1"))
    {
        out.print("Your IP addr is blocked. Retry later");
        return;
    }

    out.print("
myfilter is invoked before"); chain.doFilter(req, resp);//sends request to next resource out.print("
myfilter is invoked after"); System.out.println("doFilter() in MyFilter"); } public void destroy() { System.out.println("destroy() in MyFilter"); } }

2. NewFilter.java - Just prints log on Web Server Console

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;

public class NewFilter implements Filter{

public void init(FilterConfig arg0) throws ServletException
{
    System.out.println("init() in NewFilter");
}

public void doFilter(ServletRequest req, ServletResponse resp,
    FilterChain chain) throws IOException, ServletException {

    PrintWriter out=resp.getWriter();
    out.print("
filter is invoked before"); chain.doFilter(req, resp);//sends request to next resource out.print("
filter is invoked after"); System.out.println("doFilter() in NewFilter"); } public void destroy() { System.out.println("destroy() in NewFilter"); } }

No Source code changes are required in the servlet.

How to map Filter to a specific URLs or Servlet(s)?

It is possible to map Filters to a specific URLS or Servlet(s). This is possible by adjusting means it Filter gets invoked for all Servlets. By chaging it to below

Filter gets invoked only when urls starting with abc are requested, from Web Browser

    <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

You may also like to read:
What is Servlet Life Cycle?
What are implicit objects in JSP

Jsp implicit objects

In JSP implicit objects are the objects created by implicitly, and can be directly used in Jsp programs with out declaring them. This is basically to reduce the code written by developer.

Below is list of Jsp implicit objects, along with the details

Implicit Object name Instance of class Brief
request javax.servlet.http.HttpServletRequest Used to retrieve all request parameters submitted from HTML page and to retrieve Cookies on Browser.

response

javax.servlet.http.HttpServletRespone used to send response from servlet to HTML Page, add Cookies to Browser, in Request Dispatcher

out

java.io.PrintWriter Used to send output from Servlet to Browser, generally HTML code

session

javax.servlet.http.HttpSession Stores details of current session in progress, using this session attributes can be set and get.

config

javax.servlet.ServletConfig used to retrieve initialization parameters which are specific to each servlet

application

javax.servlet.ServletContext used to retrieve initialization parameters which are common to all servlets

exception

java.lang.Throwable Has details of exception being thrown from a Jsp page.

pageContext

javax.servlet.jsp.PageContext Using this object you can find attribute, get attribute, set attribute and remove attribute at any of levels JSP Page (PAGE_CONTEXT) or HTTP Request (REQUEST_CONTEXT) or HTTP Session (SESSION_CONTEXT) or Application Level ( APPLICATION_CONTEXT)

page

java.lang.Object class and represents the current JSP page. page object provide reference to the generated servlet class. This object is very rarely used.