Advanced Java Programming Notes Unit 2
Advanced Java Programming Notes Unit 2
JavaBeans (thereafter referred to as beans) are reusable software components that are
written in the Java programming language and can be manipulated by using beans-aware
builder tools. Because the beans are reusable, you can use them to construct more
complex components, build new applications, or add functionality to existing applications.
Getter and Setter have important roles in the topic. So, let us check on Getter and
Setter below:
Setter and Getter Methods in Java
Setter and Getter Methods in Java properties are mentioned below:
Properties for setter methods:
1. It should be public in nature.
2. The return type a should be void.
3. The setter method should be prefixed with the set.
4. It should take some argument i.e. it should not be a no-arg method.
Properties for getter methods:
1. It should be public in nature.
2. The return type should not be void i.e. according to our
requirement, return type we have to give the return type.
3. The getter method should be prefixed with get.
4. It should not take any argument.
For Boolean properties getter method name can be prefixed with either “get” or
“is”. But recommended to use “is”.
• JAVA
// Constructor
public Student() {}
// Setter for Id
public void setId(int id) { this.id = id; }
// Getter for Id
public int getId() { return id; }
import java.io.Serializable;
public StudentBean() {
}
Session Bean
The bean sprout business idea that can be systematically used by customer, remote,
and web service. When a client wants to use an application distributed on a server,
then the client uses session bean methods. This session bean provides services to
customers, protecting them from complex problems by performing business
operations within the server.
To get to an application that is conveyed to the worker, the client summons the
meeting bean's strategies. The meeting bean performs work for its client, safeguarding
it from intricacy by executing business errands inside the worker. Remember that
session beans are not persistence.
At the point when the method has finished, the client explicit state should not be held.
However, the client may change the state of instance variable presented in pooled
stateless beans, and this state is held over to the following invocation of the pooled
stateless bean.
Besides this, during the invocation of the method, all instances of a stateless bean are
the same, permitting the EJB container to assign an instance to any client. Therefore,
the state of a stateless session bean should apply across all clients. It can be
implemented in a web-services.
Since they can maintain various customers, stateless session beans can offer better
adaptability for applications that require large numbers of clients. Ordinarily, an
application requires fewer stateless session beans than stateful session beans to
support the same number of clients.
To improve execution, we may choose a stateless session bean in the event that it has
any of these characteristics.
o The state of the bean has no information or data for a particular client.
o In a private method invocation, the bean performs a generic task for all clients.
o The bean implements a web service.
AD
AD
The state is held for the span of the client/bean session. In case if the client eliminates
the bean, the session closes and the state is omitted. This transient nature of the state
isn't an issue, because the interaction between the client and the beans ends. So, it is
not required to hold the state.
Stateful session beans should be used, if any of the following conditions are valid:
o The bean's state denotes the alliance between the bean and a particular client.
o The bean needs to hold data about the customer across method invocations.
o The bean interferes between the customer and different segments of the
application, introducing an improved visible to the client.
o In the background, the bean deals with the workstream of a few enterprise
beans.
Note: Stateless and stateful both session beans are not persistent.
From that pool, any of the session beans may respond to the client. We can implement
it in the web-service endpoints. It takes care of the state but does not hold the state if
unexpected crashes or shutdown occur. It can be used if we want to perform cleanup
tasks on closing the application or shut down as well. It is because it operates
throughout the life cycle of the application.
Singleton session beans are suitable for the following conditions:
Entity Bean
An entity bean is an unpredictable business substance. It models a business substance
or models different activities inside a business interaction. It is used to encourage
business benefits that include data and calculations on that data. It can deal with
various, needy, diligent articles in playing out its essential assignments. A substance
bean is a far-off object that oversees steady information and performs complex
business rationale. It can be extraordinarily distinguished by an essential key.
AD
AD
It is a far-off object that oversees steady information, performs complex business
rationale, possibly utilizes a few ward Java protests, and can be remarkably
distinguished by an essential key. It ordinarily coarse-grained determined items since
they use steady information put away inside a few fine-grained relentless Java objects.
Element beans are diligent on the grounds that they do endure a worker crash or an
organization's disappointment.
Every entity bean has a persistence identity that is associated with it. It means that it
comprises a unique identity that can be fetched if we have a primary key. The type for
the unique key is defined by the bean provider. A client can retrieve the entity bean if
the primary has been misplaced. If the bean is not available, the EJB container first,
instantiates the bean and then re-populates the data for the client.
The diligence for entity bean information is given both to saving state when the bean
is passivated and for improving the state when a failover has detected. It can endure
in light of the fact that the information is put away determinedly by the holder in some
type of information stockpiling framework, like a data set.
Entity beans persist business data by using the following two methods:
AD
AD
It can be used as an alternative to CMP. If the deployment tools are incompatible for
mapping the bean instance's state to the database. The disadvantage of BMP is that
more work is required to define the bean and it ties the bean to a specific database
type and structure.
Container-Managed Persistence
In container-managed persistence, the EJB container transparently and implicitly
handles the relationship between the bean and the database. Bean developers focus
on the data and the business process. The principal constraint is that the EJB
compartment can most likely not produce information base access articulations with
the proficiency of a programmer.
Unlike BMP, CMP does not allow us to write database access calls in the methods of
the entity bean class. It is because the persistence is handled by the container at run-
time. The following two things are required to support the CMP:
Note: Entity bean has been replaced with Java persistence API.
It is quite similar to stateless session bean. Because it does not save informal state, also
used to handle multiple incoming requests. EJB has the following benefits over the
JMS are as follows:
The primary function of MDB is to read (receive) or write (send) incoming from a JMS
destination (i.e. queue or topic). While using MDB ensure that it is configured and
installed properly. It interacts with JMS and the JMS installed on the Oracle database.
The database retains queue or topic. The following figure depicts how MDB interacts
with the JMS destination.
The working of MDB is as follows:
o MDB creates and opens a JMS connection to the database by using the data
source (JMS resource provider). The JDBC driver is used to facilitate the JMS
connection.
o A JMS session over the JMS connection is opened by the MDB.
o If any message for the MDB is routed to the onMessage() method of the MDB
from the queue o topic. Other clients may also access the same queue and topic
to put the message for the MDB.
Note that it does not handle the requests that are requested by the clients instead it
handles requests that are placed into a queue.
Method Description
ejbCreate() This method is used just like the stateless session bean ejbCreate
method. No initialization should be done in this method.
However, any resources that you allocate within this method will
exist for this object.
Primary Key It has no primary key. It is used to It has a primary key that allows us to find
identify and retrieve specific bean instances and can be shared by more
instances. than one client.
Persistence of It persists data only for the span of Persistence beyond the life of a client
Data the conversation with the client. instance. Persistence can be container-
managed or bean-managed.
The following figure shows the life cycle of an entity bean. An entity bean has the
following three states:
• Does not exist. In this state, the bean instance simply does not exist.
• Pooled state . When WebLogic server is first started, several bean instances
are created and placed in the pool. A bean instance in the pooled state is not
tied to particular data, that is, it does not correspond to a record in a database
table. Additional bean instances can be added to the pool as needed, and a
maximum number of instances can be set (for more information, see
the @Entity Annotation).
• Ready state. A bean instance in the ready state is tied to particular data, that
is, it represents an instance of an actual business object.
The various state transitions as well as the methods available during the various
states are discussed below.
Servlet Architecture
•••
Servlets are grouped under the Advanced Java tree that is used to create
dynamic web applications. Servlets are robust, well scalable, and are
primarily used in developing server-side applications. If we go a little back
in time, we would be able to witness that before the introduction of
servlets, CGI (Common Gateway Interface) was used. Among several
indigenous tasks that a servlet is capable of doing, dynamically performing
client requests and responses are most common. Other tasks that a servlet
can do effectively are:
• Can easily manage/control the application flow.
• Suitable to implement business logic.
• Can effectively balance the load on the server side.
• Easily generate dynamic web content.
• Handle HTTP Request and Response
• Also act as an interceptor or filter for a specific group of requests.
Types of Servlet
• Generic Servlets: These are those servlets that provide
functionality for implementing a servlet. It is a generic class from
which all the customizable servlets are derived. It is protocol-
independent and provides support for HTTP, FTP, and SMTP
protocols. The class used is ‘javax.servlet.Servlet’ and it only has
2 methods – init() to initialize & allocate memory to the servlet and
destroy() to deallocate the servlet.
• HTTP Servlets: These are protocol dependent servlets, that
provides support for HTTP request and response. It is typically
used to create web apps. And has two of the most used methods –
doGET() and doPOST() each serving their own purpose.
There are three potential ways in which we can employ to create a servlet:
• Implementing Servlet Interface
• Extending Generic Servlet
• Extending HTTP Servlet
1. Client
The client shown in the architecture above is the web browser and it
primarily works as a medium that sends out HTTP requests over to the web
server and the web server generates a response based on some processing
in the servlet and the client further processes the response.
2. Web Server
Primary job of a web server is to process the requests and responses that a
user sends over time and maintain how a web user would be able to access
the files that has been hosted over the server. The server we are talking
about here is a software which manages access to a centralized resource or
service in a network. There are precisely two types of webservers:
• Static web server
• Dynamic web server
3. Web Container
Web container is another typical component in servlet architecture which is
responsible for communicating with the servlets. Two prime tasks of a web
container are:
• Managing the servlet lifecycle
• URL mapping
Web container sits at the server-side managing and handling all the
requests that are coming in either from the servlets or from some JSP pages
or potentially any other file system.
How does a Servlet Request flow?
Every servlet should override the following 3 methods namely:
1. init(): To initalize/instantiate the servlet container.
2. service(): This method acts like an intermediatory between the
HTTP request and the business logic to serve that particular
request.
3. destroy(): This method is used to deallocate the memory allocated
to the servlet.
These methods are used to process the request from the user.
Following are the steps in which a request flows through a servlet which
can be observed in the architecture diagram:
• The client sends over a request.
• The request is accepted by the web server and forwarded to the
web container.
• In order to obtain the servlet’s address, the web container
traces web.xml file corresponding to the request URL pattern.
• By the time above process takes place, the servlet should have
been instantiated and initialized. The init() method is invoked to
initialize the servlet.
• By passing ServletRequest and Response
object, public service() method is called by the container.
• In the next step, the ServletRequest and ServletResponse objects
are type casted
to HttpServletRequest and HttpServletResponse objects by
the public service() method.
• Now protected service() method is called by the public
service() method.
• The protected service() method dispatches the request to the
correct handler method based on the type of request.
• When servlet container shuts down, it unloads all the servlets and
calls destroy() method for each initialized servlet.
Advantages
• Prime functionality of a servlet is that they are independent of
server configuration, and they are pretty much compatible with any
of the web servers.
• Servlets are also protocol-independent
supporting FTP, HTTP, SMTP, etc. protocols to the fullest.
• Until destroyed manually, servlets can be retained in the memory
helping process several requests over time. Also, once a database
connection is established, it can facilitate process several requests
for a database in the very same database session.
• Servlets inherit Java’s property of portability and hence are
compatible with nearly any web server.
• Servlets are first converted into byte codes and then executed,
which helps in increasing the processing time.
Disadvantages
• Designing a servlet can be pretty laborious.
• Exceptions need to be handled while designing a servlet since they
are not thread safe.
• Developers may need additional skills to program a servlet.
• Servlet class is loaded first when the Web container receives a new request.
• Then the web container creates an instance of the servlet. This instance is created only
once in the whole Servlet Life Cycle.
• The servlet is initialized by the calling init() method.
• service() method is called by the servlet to process the client's request.
• Servlet is destroyed by calling the destroy() method.
• Java Virtual Machine's(JVM) garbage collector clears the destroyed servlet's memory.
Let us see the signature for each of the methods mentioned above:
init()
Whenever a user invokes the URL associated with the particular servlet, the init() method is
called. It is called only once and not each time there is a request. An instance of a servlet is
created through the init() method. Each user request creates a new thread catering
to GET and POST requests.
service()
The web container calls the service() method each time there is a new request to the servlet.
This is done by spawning a new thread. This method checks the HTTP request type, i.e,
whether it is a GET, POST, DELETE, etc, and calls the doGet, doPost, doDelete, etc methods
as per the request.
destroy()
This method is called just once at the end of the Life Cycle of Servlet. It helps perform all the
clean-up activities including closing database connections, halting background threads, etc.
Then it removes the servlet from the container.
The destroy() method is only called once all threads within the servlet's service methods have
exited or after a timeout period.
Program Illustrating Java Servlet Implementation
A program illustrating Java Servlet implementation We can implement a Servlet in the
following ways:
The easiest and most common way is to extend HTTPServlet class. Let us see a Hello
World program of a servlet using this method.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
The HttpServlet class is extensively used to create servlet since it provides methods to handle
HTTP requests like doGet(),doPost, doDelete() etc. The above code is used to display HTML
content on the web page displaying "Hello World".
Its portability comes from the fact that Java is portable. This means that the Java code is
compiled into bytecode. The bytecode is platform-independent. Hence it is Write Once Run
Anywhere(WORA).
2. Efficient
Efficient because it creates a new thread for each request and not each process.
3. Scalable
Since Servlets can handle multiple requests due to multithreading, it is scalable to be quite
responsive. Servlets are also amenable to various load distribution architectures. We can scale
the web applications easily with the right load distribution.
4. Robust
JVM handles all the Servlet programs, including garbage collection and prevention
of memory leaks.
HTTP Request header is used to pass additional information about the client/requestor to the
server. These include extra information, metadata that the server can use.
HTTPServletRequest provides getHeaderNames() and getHeader() methods which can be
used to extract header names and header values, respectively. Let us see some of the common
header names sent:
Accept-Charset: This indicates the acceptable character sets in the response. E.g., ISO-8859-
1
Accept-Encoding: This restricts the content-coding values that are acceptable in the
response.
Accept-Language: This restricts the set of language that is preferred in the response.
Authorization: This type indicates that the user agent is attempting to authenticate itself with
a server.
User-Agent: This type contains the information about the user agent originating the request.
Cookie: From the Email address of the requester. Only used by custom clients, not by
browsers.
Typically, if an HTTP GET request is sent, the parameters are included in the query string in
the URL. Whereas, if it is an HTTP POST request, the parameters are included in the body
part of the HTTP request.
An HTTP Post request can have a lot of data sent to the server in the request body. We can
access all these data using InputStream pointing to the request body.
This will return the raw data from the request which can be separately parsed and used as
necessary.
An object of ServletContext is created by the web container when deployed. This object can
be used to get metadata about the web application which is stored in the web.xml file.
As you can see, you have to first get the session object, to get access to the ServletContext
object.
A session can hold the details about a user between requests, across the application.
An HTTPSession object is used for session management. When a new user accesses the
application for the first time, the HTTPSession object is obtained
through request.getSession().
The user is given a unique ID to identify the session. A particular session is active until a
particular specified timeout value is mentioned in the web.xml file. Let us see the code
snippet to create a session:
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession();
}
session.setAttribute("name", "Scaler");
String userName = (String) session.getAttribute("name");
Headers in response must be set before writing data into it. You can set it as key-value pair in
the following way-
This is a header used to tell the browser, the kind of data being returned. The default for
servlets is text/plain, but text/HTML is usually explicitly specified. This header can be set in
the following way-
response.setHeader("Content-Type", "text/HTML");
Content length is used to tell the browser how many bytes are being sent by the servlet. This
is needed only when the browser is using a persistent HTTP connection.
response.setHeader("Content-Length", "12908");
When we need to direct users to a location other than what is requested, redirection is used.
This can happen when the document is moved pointing to a different location. We can do this
by using the following code in doGet()/doPost() method:
response.sendRedirect("https://www.yoursite.com");
Benefits of Servlets
Easy to implement
It is wasy to implement Servlet using Java APIs. It is also easy to implement sessions and
cookies since dedicated interfaces are provided for each use case.
There was no way to connect to the database directly using CGI. But using Servlets, we can
connect to the database directly and track sessions.
Protocol Independent
Servlets are flexible to follow any web protocol including FTP, HTTP.
Earlier, CGI(Common Gateway Interface) scripts which were used before Servlets and
written in C++ did not have good exception handling, for instance, the application might
crash if there was a divide by 0 error. Servlets, written in Java have much better ways to
handle such exceptions and make sure the application doesn't crash. It has provisions for
redirection and forwarding.
Security
The server-side components inherit the security of the webserver. And the Servlet programs
benefit from Java's Security Manager.
Servlet Interface
1. Servlet Interface
2. Methods of Servlet interface
Servlet interface needs to be implemented for creating any servlet (either directly or
indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to
service the requests, and to destroy the servlet and 2 non-life cycle methods.
Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle method of
servlet and invoked by the web container only
once.
public void destroy() is invoked only once and indicates that servlet is
being destroyed.
File: First.java
1. import java.io.*;
2. import javax.servlet.*;
3.
4. public class First implements Servlet{
5. ServletConfig config=null;
6.
7. public void init(ServletConfig config){
8. this.config=config;
9. System.out.println("servlet is initialized");
10. }
11.
12. public void service(ServletRequest req,ServletResponse res)
13. throws IOException,ServletException{
14.
15. res.setContentType("text/html");
16.
17. PrintWriter out=res.getWriter();
18. out.print("<html><body>");
19. out.print("<b>hello simple servlet</b>");
20. out.print("</body></html>");
21.
22. }
23. public void destroy(){System.out.println("servlet is destroyed");}
24. public ServletConfig getServletConfig(){return config;}
25. public String getServletInfo(){return "copyright 2007-1010";}
26.
27. }
Handling GET requests involves overriding the doGet method. The following
example shows the BookDetailServlet doing this. The methods discussed in
the Requests and Responses section are shown in bold.
The servlet extends the HttpServlet class and overrides the doGet method.
Within the doGet method, the getParameter method gets the servlet's expected
argument.
To respond to the client, the example doGet method uses a Writer from
the HttpServletResponse object to return text data to the client. Before accessing
the writer, the example sets the content-type header. At the end of
the doGet method, after the response has been sent, the Writer is closed.
Handling POST requests involves overriding the doPost method. The following
example shows the ReceiptServlet doing this. Again, the methods discussed in
the Requests and Responses section are shown in bold.
JSP and servlets have greatly enhanced the way in which we can create and manage Web pages.
The difficulty level of coding JSP is between that of coding HTML and pure Java. Servlets are pure
Java. The idea behind having both is providing a way for non-programmers to contribute functionality
through JSP. You can “program” a JSP page almost as easily as you can write an HTML page. For
simple tasks like displaying the current date, you write a normal HTML page and add only a small
amount of Java as a scriptlet. For big tasks like processing a shopping cart, you use JSP as the
mediator between the Web form and a component(s) (bean or servlet) that has all the processing
logic. Most of the code in a Web application will go into servlets. The JSP portion is a just front end to
the application (with little logic of course) that a user can use/navigate comfortably.
We all know that the web (Internet) lives over the Http protocol. The servlet as expected is handle the
http requests. Well, what use would a servlet be if it cannot handle the most commonly used protocol
in the internet.
A lot of things happen when a servlet is invoked because of some user action in a web page. The
sequence of events starts with a browser sending a request to a Web server. The server hands the
request to a Servlet Container. The container loads the servlet (if it isn't already loaded), instantiates a
request and response objects, and then hands these objects to the servlet by calling first its init()
method, then its service() method, and lastly the destroy() method. The service() method will typically
call one of the doXXX() methods such as doGet(). The response based on the output of the doXXX()
methods will be sent back to the browser and will be displayed on screen.
Below is a diagrammatic representation of how data flows from a browser to the servlet and then back
to the browser.
Now that we know how the requests makes its way to the servlet and then comes back to the client,
lets look at a sample Servlet that will actually compile and produce some output on the browser.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
HTTP is stateless that means each request is considered as the new request. It is shown
in the figure given below:
Why use Session Tracking?
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client
requests.
A cookie has a name, a single value, and optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a version number.
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the
browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides
a lot of useful methods for cookies.
Constructor Description
Cookie(String name, String value) constructs a cookie with a specified name and value.
There are given some commonly used methods of the Cookie class.
Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
public String getName() Returns the name of the cookie. The name cannot be changed
after creation.
For adding cookie or getting the value from the cookie, we need some methods provided by other
interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to
add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all
the cookies from the browser.
How to create Cookie?
Let's see the simple code to create cookie.
1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and va
lue of cookie
4. }
FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse respon
se){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. Cookie ck=new Cookie("uname",n);//creating cookie object
18. response.addCookie(ck);//adding cookie in the response
19.
20. //creating submit button
21. out.print("<form action='servlet2'>");
22. out.print("<input type='submit' value='go'>");
23. out.print("</form>");
24.
25. out.close();
26.
27. }catch(Exception e){System.out.println(e);}
28. }
29. }
SecondServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse respons
e){
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. Cookie ck[]=request.getCookies();
14. out.print("Hello "+ck[0].getValue());
15.
16. out.close();
17.
18. }catch(Exception e){System.out.println(e);}
19. }
20.
21.
22. }
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>
download this example (developed using Myeclipse IDE)
download this example (developed using Eclipse IDE)
download this example (developed using Netbeans IDE)
Output
2) Hidden Form Field
1. Hidden Form Field
2. Example of Hidden Form Field
In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the
state of an user.
In such case, we store the information in the hidden field and get it from another
servlet. This approach is better if we have to submit form in all the pages and we don't
want to depend on the browser.
Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.
It is widely used in comment form of a website. In such case, we store page id or page
name in the hidden field so that each page can be uniquely identified.
1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>
FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class FirstServlet extends HttpServlet {
6. public void doGet(HttpServletRequest request, HttpServletResponse response
){
7. try{
8.
9. response.setContentType("text/html");
10. PrintWriter out = response.getWriter();
11.
12. String n=request.getParameter("userName");
13. out.print("Welcome "+n);
14.
15. //creating form that have invisible textfield
16. out.print("<form action='servlet2'>");
17. out.print("<input type='hidden' name='uname' value='"+n+"'>");
18. out.print("<input type='submit' value='go'>");
19. out.print("</form>");
20. out.close();
21.
22. }catch(Exception e){System.out.println(e);}
23. }
24.
25. }
SecondServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class SecondServlet extends HttpServlet {
5. public void doGet(HttpServletRequest request, HttpServletResponse response
)
6. try{
7. response.setContentType("text/html");
8. PrintWriter out = response.getWriter();
9.
10. //Getting the value from the hidden field
11. String n=request.getParameter("uname");
12. out.print("Hello "+n);
13.
14. out.close();
15. }catch(Exception e){System.out.println(e);}
16. }
17. }
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>
3)URL Rewriting
1. URL Rewriting
2. Advantage of URL Rewriting
3. Disadvantage of URL Rewriting
4. Example of URL Rewriting
In URL rewriting, we append a token or identifier to the URL of the next Servlet or the
next resource. We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??
A name and a value is separated using an equal = sign, a parameter name/value pair
is separated from another parameter using the ampersand(&). When the user clicks
the hyperlink, the parameter name/value pairs will be passed to the server. From a
Servlet, we can use getParameter() method to obtain a parameter value.
Advantage of URL Rewriting
index.html
1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>
FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response
){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. //appending the username in the query string
18. out.print("<a href='servlet2?uname="+n+"'>visit</a>");
19.
20. out.close();
21.
22. }catch(Exception e){System.out.println(e);}
23. }
24.
25. }
SecondServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse response
)
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. //getting value from the query string
14. String n=request.getParameter("uname");
15. out.print("Hello "+n);
16.
17. out.close();
18.
19. }catch(Exception e){System.out.println(e);}
20. }
21.
22.
23. }
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>
4) HttpSession interface
1. HttpSession interface
2. How to get the HttpSession object
3. Commonly used methods of HttpSession interface
4. Example of using HttpSession
In such case, container creates a session id for each user.The container uses this id to
identify the particular user.An object of HttpSession can be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.
index.html
1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>
FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response
){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. HttpSession session=request.getSession();
18. session.setAttribute("uname",n);
19.
20. out.print("<a href='servlet2'>visit</a>");
21.
22. out.close();
23.
24. }catch(Exception e){System.out.println(e);}
25. }
26.
27. }
SecondServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse response
)
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. HttpSession session=request.getSession(false);
14. String n=(String)session.getAttribute("uname");
15. out.print("Hello "+n);
16.
17. out.close();
18.
19. }catch(Exception e){System.out.println(e);}
20. }
21.
22.
23. }
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>