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

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

ServletConfig in Servlet

February 1, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

In this article we will see about ServletConfig Interface and how it works. The config object is created by the web container based on the initialization parameters specified in the deployment descriptor. It is used to send information to a servlet during initialization.

Now let see the methods of ServletContext interface, which are listed the following table:

Name Description
String getInitparameter(String Name) It returns the Servlet initialization parameter of the given name and if the requested parameter is not available then it returns null.
Enumeration getInitparameter Names( ) It returns names of all Servlet initialization parameters defined in web.xml file.
String getServletName() Returns the servlet name as defined in the deployment descriptor .
ServletContext getServletContext() Returns the ServletContext object reference.

ServletConfig Example

Let us try out simple example to understand the working of the ServletConfig. Create a class named ServletconfigExample. This class shall create an object of ServletConfig and fetch the init-param from the deployment descriptor and print on the screen.

Listing 1: ServletconfigExample

[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 ServletconfigExample 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("websitename");
out.print("I’m : " + S1 + "website!!!!");

out.close();
}
}
[/code]

Listing 2: 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>ServletconfigExample</servlet-name>
<servlet-class>javabeat.net.servlets.ServletconfigExample</servlet-class>
<init-param>
<param-name>websitename</param-name>
<param-value>Javabeat</param-value>
</init-param>
</servlet>

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

</web-app>
[/code]

Here we have defined the <init-param> which defines a param-name as websitename and param-value as Javabeat.

Now execute the ServletconfigExample, right click select Run>Run As and the following output appears:
ServletConfig

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

Filed Under: Java EE Tagged With: Servlets Tutorials

sendRedirect in Servlet

February 1, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

In this article we shall see how to redirect your current page to some other page. The easiest way to achieve this is by using the sendRedirect() method of class javax.servlet.http.HttpServletResponse.

sendRedirect() method redirects your current page to another servlet or jsp page. This method is used to redirect response to another resource. This method accepts relative as well as absolute URL.
Using sendRedirect() method whenever the client makes any request it goes to the container, then the container decides whether servlet can handle request or not. If it is not handled then that request cab be handled by other servlets.

Some important points on sendRedirect() method:

  • In the sendRedirect method existing request and response objects are lost.
  • sendRedirect methods happens on the client side.
  • In this method request gets transferred to resource outside the application.
  • sendRedirect method works on response object.
  • sendRedirect method is transfer to another resource to different domain.
  • In the sendRedirect method it call old request and response object is list because it is treated as new request.
  • sendRedirect method is slower because extra round trip is required because completely new request is created and old object request is lost.

sendRedirect Example

Now let us try an example as below. In this exmaple the sendRedirect() method would take you to the URL mentioned https://javabeat.net

Listing 1: SendRedirectExample

[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 SendRedirectExample extends HttpServlet {

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

response.sendRedirect("https://javabeat.net");
}
}
[/code]

Listing 2: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>SendRedirectExample</servlet-name>
<servlet-class>javabeat.net.servlets.SendRedirectExample</servlet-class>
</servlet>

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

</web-app>
[/code]

Previous Tutorial : Request Dispatcher in Servlet  || Next Tutorial : ServletConfig in Servlet

Filed Under: Java EE Tagged With: Servlets Tutorials

Request Dispatcher In Servlet

January 31, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

Request Dispatcher

While developing web applications we need to distribute the request processing and response generation to multiple servlet objects. So we need to dispatch requests from one component to another component. This can be done by using RequestDispatcher interface.

RequestDispatcher interface is implemented by servlet container to dispatch or to pass the request to a web resource such as Servlet, HTML page or JSP page.

To dispatch the request from Servlet or JSP to web resource using RequestDispatcher we need to perform following steps:

  • Get a RequestDispatcher object reference
  • Using include () and forward () methods of RequestDispatcher.

Getting a RequestDispatcher object

RequestDispatcher object can be obtained by using following methods.

  • The getRequestDispacther () method of ServletContext.
  • The getNamedDispacther () method of ServletContext.
  • The getRequestDispacther () method of ServletRequest.

The getRequestDispacther () method of ServletContext

This method takes String argument to locate the resource to which request is to be dispatched. When this method is called, the container locates given path. Path should start with the / character. If given path does not start with / character it throws IllegalArgumentException.

The getNamedDispacther () method of ServletContext

This method takes String argument used to locate Servlet to which request is to be dispatched. When this method is called, the container locates the Servlet with given name in the context.

The getRequestDispacther () method of ServletRequest

This method obtains the RequestDispatcher object using path to the current request. The Servlet container builds complete path and locates the resource provided in the getRequestDispacther() method of ServletContext.

Using include () and forward () methods of RequestDispatcher

The include() method: This method includes the response of another Servlet into the calling Servlet. This method can be invoked from calling Servlet while servicing the request. It includes contents of resource such as Servlet, JSP page or HTML page in the response. If we want generate response in the source servlet then we should make use of include () method.

The forward() method: This method is used to forward requests to resource such as Servlet, JSP file or HTML page on the server. This method checks whether servlet has obtained the response and output in the response buffer. If buffer is not committed, the content is cleared. However if the buffer is already committed, it throws IllegalStateException. It implies that after invoking forward () method, the Servlet cannot add any response content.

Request Dispatcher Example

Now let us write an example to see how RequestDispatcher works. First write an HTML file called hello.html. This file will contain a form, to enter some text.

Listing 1:hello.html

[code lang=”html”]
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="Simple" method="get">
Name: <input type="text" name="uname"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
[/code]

Now on submit of the the data, an action Simple.java which is a servlet would be called. In this servlet we are checking if the entered String equals “Javabeat”. If true, then the request is dispatched to another servlet Welcome. Else and error message is displayed and the request dispatcher calls the hello.html again.

Listing 2: Simple.java servlet

[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 Simple 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");
if (str.equals("Javabeat")) {
RequestDispatcher rd = request.getRequestDispatcher("Welcome");
rd.forward(request, response);

} else {
out.print("Sorry username error–redirecting to login page!");
RequestDispatcher rd = request.getRequestDispatcher("hello.html");
rd.include(request, response);
}

}
}
[/code]

Listing 2: Welcome.java servlet

[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 uname = request.getParameter("uname");
out.print("Welcome " + uname);
}
}

[/code]

Now that everything is ready, execute the hello.html. Right mouse click on hello.html select Run > Run As and output would appear as below:
servlet_reqdis_1

Now enter data as “Javabeat” and click on submit button:
servlet_reqdis_2

servlet_reqdis_3

Now enter data as “somename” and click on submit button:

servlet_reqdis_4

servlet_reqdis_5

Previous Tutorial : Servlet Context  || Next Tutorial : sendRedirect in Servlet

Filed Under: Java EE Tagged With: Servlets Tutorials

Servlet Context

January 30, 2014 by Krishna Srinivasan Leave a Comment

  • Java EE Tutorials
  • Servlets Tutorials
  • Servlets Interview Questions

Servlet Context is used to communicate with the servlet container to get the details of web application. It is created at the time of deploying the project. There is only one Servlet Context for entire web application. Servlet Context parameter uses <context-param> tag in web.xml file.

Methods of ServletContext interface:

Name Description
String getInitParameter(String) It returns the Servlet initialization parameter of the given name and if the requested parameter is not available then it returns null.
Enumeration getInitParameterNames() It returns names of all Servlet initialization parameters defined in web.xml file.
void setAttribute(String, Object) Sets an attribute with the current request.
Object getAttribute(string) Returns the value of an attribute located with the given name or returns null value if an attribute with the given name is not found.
Enumeration getAttributeNames() Returns all the attribute names in the current request.
void removeAttribute(String) Removes an attribute identified by the given name from the request.
getRequestDispatcher( ) This method takes a string argument describing the path to located the resource to which the request is to be dispatched..

Servlet Context Example

Following example shows use of ServletContext:

[code lang=”java”]
package javabeat;

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

PrintWriter pw = response.getWriter();
pw.println(getServletContext().getInitParameter(&amp;quot;Welcome&amp;quot;));

}
}
[/code]

Here getInitParameter() is used to initialize the parameter from the web.xml file.

web.xml file:

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

<context-param>
<param-name>Welcome</param-name>
<param-value>Welcome to javabeat!!!!!!!!!</param-value>
</context-param>

<servlet-mapping>
<servlet-name>ServletExample</servlet-name>
<url-pattern>/ServletExample</url-pattern>
</servlet-mapping>
</ web-app>
[/code]

Here <context-param > tag contains two tags namely <param-name> and <param-value> which is used to initialize the attributes of the servlet.

The output of the following program is:
Servlet Context output

Previous Tutorial : Web.xml  || Next Tutorial :  Request Dispatcher

Filed Under: Java EE Tagged With: Servlets Tutorials

  • « Previous Page
  • 1
  • 2
  • 3
  • 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