Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit - Iii Server Side Programming: DR S Sankar

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 76

UNIT – III SERVER SIDE

PROGRAMMING
Dr S Sankar
SERVLETS
Servlets: Java Servlet Architecture
Servlet Life
Cycle- Form GET and POST actions-
Session Handling
Understanding Cookies
Servlets
 What are Servlets?
 Java Servlets are programs that run on a Web or Application server and act
as a middle layer between a web browser and databases
 Servlets work on the server-side.
 Servlets are capable of handling complex requests obtained from web server.
  Servlets offer several advantages
 Servlets are platform-independent because they are written in Java.
 Servlets are trusted.
 The full functionality of the Java class libraries is available to a servlet.
 It can communicate with applets, databases, or other software via the sockets
and RMI mechanisms 
•A client sends a request to a Web Server, through a Web Browser.
•The Web Server searches for the required Servlet and initiates it.
•The Servlet then processes the client request and sends the
response back to the server, which is then forwarded to the client.
Advantages of a Servlet

 Platform-independent since written in Java


 Servlets overcomes the limitations of CGI program.
 Servlet request processing is faster than CGI.
 Servlet technology, in addition to improved
performance, offers security, robust, object orientation
 A servlet handles concurrent requests
Generic servlet vs Http servlet
Generic Http
Protocol Independent Specific to HTTP protocol
It can handle all types of It can handle only http protocol
protocol requests requests
service() method is used to Http methods such as doPost(),
process the request doGet() are used to handle
request
It is available in javax.servlet It is available in
package javax.servlet.http package
What is the difference between Get and Post?
Servlet API or Packages needed for Servlet  

 import javax.servlet.*;
 import javax.servlet.http.*;
Servlet Life Cycle and Its Methods
Servlet Life Cycle
 A servlet life cycle can be defined as the entire
process from its creation till the destruction
 It has three life cycle methods
 init()
 service()
 destroy()
init() method
 The init method is called only once.
 It is called only when the servlet object is created
 It is used for servlet object initializations
 It loads some data into object and are used through out the life cycle.
 Syntax
public void init() throws ServletException
{
// Initialization code...
}
service() Method

 The service() method is used to handle the request which is coming


from client and to write the formatted response back to the client.
 It can be called any number of times
 Syntax
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{
// code to handle request type
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Servlet code
}

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException
{
// Servlet code
}
destroy() method

 The destroy() method is called only once 


 It is called at the end of the servlet

 Used for garbage collection. That is, used to reclaim

the resources occupied by the objects, close the db


connection, halt the background threads and other
cleanup activities
Syntax:
public void destroy()
{
// Finalization code...
}
ServletRequest Methods
Method name Description
getParameter(String name) returns a parameter value
getParameterValues(String name) returns all parameter values as string
object
getParameterNames() returns all parameter names as string
object
getServletContext() returns the servlet context of current
request.
ServletResponse Methods
setContentType(String sets the content type of the
type) response being sent to the
client before sending the
respond
getWriter() returns a PrintWriter object that
can send character text to the
client.
How to handle HTML form data with Java Servlet

<html> LoginForm.html
<body>
<form name="loginForm" method="post" action=“LoginServlet">
Username: <input type="text" name="username"/> <br/>
Password: <input type="password" name="password"/> <br/>
<input type="submit" value="Login" />
</form>
</body>
</html>
How to handle HTML form data with Java Serv
let
import javax.servlet.*; LoginServlet.java
import javax.servlet.http.*;
import java.io.*;
public class LoginServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException
{
resp.setContentType("text\html");
PrintWriter out = req.getWriter();
String un = req.getParameter("username");
String pwd = req.getParameter("password");
String msg = "Your username is: "+ un + "Your password is: "+ pwd;
out.println("<html>");
out.println("<body>");
out.println("<h2>" + msg + "</h2>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
Session Tracking and its techniques
Session Tracking / Handling
 Session simply means amount of time user spends in web application.
 Session Tracking is a way to maintain state (activity) of an user. It is
also known as session management in servlet.
 Http protocol is a stateless  protocol.
 Since Http is stateless protocol, it does not keep the user state
(activity)in between web pages.
 To recognize the user and his activity throughout the application,
session tracking is important.
Session Tracking Techniques

 There are four techniques used in Session tracking:


1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Hidden Form Field
(Also it is lab Exercise 4)
Hidden form field
 In case of Hidden Form Field a hidden (invisible)
textfield is used for maintaining the state of an
user.
 we store the information in the hidden field and get
it from another servlet.
<input type="hidden" name="uname" value=“Vimal">  
Hidden form field
 Advantage of Hidden Form Field
 It will always work whether cookie is disabled or not.
 Disadvantage of Hidden Form Field:
 It is maintained at server side.
 Extra form submission is required on each pages.
 Only text information can be used.
Example of using Hidden Form Field
index.html
<form action="servlet1“ method=“post”>  
Name:<input type="text" name=“username"/><br/>  
<input type="submit" value="go"/>  
</form>  
FirstServlet.java

public class FirstServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
out.print("Welcome "+n);
//creating form that have invisible textfield
out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java

public class SecondServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//Getting the value from the hidden field
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
COOKIES
Cookies:
 A cookie is a small piece of data sent from a website and are
stored on the user's computer by the browser while the user
is browsing. 
 Uses
 Cookies are most commonly used to track user activity.
 When you visit some sites, the server gives you a cookie that
acts as your identification card. Upon each return visit to that
site, your browser passes that cookie back to the server.
How cookie works?
Advantage:
 Used to track user activity
 Cookies are maintained at client side.
Disadvantages:
 Not fully supported by some browsers
 Some browsers limit the amount of data that can be
stored with a cookie
 It will not work if cookie is disabled from the browser
 Storing confidential data like password in cookies is
not recommended
Types of Cookie
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 the application.
Create Cookie
 javax.servlet.http.Cookie class provides the
functionality of using cookies. It provides a lot of
useful methods for cookies.
 Create a cookie
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a
specified name and value.
Methods of Cookie class
Method Description
public void setMaxAge(int expiry) Sets the maximum age of the
cookie in seconds.
public String getName() Returns the name of the cookie.
The name cannot be changed
after creation.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.
How to send Cookies to the Client
 Here are steps for sending cookie to the client:
1. Create a Cookie object.
2. Set the maximum Age.
3. Add the cookie in response header.

1) Create a Cookie object:


Cookie c = new Cookie("userName",“Ram");
2) Set the maximum Age: By using setMaxAge () method we can set the maximum age
for the particular cookie in seconds.
c.setMaxAge(1800);
3) Place the Cookie in HTTP response header:
We can send the cookie to the client browser through response.addCookie() method.
response.addCookie(c);
How to read cookies?
Cookie c[] = request.getCookies();
//c.length gives the cookie count

for(int i=0;i<c.length;i++)
{
out.print("Name: "+c[i].getName()+" and Value: "+c[i].getValue());
}
Login.html
<html>
<body>
<form action=“createcookie" method="post">
Username:<input type="text" name="username"/><br/>
Password:<input type="text" name="password" /></br>
<input type="submit" value=“login"/>
</form>
</body>
</html>
Enter username: jai and password: 1234
Click on login button.
public class CreateCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException
{
resp.setContentType("text\html");
PrintWriter out = resp.getWriter();

String un = req.getParameter("username");
String pd = req.getParameter("password");

// Create cookie objects


Cookie cookie1 = new Cookie(“username“,un);
Cookie cookie2 = new Cookie(“password“,pd);

//add cookie in response


resp.addCookie(cookie1);
resp.addCookie(cookie2);

out.println("<html><body>");
out.println(“<p> Cookies are created. Click on the below button to get
cookies<“/p>”);
out.println("<form method='post' action='GetCookieServlet'>");
out.println("<input type='submit' value=‘Get Cookie' />");
out.println("</form></body></html>");
out.close();
}
}
public class GetCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletExpcetion, IOException
{
resp.setContentType("text\html");
PrintWriter out = resp.getWriter();
out.println(“<html><body><p>”);

Cookie cookies[] = req.getCookies();

for(Cookie cookie : cookies)


{
out.println("Cookie name:" + cookie.getName());
out.println("Cookie value:" + cookie.getValue());
}
out.println(“</p></body></html>”);
out.close();
}
}
Database connectivity
Step 1: Creation of Database and Table in
MySQL

mysql> create database mydb;

mysql> use mydb;

mysql> create table student(id int(10), name varchar(20))


Step 2: Creation of required Web-page
<html>
<body>
<form action="InsertData" method="post">
ID: <input type="text" name="id"/> </br>
Name: <input type="text" name="name"/> </br>
<input type="submit" value="Submit" />
</form>
</body>
Step 3: Creation of Java Servlet program with
JDBC Connection
 To create a JDBC Connection steps are
1. Import all the packages
2. Register the JDBC Driver
3. Open a connection
4. Create query
5. Execute the query
6. Retrieve the result
7. Close the connection
// Import packages
import java.sql.*;
//Register the driver
Class.forName("com.mysql.jdbc.Driver");  
//Get the connection
Connection con=DriverManager.getConnection(  
"jdbc:mysql://localhost/dbname",“un",“pwd");  
//Create query
String query = “SELECT * FROM emp”;
//Execute the query
Statement stmt=con.createStatement();  
ResultSet rs=stmt.executeQuery(query);  
//Retrieve the result
while(rs.next()) {
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));
}
// Close the connection
con.close();  
public class InsertData extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = repsonse.getWriter();

String id = request.getParameter("id");
String name = request.getParameter("name");

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "", "");

String query = "INSERT INTO student VALUES(" + id +",'"+name+"')";

Statement st = con.createStatement();
st.executeUpdate(query);

out.println(“<html><body>Sucessfully inserted…</body></html>”);

con.close();
out.close();
}
}
JSP
 Java Server Pages
 Why JSP?
 To separate presentation and business logic
 Supports dynamic content.
 JSP are extended version of Servlet.
JSP vs Servlet
JSP Life Cycle
JSP Elements
 JSP Scripting tags
 JSP Directive tags
 JSP Action tags
JSP Scripting tag
JSP Directives tag
JSP Action tags
JSP program to work with Database
1. Create db and table
2. Create HTML file
3. Create JSP file
 Import necessary packages
 Register DB driver
 Establish connection
 Create Query
 Execute Query
 Process the result
 Close the connection
Step 1: Creation of Database and Table in
MySQL

mysql> create database mydb;

mysql> use mydb;

mysql> create table student(id int(10), name varchar(20))


Step 2: Creation of required Web-page
3. Create JSP file
Install And Configure Apache Tomcat7 Server
Install And Configure Apache Tomcat7 Server In
Windows
 Step 1 Download and Install Tomcat
 Go to http://tomcat.apache.org/download-70.cgi then go to the Binary Distribution/Core/ and
download the "zip" package
 Now unzip the downloaded file into a directory 
 Step 2: Check the installed directory to ensure it contains the following sub-directories:
 bin folder
 logs folder
 webapps folder
 work folder
 temp folder
 conf folder
 lib folder
 Step 3: Now, we need to create an Environment Variable
JAVA_HOME.
 To create the JAVA_HOME environment variable in Windows
XP/Vista/7 we need to push the "Start" button then select "Control
Panel" / "System" / "Advanced system settings".  Then switch to the
"Advanced" tab and select "Environment Variables" / "System
Variables" then select "New" (or "Edit" for modification). In "Variable
Name", enter "JAVA_HOME". In "Variable Value", enter your JDK
installed directory
 For ensuring that it is set correctly, we need to start a command
shell (to refresh the environment) and issue:
set JAVA_HOME
JAVA_HOME=c:\Program Files\Java\jdk1.7.0
 Step 4: Configure Tomcat Server
 The configuration files of the Apache Tomcat Server are
located in the "conf" sub-directory of our Tomcat installed
directory
 There are 4 configuration XML files:
 context.xml file
 tomcat-users.xml file
 server.xml file
 web.xml file
 Step 4(a) "conf\web.xml"; Enabling a Directory
Listing
 Open the configuration file "web.xml". We shall enable
the directory listing by changing "listings" from "false"
to "true" for the "default" servlet.
<param-value>true</param-value> like:
Step 4(b) "conf\server.xml file"; set the TCP Port
Number
 Open the file "server.xml" in a text editor.
  The default port number of Tomcat is 8080. Now we need to change the TCP
port number for Tomcat, since the same port number can be used by other servers
like SQL Server. We may choose any number between 1024 and 65535.
 Locate the following lines, and change port="8080" to port="9999“, like:
<Connector port="9999" protocol="HTTP/1.1" >
Step 4(c) "conf\context.xml"; Enabling
Automatic Reload
 In that we set reloadable="true" to the <Context>
element to enable automatic reload after code changes.

<Context reloadable="true” >


......
</Context> Like
Step 4(d) (Optional) "conf\tomcat-users.xml"
 It is used to manage Tomcat by adding the
highlighted lines, inside the <tomcat-users>
elements.
  In that we can add a password and username as an
optional step.
 Step 5: Now, start the tomcat server
 Launch a command shell. Set the current directory to
"<TOMCAT_HOME>\bin" like E:\myserver\tomcat7.0.40\bin, and run
"startup.bat" as follows:

After that a new Tomcat console window appears


 Step 6: Access the Server
 Open a browser then enter the URL
"http://localhost:9999" to access the Tomcat server's
welcome page.
  If we get this type of page then it means we are done.
 Step 7: Shutdown the server
 We can stop the server using one of the
following:
1. Press ctrl-c on the Tomcat console; or
2. Run "<TOMCAT_HOME>\bin\shutdown.bat"
script
Index.html
<html>
<body>
<form method="post" action=“FirstServlet">
Username: <input type="text" name="t1"/></br>
<input type="submit" value="submit"/>
</form>
</body>
</html>
public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException
{

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

String un = request.getParameter("t1");

ServletContext ctx = getServletContext();


RequestDispatcher rd = ctx.getRequestDispatcher("/SecondServlet");

// Set the value as request to secondservlet


request.setAttribute("Username",un);

// Send the request and response to secondservlet from firstservlet


rd.forward(request, response);
}
}
public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException


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

// Get the value from request object


String username = (String)request.getAttribute("Username");

// Create response object


out.println("<html><body>");
out.println(username);
out.println("</body></html>");
out.close();

}
}

You might also like