Servlet Single ThreadModel Interface - Following are the required files to this example.
index.html
[html]<a href="servlet1">click here to invoke single threaded servlet</a>[/html]
web.xml
Following is the code structure of life cycle methods.
[xml]<web-app>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>servletsinglethread.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
[/xml]
MyServlet.java
[java]package servletsinglethread;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.SingleThreadModel;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet implements SingleThreadModel{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("Dear users");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
e.printStackTrace();
}
out.print(" welcome to splesson");
out.close();
}
} [/java]
In
doGet(), the parameters are appended to the URL and sent along with the header information. Sets the content type of the response being sent to the client, if the response has not been committed yet. The given content type may include a character encoding specification. The
java.lang.Thread.sleep(long millis) strategy causes the presently executing string to rest for the predefined number of milliseconds, subject to the exactness and precision of framework clocks and schedulers.
The
java.lang.Throwable.printStackTrace() strategy prints this throwable and its backtrace to the standard mistake stream. It prints a stack follow for this Throwable article on the blunder yield stream that is the estimation of the field System.err.
Catch block is meant to give a message to the user when an exception occurs during the execution of a program. There are different styles used by the programmer where each style gives different messages. Programmer can choose one on his needs. Few. styles are using getMessage(), printStackTrace()
Output
When compile the code following link will be displayed, click on that link.
When clicked on the link following message will be displayed.