Servlet Programs

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

Servlet

Servlets are the Java platform technology of choice for extending and
enhancing Web servers. Servlet provides a component based,
platform-independent method for building Web-based applications,
without the performance limitations like CGI programs. And unlike
proprietary server extension mechanisms (Netscape server API or
Apache Modules), servlets are server and platform-independent.
Servlets have access to the entire family of Java APIs, including the
JDBC API to access enterprise databases. Servlets can also access a
library of HTTP-specific calls and receive all the benefits of the mature
Java language, including portability, performance, reusability, and
crash protection.

Today servlets are a popular choice for building interactive Web


applications. Third party servlet containers are available for Apache
Web Server(Tomcat), Microsoft IIS, and others. Servlet containers are
usually a component of Web and Application servers such as
WEBLOGIC Application Server, IBM-WebSphere, Sun Java System
Web Server, Sun Java System Application Server, and others.

PROGRAMS
Program 1: write a program to demonstrate ServletContext object
And ServletConfig object

First.java

package MAINPACK;

/*ServletConfig interface
public String getInitParameter(String name): Returns the value of
given parameter as String, or null if the given parameter doesn’t
exist in web.xml.
public Enumeration getInitParameterNames(): Returns an enumeration of
all the parameter names.
public String getServletName(): Returns the name of the servlet
instance.
public ServletContext getServletContext(): Returns an object of
ServletContext.
*/
/*
ServletContext interface
public String getInitParameter(String name):Returns the parameter
value for the specified parameter name.
public Enumeration getInitParameterNames():Returns the names of the
context's initialization parameters.
public void setAttribute(String name,Object object):sets the given
object in the application scope.
public Object getAttribute(String name):Returns the attribute for the
specified name.
public void removeAttribute(String name):Removes the attribute with
the given name from the servlet context.
*/
import java.io.IOException;
import java.io.*;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class First
*/

public class First extends HttpServlet {


private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public First() {
//ServletContext object created when application SERVLETAPP is
deployed

super();//creates ServletConfig object for First Servlet

/**
* @see HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at:
").append(request.getContextPath());
System.out.println(getServletConfig());
System.out.println(getServletContext());
System.out.println(getServletInfo());
System.out.println(getServletName());

/**
* @see HttpServlet#doPost(HttpServletRequest request,
HttpServletResponse response)
*/

Second.java
package MAINPACK;

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

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class Second
*/

public class Second extends HttpServlet {


private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public Second() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at:
").append(request.getContextPath());
System.out.println(getServletConfig());
System.out.println(getServletContext());
System.out.println(getServletInfo());
System.out.println(getServletName());
RequestDispatcher rd=request.getRequestDispatcher("/fir");
rd.forward(request,response);
}

Program 2: write a program to demonstrate ServletContext object


with context-param And ServletConfig object with init-param

Program 3: Write a program to display simple greeting message


using Servlets

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

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

public class Message extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("hi welcome to Presidency");

}
}
Output:

Program 4: write a program to invoke a servlet using hyper link


1.html
<html>
<body>
<a href=”fir” >click here</a>
</body>
</html>
Program 5: write a program to invoke a servlet using HTML form
using GET method
2.html
<html>
<body>
<form method=”GET” action=”/fir”>
<input type=”submit” value=”Click”>
</form>
</body>
</html>

Program 6: write a program to invoke a servlet using HTML form


using POST method
4.html
<html>
<body>
<form method=”POST” action=”/fir”>
<input type=”submit” value=”Click”>
</form>
</body>
</html>

Program 7: write a program to distinguish GET and POST using


Request header and Request Body
5.html
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>Greeting Message</TITLE>
</HEAD>
<BODY BGCOLOR="red" TEXT="blue">
<FORM METHOD="get" ACTION="Welcome">
<B>Enter Your Name:</B>
<INPUT TYPE="text" NAME="uname"><BR><BR>
<INPUT TYPE="submit" VALUE="Click To Submit">
</FORM>
</BODY>
</HTML>
Program 8: write a program to display greeting message by
accepting name from HTML using servlet.

HTML:

<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>Greeting Message</TITLE>
</HEAD>
<BODY BGCOLOR="red" TEXT="blue">
<FORM METHOD="get" ACTION="Welcome">
<B>Enter Your Name:</B>
<INPUT TYPE="text" NAME="uname"><BR><BR>
<INPUT TYPE="submit" VALUE="Click To Submit">
</FORM>
</BODY>
</HTML>

Servlet:

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

public class Welcome extends HttpServlet


{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter p=res.getWriter();
String name=req.getParameter("uname");
p.println("<html>");
p.println("<body bgcolor=red text=yellow>");
p.println("<font color=yellow size=15>Hello <b>"+name);
p.println("</b>Welcome To Presidency</font><br><br>");
}
}

Output:
Program 9: Demonstrate how the parameters are accepted from
HTML and insert into database through Servlets

HTML:

<!DOCTYPE html>
<html>
<head>
<title>Register form</title>
</head>
<body>
<form method="post" action="register">
Emp id:<input type="text" name="id" /><br/>
Emp Name:<input type="text" name="name" /><br/>
Emp Salary:<input type="text" name="salary" /><br/>
<input type="submit" value="register" />
</form>
</body>
</html>

Servlet:

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

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

public class Registerdb extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

String id = request.getParameter("id");
int empid = Integer.parseInt(id);
String name = request.getParameter("name");
String sal = request.getParameter("salary");
double salary=Double.parseDouble(sal);
try{

//loading drivers for mysql


Class.forName("com.mysql.jdbc.Driver");

//creating connection with the database


Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/test","root","root");

PreparedStatement ps=con.prepareStatement
("insert into employee values(?,?,?)");
ps.setInt(1, empid);
ps.setString(2, name);
ps.setDouble(3,salary);
int i=ps.executeUpdate();

if(i>0)
{
out.println("You are sucessfully registered");
}
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from employee");
out.println("<html><head><title>employee</title></head>");
out.println("<body bgcolor=green><center>");
out.println("<table border=2>");
out.println("<tr><td>empid</td><td>name</td><td>salary</td></tr>");
while(rs.next())
{
out.println("<tr><td>"+rs.getInt(1)+"</td>");
out.println("<td>"+rs.getString(2)+"</td>");
out.println("<td>"+rs.getDouble(3)+"</td></tr>");

}
out.println("</center></table></body></html>");

}
catch(Exception se)
{
se.printStackTrace();
}
//doGet(request, response);
}

MySQL:

 Use test;
 Create table employee(empid int,name varchar(50),salary double);
 Query OK, 0 rows affected (0.37 sec)

Output:
Program 10: Write a Program to set cookies and display
cookies using Servlets

Program:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Cookiedemo extends HttpServlet {

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Cookie c1 = new Cookie("ANDHRA", "HYDERABAD");
Cookie c2 = new Cookie("TAMILNADU", "CHENNAI");
res.addCookie(c1);
res.addCookie(c2);

Cookie c3 = new Cookie("KARNATAKA", "BANGLORE");


Cookie c4 = new Cookie("BIHAR", "PATNA");
c3.setMaxAge(300);
c4.setMaxAge(600);
res.addCookie(c3);
res.addCookie(c4);
System.out.println("SUCCESSFUL IN SETTING COOKIES");
String title = "Active Cookies";
pw.println("<html><head><title>" + title + "</title></head></body>");
pw.println("<table border=\"1\" align=\"center\">");
pw.println("<tr><th>Cookie Name</th><th>Cookie Value</th></tr>");
Cookie ck[] = req.getCookies();
if (ck != null) {
for (int i = 0; i < ck.length; i++) {
pw.println("<tr><td>" + ck[i].getName() + "</td><td>" + ck[i].getValue() +
"</td></tr>");
}
}
else {
System.out.println("NO COOKIES PRESENT");
}
pw.println("</table></body></html>");
}

}Output:
Program 11: Write a program to display Session Information
using Servlets.
Program
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class GetSession extends HttpServlet {

protected void doGet(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {
// TODO Auto-generated method stub
res.setContentType( "text/html" );
PrintWriter pw = res.getWriter();
pw.println( "<HTML><BODY>" );

// get session, and create it if one doesn't already exist


HttpSession theSession = req.getSession();
// get session id and it's max lifetime in seconds
pw.println( "<BR>Session Id: " + theSession.getId() );
pw.println( "<BR>Session Max Inactive Time (seconds): "
+ theSession.getMaxInactiveInterval() );

// get creation time


long dateTimes = theSession.getCreationTime();
pw.println( "<BR>Session Creation Time: " + new
Date( dateTimes ) );

// get last access time, negative if never been accessed


dateTimes = theSession.getLastAccessedTime();
if( dateTimes < 0 ) {
pw.println( "<BR>Session Last Access Time: Never Been Access
Befored" );
}
else {
pw.println( "<BR>Session Last Access Time: " + new
Date( dateTimes ) );
}

pw.println( "</BODY></HTML>" );
res.getWriter().append("Served at: ").append(req.getContextPath());
}
}
Output:

Softwares and Hardwares:


Javax.servlet.jar API
Tomcat 9 Web Server
Eclipse Oxygen
Windows 10
MySQL
RAM minimum 500MB
Hard Disk Minimum 64GB

You might also like