JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Request Headers In Servlet

February 8, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

Request Header

Request header is used to pass additional information about the request or itself to the server. Request header can be used by client to pass useful information. getHeaderNames() and getHeader() methods of javax.servlet.http.HttpServletRequest interface can be used to get the header information. Following important request header information which comes from browser side can be frequently used while programming:

  1. Accept: This specifies the certain media types that are acceptable in the response.
  2. Accept-Charset: This indicates the character sets that are acceptable in the response.
  3. Accept-Encoding: This restricts the content-coding values that are acceptable in the response
  4. Accept-Language: This restricts the set of language that are preferred in the response.
  5. Authorization : This type indicates that user agent is attempting to authenticate itself with a server.
  6. From: This type contains internet email address for the user who controls the requesting user agent.
  7. Host: This type indicates internet host and port number of the resource being requested.
  8. If-Modified-Since: This type makes GET method condition. Do not return the requested information if it is not modified since the specified date.
  9. Range: This type request one or more sub-range of the entity, instead of the entire entity.
  10. Referer: This type enables client to specify, for the servers benefit, the address(URL) of the resources from which the Request-URL was obtained.
  11. User-Agent: This type contains information about the user agent originating the request.

Request Header Example

Following example displays the HTTP header information. Here we have used method getHeaderNames() to get the information.

[code lang=”java”]
package javabeat.net.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

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

public class RequestHeaderDemo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException {
doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Headers<hr/>");
Enumeration<String> headerNames = request.getHeaderNames();

while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
out.print("Header Name: <em>" + headerName);
String headerValue = request.getHeader(headerName);
out.print("</em>, Header Value: <em>" + headerValue);
out.println("</em><br/>");
}

}
}
[/code]

Execute the above program in Eclipse. Right mouse click on the class RequestHeaderDemoOutput, select Run > Run As and an output as below would be seen:
servlet_requheader_demo

Previous Tutorial : How To Refresh Servlet  || Next Tutorial : Session Tracking Using Servlet

Filed Under: Java EE Tagged With: Servlets Tutorials

How To Refresh Servlet

February 8, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

We can refresh the server in two ways

  • Through client side
  • and another through server side.

Consider the webpage containing the live score of the match or any live activities we want to see in web page in such cases we have to either refresh the web page or browse to know the current status. Servlet can help to get the solution for this problem. We can make a webpage in such a way that the webpage gets refreshed automatically after a given interval.

Refreshing A Servlet

Easiest way of refreshing the web is we can use the method setIntHeader() of the class javax.servlet.http.HttpServletResponseWrapper.
Syntax of this method is :

[code lang=”java”]
public void setIntHeader(String headerName, int headerValue)
[/code]

For example setIntHeader(“refresh”, “10”) refreshes the web page every 10 second. This method sends back header “Refresh” to the browser along with an integer value. This indicates time interval in seconds.

Example Of Refreshing A Servlet

Listing 1: RefreshServletExample

[code lang=”java”]
package javabeat.net.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

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

public class RefreshServletExample extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/plain");

response.setHeader("Refresh", "3");

PrintWriter out = response.getWriter();

Date d = new Date();

out.println(d.toString());
}
}
[/code]

Web.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<servlet>
<servlet-name>RefreshServletExample</servlet-name>
<servlet-class>javabeat.net.servlets.RefreshServletExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RefreshServletExample</servlet-name>
<url-pattern>/RefreshServletExample</url-pattern>
</servlet-mapping>
</web-app>
[/code]

Execute the RefreshServletExample and you will see that the page gets refershed every 3 second.

Advantages Of Refreshing Servlet

  1. Refreshing servlet may helps to know the current status of the web page For Example live cricket score.
  2. Refreshing servlet help to update the current web server or in the same tab we can change the web page by assigning the url

Previous Tutorial : How To Set PDF File Display In Servlet  || Next Tutorial : Request Headers In Servlet

Filed Under: Java EE Tagged With: Servlets Tutorials

How To Set PDF File Display In Servlet

February 7, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

In this article we will write a simple program which will write content to a PDF file. Example of writing data into PDF using Servlet. Create a Servlet called PDFDemo.

[code lang=”java”]
package javabeat.net.servlets;

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

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

public class PDFDemo extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
PrintWriter out = response.getWriter();
response.setContentType("application/pdf");
String filepath = "/home/jsp.pdf";
response.setHeader("Content-Disposition", "inline; filename=’jsp.pdf’");
FileOutputStream fileout = new FileOutputStream(filepath);
fileout.close();
out.close();
}

}
[/code]

Explanation:

  • Content-Disposition in response header contains inline disposition type and file name attributes.
  • inline is disposition type. If it is marked “inline” then it should be automatically displayed when the message is displayed.
  • filename is name of the file used when creating the file.
  • ContentType is used to display MIME (Multipurpose Internet Mail Extensions) type. MIME type describes contents of various files.
  • PrintWriter object is used to display the result.
  • FileOutputStream is an output stream which is used to write data to file or file descriptor.

Execute the above program, right mouse click on the class PDFDemo and select Run>Run As, a pdf file with the name jsp.pdf would be created at the specified path in our case it is /home/jsp.pdf.

Previous Tutorial : How To Initialize Variables In Servlet?  || Next Tutorial : 

Filed Under: Java EE Tagged With: Servlets Tutorials

How To Initialize Variables In Servlet

February 7, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

While developing web applications (servlets), some data elements are required to process the request at the development phase. For example, in login application we need to enter user name and password. But user name and password are available only at the time of deploying the application. Instead of using database details we can configure the data into servlet by using initialization parameters. Servlet container provides configuration information for servlet in the form of init parameters and context parameters.

Retrieval of Initialization Parameters

The servlet initialization parameters are retrieved by using the ServletConfig object. The following methods provide functionality to retrieve the values of the initialization parameters.

  • public String getInitParameter (String): It returns the string value of initialized parameter or it returns null if requested parameter does not exist in the web.xml file.
  • public Enumeration getInitParameterNames (): It returns names of all initialization parameters as an Enumeration of string objects or returns empty enumeration if no initialization parameters specified in web.xml file.
  • public String getServletName () :It returns name of the servlet.
  • public ServletContext getServletContext(): It is method of ServletContext interface which returns information about the servlet.

We can configure init parameters by using the following tag under <servlet> tag after <servlet-class> tag in the web.xml file:

[java lang=”xml”]
<init-param>
<param-name>parameter name</param-name>
<param-value>parameter value</param-value>
</init-param>
[/java]

Here, <param-name> tag defines name of the attribute and tag defines string value for attribute.

Example

[code lang=”java”]
package javabeat.net.servlets;

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 ServletConfigDemo extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType ("text/html");
PrintWriter out = response.getWriter ();

ServletConfig config= getServletConfig();
String S1 =config. getInitParameter ("r1");
out. print ("r1 value is: " +S1);
out.close ();

}
}
[/code]

Web.xml:

[code lang=”xml”]
<web-app>

<servlet>
<servlet-name>ServletConfigDemo</servlet-name>
<servlet-class>javabeat.net.servlets.ServletConfigDemo</servlet-class>
<init-param>
<param-name>r1</param-name>
<param-value>5</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ServletConfigDemo</servlet-name>
<url-pattern>/ServletConfigDemo</url-pattern>
</servlet-mapping>

</web-app>
[/code]

Execute the above class ServletConfigDemo, following output will be displayed.

[code]
r1 value is: 5
[/code]

Context Initialization Parameters

In some cases we want to configure data that has to be retrieved into all or multiple servlets configured in the web.xml file. We can implement them by using the context initialization parameters provided under servlet specification.
We can configure Servlet context parameter by using <context-param> tag in the web.xml file as shown in the following code:

[code lang=”xml”]
<context-param>
<param-value>parameter name</param-name>
<param-value>parameter value</param-value>
<context-param>
[/code]

Here, <param-name> tag defines name of the attribute and tag defines string value for attribute.

Retrieval of Context Initialization Parameters

The servlet context initialization parameters are retrieved by using the ServletContext object. The following methods provide functionality to retrieve the values of the context initialization parameters.

  • public String getInitParameter (String): It returns the string value of initialized parameter or it returns null if requested parameter does not exist in the web.xml file.
  • public Enumeration getInitParameterNames() : It returns names of all context initialization parameters as an Enumeration of string objects or returns empty enumeration if no initialization parameters specified in web.xml file.
  • public void setAttribute(String name, Object object) : It is used to set the object in the scope such as request, application or session.
  • public object getAttribute(String name) : It is used to return the attribute for the specified string name.
  • public void removeAttribute(String name): It is used to remove the attribute name from the servlet context.

Example

[code lang=”java”]
package javabeat.net.servlets;

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

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

public class ServletContextDemo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
PrintWriter out = response.getWriter();
out.println(getServletContext().getInitParameter("Welcome"));

}
}
[/code]

Web.xml file

[code lang=”xml”]
<web-app>
<servlet>
<servlet-name>ServletContextDemo</servlet-name>
<servlet-class>javabeat.net.servlets.ServletContextDemo</servlet-class>
</servlet>

<context-param>
<param-name>Welcome</param-name>
<param-value>hello world!!!!!!!!!</param-value>
</context-param>

<servlet-mapping>
<servlet-name> ServletContextDemo </servlet-name>
<url-pattern>/ ServletContextDemo </url-pattern>
</servlet-mapping>

</ web-app>
[/code]

Execute the above class ServletContextDemo, following output will be displayed.

[code]
hello world!!!!!!!!!

[/code]

Previous Tutorial : ServletInputStream and ServletOutputStream || Next Tutorial : How To Set PDF File Display In Servlet

Filed Under: Java EE Tagged With: Servlets Tutorials

ServletInputStream and ServletOutputStream

February 6, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

javax.servlet.ServletInputStream and javax.servlet.ServletOutputStream are abstract classes. These classes define several key methods that the other stream classes implement. Two of the most important methods are read( ) and write( ), which are used for reading the client request and writing servlet response to client respectively.

ServletInputStream

The ServletInputStream class extends java.io.InputStream. It is implemented by the servlet container and provides an input stream, that a developer can use to read the data from a client request.

Methods of ServletInputStream

  • readline( ) method is used to read the input values.

ServletOutputStream

ServletOutputStream is an abstract class in the javax.servlet package. It is used in servlets to write the response to the client. ServletOutputStream class extends java.io.OutputStream. It also defines the print( ) and println( ) methods, which output data to the stream.

Methods of ServletOutputStream

Methods Name Description
print(boolean value) Prints boolean value(true/false).
print(string) Prints string values.
print(char) Prints a single character .
print(float) Prints float value( uses 32 bits).
print(double) Prints double value(uses 64 bits).
print(int) This prints an integer type value.
print(long) It prints long value i.e. large value(64 bit).
println(boolean value) Prints boolean value(true/false).
println(string) Prints string values.
println(char) Prints a single character.
println(float) Prints float value( uses 32 bits).
println(double) Prints double value(uses 64 bits) .
println(int) This prints an integer type value.
println(long) It prints long value i.e. large value(64 bit).

Example

Now let use see an example which demonstrates the use of these classes. This class tries to open the image lily.JPG.

[code lang=”java”]
package javabeat.net.servlets;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletIOExample extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
FileInputStream img = new FileInputStream("/home/manisha/Pictures/lily.JPG");

BufferedInputStream bin = new BufferedInputStream(img);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch = 0;
;
while ((ch = bin.read()) != -1) {
bout.write(ch);
}

bin.close();
img.close();
bout.close();
out.close();
}
}
[/code]

Web.xml

[code lang=”xml”]
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<servlet>
<servlet-name>ServletIOExample</servlet-name>
<servlet-class>javabeat.net.ServletIOExample</servlet-class>

</servlet>
<servlet-mapping>
<servlet-name>ServletIOExample</servlet-name>
<url-pattern>/ServletIOExample</url-pattern>
</servlet-mapping>

</web-app>
[/code]

Output:
servlet_io_demo

Previous Tutorial : Difference Between Forward And sendRedirect  || Next Tutorial : How To Initialize Variables In Servlet?

Filed Under: Java EE Tagged With: Servlets Tutorials

Difference Between Forward And sendRedirect In Servlet

February 6, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

First let us list the differences between the forward() and sendRedirect() methods. Then we will see an example for each:

forward() sendRedirect()
The forward() method is executed in the server side. The sendRedirect() method is executed in the client side.
The request is transfer to other resource within same server. The request is transfer to other resource to different server.
It does not depend on the client’s request protocol since the forward ( ) method is provided by the servlet container. The sendRedirect() method is provided under HTTP so it can be used only with HTTP clients.
The request is shared by the target resource. New request is created for the destination resource.
Only one call is consumed in this method. Two request and response calls are consumed.
It can be used within server. It can be used within and outside the server.
We cannot see forwarded message, it is transparent. We can see redirected address, it is not transparent.
The forward() method is faster than sendRedirect() method. The sendRedirect() method is slower because when new request is created old request object is lost.
It is declared in RequestDispatcher interface. It is declared in HttpServletResponse.
Signature :
forward(ServletRequest request, ServletResponse response)
Signature:
void sendRedirect(String url)

Example for sendRedirect () method

[code lang=”java”]
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 RedirectServlet extends HttpServlet {

protected void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();

res.sendRedirect("https://javabeat.net");

out.close();
}

}
[/code]

Example for forward () method

Hello.html

[code lang=”html”]
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="Simple" method="get">
Name: <input type="text" name="uname">
password: <input type="password" name="upass"><br />
<input type="submit" value="Submit" />
</form>

</body>
</html>
[/code]

SimpleServlet(servlet file)

[code lang=”java”]
package javabeat.net.servlets;

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

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

public class SimpleServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("doGet————–start");
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String str = request.getParameter("uname");
String st = request.getParameter("upass");
System.out.println("doGet————–Middle");
if (st.equals("javabeat")) {
RequestDispatcher rd = request.getRequestDispatcher("Welcome");

rd.forward(request, response);

} else {
out.print("Sorry username and password error!");
RequestDispatcher rd = request.getRequestDispatcher("/Hello.html");
rd.include(request, response);
}
System.out.println("doGet————–end");
}

}
[/code]

Welcome (servlet file)

[code lang=”java”]
package javabeat.net.servlets;

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 Welcome extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String str = request.getParameter("uname");
out.print("welcome " + str);
}

}
[/code]

Now execute the Hello.html,right mouse click select Run >Run As and enter “javabeat” and click on submit. A message “Welcome Javabeat” will be displayed on the screen.

Previous Tutorial : Http Status Code  || Next Tutorial : ServletInputStream and ServletOutputStream

Filed Under: Java EE Tagged With: Servlets Tutorials

HTTP Status Codes

February 5, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

Hypertext Transfer Protocol (HTTP) is an application-level protocol for common hypermedia information systems. It is a request/response protocol between clients and servers. It is a generic stateless protocol, used to transfer hypertext.

HTTP Status Codes

Status Codes are used by the client application to know the status of a request processing in the server. The status code has 3 digit numbers, where the first digit defines the class of the response.
The Status code are of 5 categories namely:

  • 1XX – Informational
  • 2XX – Success
  • 3XX – Redirection
  • 4XX – Client Error
  • 5XX – Server Error

Informational Codes

Code Message
100 Continue
101 Switching Protocols

Success Codes

Code Message
200 OK
201 Created
202 Accepted
203 Non-Authoritative Information
204 No Content
205 Reset Content
206 Partial Content

Redirection Codes

Code Message
300 Multiple Choices
301 Moved Permanently
302 Found
303 See Other
304 Not Modified
305 Use Proxy
307 Temporary Redirect

Client Error Codes

Code Message
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Methods Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Time-Out
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Request Entity Too Large
414 Request-URI Too Large
415 Unsupported Media Type
416 Requested range not satisfy able
417 Exceptional Failed

Server Error Codes

Code Message
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Time-Out
505 HTTP Version not supported

Http Status Codes Example

[code lang=”java”]
package javabeat.net.servlets;

import java.io.IOException;

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

public class ErrorcodeExample extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendError(411, "Length Required!!!");
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
[/code]

Execute the above program, an output as below would be seen:

servlet_httpcode_demo

Previous Tutorial : SingleThreadModel in Servlet  || Next Tutorial : Difference Between Forward And sendRedirect

Filed Under: Java EE Tagged With: Servlets Tutorials

SingleThreadModel In Servlet

February 5, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

The SingleThreadModel interface was designed to guarantee that only one thread is executed at a time in a given servlet instance’s service method. It is a marker interface and has no methods.

This interface is currently deprecated, excerpts from the Java Doc:

Deprecated. As of Java Servlet API 2.4, with no direct replacement. It is recommended that a developer take other means to resolve those issues instead of implementing this interface, such as avoiding the usage of an instance variable or synchronizing the block of the code accessing those resources. The SingleThreadModel Interface is deprecated in this version of the specification.

Let us see a simple example using this interface, though it doesn’t guarantee what its specification says.

Example of SingleThreadModel

[code lang=”java”]
package javabeat.net.servlets;

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 SingleThreadModelExample extends HttpServlet implements
SingleThreadModel {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.print("Welcome");

try {
Thread.sleep(2000);
out.print(" to Javabeat");
} catch (Exception e) {

}

out.close();
}
}

[/code]

Web.xml

[code lang=”xml”]
<web-app>

<servlet>
<servlet-name>SingleThreadModelExample</servlet-name>
<servlet-class>javabeat.net.SingleThreadModelExample </servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SingleThreadModelExample</servlet-name>
<url-pattern>/SingleThreadModelExample</url-pattern>
</servlet-mapping>

</web-app>

[/code]

Example Explanation

  • Class SingleThreadModelExample implements the SingleThreadmodel interface. The class SingleThreadModelExample which is a servlet prevents handling Single requests at a single time.
  • Here sleep() is a static method in Thread class, which is used to suspend execution of a thread for some specified milliseconds. Thread. Sleep( 2000 ) will stop the execution of the thread for 2000 millisecond.
  • When another user access the same servlet, the new instance is created instead of using the same instance for multiple threads.

 

Previous Tutorial : MVC Architecture  || Next Tutorial : HTTP Codes

Filed Under: Java EE Tagged With: Servlets Tutorials

MVC Architecture Using Servlet And JSP

February 4, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

Web Architecture Models

Different programmers may design an application in different ways. Designing an application depends on how the programmers recognize the problem and approaches for solving that problem. A development model facilitates the design process by separating the code according to the functions performed by different parts of the application.
Two types of development models are used for web applications.

  • Model-1 architecture
  • Model-2 architecture

Model-1 Architecture

Servlet and JSP are the main technologies to develop the web applications. This model uses JSP to design applications which is responsible for all the activities provided by the application. The following figure shows Model-1 architecture.
model - 1 arch

In Model-1 architecture web applications are developed by combining both business and presentation logic. In this model, JSP pages receive requests which are transferred to data sources by JavaBeans. After the requests are serviced, JSP pages send responses back to client.

Advantages

By using this model it’s easy to develop web application.

Disadvantages

  • This architecture is not suitable for large applications.
  • It increases the complexity of the program so it is difficult to debug the program.
  • It needs more time to develop custom tags in JSP.
  • A single change in one page needs changes in other pages. So it is difficult to maintain.

Model-2 (MVC) Architecture

The Model-2 architecture is based on MVC design model i.e. Model, View and Controller.

Following figure shows Model-2 Architecture.
model-2  arch

As shown in above model Servlet acts as Controller, JSP acts as View and JavaBean acts as Model. In this model, Controller receives requests which are transferred to data sources by View component and Model component. After the requests are serviced, JSP pages i.e. View component send responses back to client. These components can be described as follows:

  • Model: It represents data and business logic of the application that specifies how data is accessed and updated. Model is implemented by using JavaBeans. It has no concerns with the presentation logic.
  • View: It represents presentation logic. A View provides the Graphical User Interface (GUI) for model. It specifies how data should be presented to user in an understandable form. A user can interact with application through View and allows user to alter the data.
  • Controller: It acts as interface between view and model. It receives HTTP request. It controls all the Views associated with a Model. It receives requests from the client and delegates the responsibility for producing the next phase of user interface to view component.

MVC Advantages

  • This model is suitable for large applications.
  • It allows use of reusable software components to design the business logic.
  • It easy to maintain and test.

MVC Disadvantage

If we change the code in controller, we need to recompile the class and redeploy the application.

Previous Tutorial : Difference Between JSP and Servlet  || Next Tutorial : 

Filed Under: Java EE Tagged With: Servlets Tutorials

Difference Between Servlet and JSP

February 4, 2014 by Krishna Srinivasan Leave a Comment

This tutorial post highlights the important difference between JSP and Servlet technologies. Servlet and JSP are the two key Java server side technologies that are building blocks for any of the Java web frameworks. It is important to know the difference between these two technologies. This is one of the fundamental concept that confuses the many beginner Java web developers.

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

The basic difference is that, JSP is for web page and Servlet is for Java components. Servlet is HTML in Java where as JSP is Java in HTML.

  • Java EE Complete Reference
  • A servlet is like any other java class. You put HTML into print statements like you use System.out or how javascript uses document.write.
  • A JSP technically gets converted to a servlet but it looks more like PHP files where you embed the java into HTML.

Servlet Life Cycle

Servlet Life Cycle

JSP Life Cycle

jsp execution life cycle

Difference Between Servlet and JSP

In this article we will list some of the differences between Servlets and JSP.

[table id=5 /]

If you have any questions or personal guidance on learning the Servlet and JSP programming, please send a mail to krishnas at javabeat.net or write it in the comments section.

Previous Tutorial : ServletConfig in Servlet  || Next Tutorial : MVC Architecture Using JSP and Servlet

Filed Under: Java EE Tagged With: Servlets Tutorials

  • « Previous Page
  • 1
  • …
  • 8
  • 9
  • 10
  • 11
  • 12
  • …
  • 21
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved