0% found this document useful (0 votes)
18 views6 pages

Servlet

servlet

Uploaded by

anshulrajput338
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views6 pages

Servlet

servlet

Uploaded by

anshulrajput338
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

DHTML

Client-side scripts: JavaScript, VBScript, etc.


Server-side scripts: CGI (Common Gateway Interface), Servlets, ASP (Active Server Pages),
JSP (Java Server Pages), PHP, etc.

Web Servers: Apache, Microsoft IIS, nginx, Google Web Server, LiteSpeed Web Server
Application Servers: Apache Tomcat, WebLogic (Google), WebSphere (IBM), JBoss (RedHat)

Cookies
Cookies are data, stored in small text files, on your computer.
When a web server has sent a web page to a browser, the connection is shut down, and the server
forgets everything about the user.
Cookies were invented to solve the problem "how to remember information about the user":
When a user visits a web page, his name can be stored in a cookie.
Next time the user visits the page, the cookie remembers his name.
A cookie is a name-value pair e.g. “username=msit”.

Session Management
HTTP is a stateless protocol. Each request is independent of the previous one. However, in some
applications, it is necessary to save state information so that information can be collected from
several interactions between a browser and a server. Sessions provide such a mechanism.
Servlets
Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
● Servlets are platform-independent because they are written in Java.
● Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.
● Performance is significantly better.
● Java security manager on the server enforces a set of restrictions to protect the resources
on a server machine. So 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 that you have seen already.

Servlets Architecture

The following diagram shows the position of Servlets in a Web Application.

Servlet Life-Cycle
A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet.
● The servlet is initialized by calling the init() method.
● The servlet calls service() method to process a client's request.
● The servlet is terminated by calling the destroy() method.
● Finally, servlet is garbage collected by the garbage collector of the JVM.

First Servlet
HelloServlet.java

import java.io.*;
import javax.servlet.*;

public class HelloServlet extends GenericServlet


{
public void service (ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
pw.println(“<b>Hello!</b>”);
pw.close();
}
}

ServletRequest object enables the servlet to read data that is provided via the client request.
ServletResponse object enables the servlet to formulate a response for the client.
Anything written to PrintWriter stream is sent to the client as part of the HTTP response.

Handling HTTP GET/POST Requests


color.html
<html><body>
<form name=“Form1” method= “post” action=“ColorServlet”>
<b>Color: </b>
<select name=“color” size=“1”>
<option value=“red”>Red</option>
<option value=“green”>Green</option>
<option value=“blue”>Blue</option>
</select>
<br><br>
<input type=“submit” value=“Submit”>
</form>
<.body></html>

ColorServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorServlet extends HttpServlet
{
public void doPost (HttpServletRequest request, HttpServletResponse response)
throws Servlet Exception, IOException
{
String color = request.getParameter(“color”);
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
pw.println(“<b>The selected color is: </b>”);
pw.println(color);
pw.close();
}
}

// get method is default in html form, but we can also set method=“get” explicitly.
// In Servlets, we need to replace doPost() with doGet() only.

Servlet JDBC
register.html
<html> <body>
<form action="servlet/Register" method="post">
Name:<input type="text" name="userName"/><br/><br/>
Password:<input type="password" name="userPass"/><br/><br/>
Email Id:<input type="text" name="userEmail"/><br/><br/>
Country: <select name="userCountry">
<option>India</option> <option>Pakistan</option> <option>other</option>
</select> <br/><br/>
<input type="submit" value="register"/>
</form> </body> </html>

Register.java
import java.io.*; import java.sql.*;
import javax.servlet.http.*; import javax.servlet.ServletException;

public class Register extends HttpServlet {


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

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

String n=request.getParameter("userName"); String p=request.getParameter("userPass");


String e=request.getParameter("userEmail"); String c=request.getParameter("userCountry");

try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Class.forName("oracle.jdbc.driver.OracleDriver");
//Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection("jdbc:odbc:mydb”);
// Connection con=DriverManager.getConnection("jdbc:mysql://localhost/TEST","root","password");
// DB_URL, USERNAME, PASSWORD

PreparedStatement ps=con.prepareStatement("insert into registeruser values(?,?,?,?)");


ps.setString(1,n); ps.setString(2,p); ps.setString(3,e); ps.setString(4,c);

int i=ps.executeUpdate();
if(i>0) out.print("You are successfully registered...");

}catch (Exception e2) {System.out.println(e2);}

out.close();
}

Cookies in Servlets
// To generate cookie when server interacts with the client for first time.
String data = request.getParameter(“t1”);
Cookie cookie = new Cookie(“MyCookie”,data);
// MyCookie is the name of the cookie, and data is its value.
response.addCookie(cookie);

// To retrieve cookies when server interacts with the client subsequently


Cookie[] cookies = request.getCookies();

Session Management in Servlets

In Servlets, a session can be created via the getSession() method of HttpServletRequest.


HttpSession hs = request.getSession(true);

// Servlet to print current date and date of last access.


import java.io.*; import java.util.*;
import javax.servlet.*; import javax.servlet.http.*;
public class DateServlet extends HttpServlet
{
public void doGet (HttpServletRequest request, HttpServletResponse response) throws
Servlet Exception, IOException
{
HttpSession hs = request.getSession(true);

response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();

Date date = (Date) hs.getAttribute(“date”);


if(date!=null) {pw.print(“Last access: ”+date+“<br>”);}

date = new Date();


hs.setAttribute(“date”, date);
pw.println(“Current date: ” + date);
}
}

You might also like