Explain how to implement single threaded model in servlets.
Implementing single threaded model in servlets
A servlet class is instantiated the first time it is invoked. The same instance will be used over several client requests. This is multi-threaded model, multiple clients that access the same instance. In multi-threaded model one client can change the internal state of the servlet this will affect the other clients, so to protect servlet member’s variables to be modified by different clients, Single threaded model is used. To implement this model SingleThreadModel interface is implemented in servlets. This interface is used to indicate that only a single thread will execute the service( ) method of a servlet at a given time. It defines no constants and declares no methods.If a servlet implements this interface, the server has two options. First, it can create several instances of the servlet. When a client request arrives, it is sent to an available instance of the servlet. Second, it can synchronize access to the servlet.
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SingleThread extends HttpServlet implements SingleThreadModel
{
private int numberOfRows=0;
Connection con=null;
public void init()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver registered with the driver manager class");
Connection con = DriverManager.getConnection("jdbc:odbc:students");
System.out.println("connected");
}
catch(Exception e)
{
System.out.println(e);
}
}
public void doGet(HttpServletRequest r1, HttpServletResponse r2) throws IOException
{
ResultSet rs = null;
PreparedStatement pStmt = null;
int startingRows = numberOfRows;
try
{
String students= null;
pStmt = con.prepareStatement ("select * from stud. students");
rs = pStmt.executeQuery();
}
catch (Exception es)
{
System.out.println(es);
}
}
}