You are on page 1of 49

EX.

NO: 1
DATE : DISPLAY WELCOME MESSAGE USING SERVLET

Aim:
To display a welcome message using Servlet.

Algorithm:

Step 1: Start the process.

Step 2: Create dynamic web application using eclipse.

Step 3: Choose file-new-other-dynamic web project and name it as helloworldservlet.

Step 4: Create servlet as helloworld.java in com.jit package.

Step 5: Map the servlet and URL.

Step 6: Run the server.

Step 7: Stop the process.


PROGRAM:

package com.jbt;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloWorld
*/
public class HelloWorld extends HttpServlet
{ private static final long serialVersionUID =
1L; /**
* Default constructor.
*/
public HelloWorld() {
}
/*
* This method will handle all GET request.
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("Hello World");
}
/*
* This method will handle all POST request
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException { }
}
package com.jbt;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloWorld
*/
public class HelloWorld extends HttpServlet
{ private static final long serialVersionUID =
1L;

/**
* Default constructor.
*/
public HelloWorld() {
}
/*
* This method will handle all GET request.
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("Hello World");
}
/*
* This method will handle all POST request
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException { } }
web.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/w
eb-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5"> <display-
name>HelloWorldServlet</display-name> <servlet>

<description></description>
<display-name>HelloWorld</display-name>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>com.jbt.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:

RESULT:

Thus the above program is verified.


EX.NO: 2
DATE : PURCHASE ORDER USING SERVLET

Aim:
To design a purchase order form using html and servlet

Algorithm:

Step 1: Start the process


Step 2: Create a HTML file using eclipse.
Step 3: Create a form with fields like Item name, quantity and required button for adding
cookies and listing cookies.
Step 4: Create a servlet file called shoppingcart for displaying the detail entered.
Step 5: Map the servlet and html file
Step 6: Run the server.
Step 7: Stop the process.
PROGRAM:

HTML File: ShoppingCart.html


<h3>Cookie Example through Shopping Cart</h3>
<body>
<form method="get" action="http://localhost:8888/india/SC">
Enter Item Name <input type="text" name="item"><br>
Enter Item Quantity <input type="text" name="qty"><br>
<input type="submit" value="Add Cookie" name="add">
<input type="submit" value="List Cookies" name="list">
</form>
</body>

web.xml entry for ShoppingCart servlet


<servlet>
<servlet-name>snrao1</servlet-name>
<servlet-class>ShoppingCart</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>snrao1</servlet-name>
<url-pattern>/SC</url-pattern>
</servlet-mapping>

Servlet File: ShoppingCart.java


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ShoppingCart extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException, IOException
{
String str1 = req.getParameter("item"); // item name
String str2 = req.getParameter("qty"); // item quantity
String str3 = req.getParameter("add"); // submit button by name add
String str4 = req.getParameter("list"); // submit button by name list
res.setContentType("text/html");
PrintWriter out = res.getWriter()
if(str3 != null)
{
Cookie c1 = new Cookie(str1, str2);
res.addCookie(c1);
res.sendRedirect("ShoppingCart.html");
}
else if(str4 != null)
{
Cookie clientCookies[] = req.getCookies();
for( int i = 0; i < clientCookies.length; i++)
{
out.print("<B>" + clientCookies[i].getName() + " : " + clientCookies[i].getValue() +
"</B><BR>");
}
}
out.close( ) ;
}
}
OUTPUT:

RESULT:

Thus the above program is verified.


EX.NO: 3
DATE : STUDENT MARKSHEET

Aim:
To Develop a program for calculating the percentage of marks of a student using JSP.

Algorithm:

Step 1: Start the process.


Step 2: Create a web application by choosing file-new project-web-web application.
Step 3: Design a form with fields like course, subject, obtained mark and total mark
using HTML
Step 4: Open a JSP and link the JSP variables with HTML fields.
Step 5: Using parseint function change the string value to integer.
Step 6: Using decision statement display the grade and required information
Step 7: Run the program.
Step 8: Stop the process.
PROGRAM:

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<!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>JSP Page test</title>
</head>
<body>
<h2>Student Grading System</h2>
<form action="" method="post">
<table>
<tr>
<td></td>
<td>
Select Course <select name="course">
<option value="select">select</option>
<option value="MCA">MCA</option>
<option value="BCA">BCA</option>
</select>
</td>
</tr>
</table>
<table>
<tr>
<th>Subject</th>
<th>Obtained Marks</th>
<th>Total Marks</th>
</tr>
<tr>
<td align="center">C</td>
<td align="center"><input type="text" size="5" name="c"/></td>
<td align="center">100</td>
</tr>
<tr>
<td align="center">Java</td>
<td align="center"><input type="text" size="5" name="java"/></td>
<td align="center">100</td>
</tr>
<tr>
<td align="center">.Net</td>
<td align="center"><input type="text" size="5" name="net"/></td>
<td align="center">100</td>
</tr>
<tr>
<td align="center">VB</td>
<td align="center"><input type="text" size="5" name="vb"/></td>
<td align="center">100</td>
</tr>
<tr>
<td align="center">DBMS</td>
<td align="center"><input type="text" size="5" name="dbms"/></td>
<td align="center">100</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr><td></td><td align="center"><input type="submit" value="submit"/></td></tr>
</table>
</form>
</body>
</html>
<%
String c = request.getParameter("c");
String j = request.getParameter("java");
String n = request.getParameter("net");
String v = request.getParameter("vb");
String d = request.getParameter("dbms");
if(!(c == null || c.isEmpty()))
{
int cmarks = Integer.parseInt(c);
int jmarks = Integer.parseInt(j);
int nmarks = Integer.parseInt(n);
int vmarks = Integer.parseInt(v);
int dmarks = Integer.parseInt(d);
int total = cmarks+jmarks+nmarks+vmarks+dmarks;
int avg = (total)/5;
int percent = avg;
String grade ="";
if(percent < 40){
grade = "E";
//request.setAttribute("grade", grade);
}
else if(percent >= 40 && percent <=44){
grade = "D";
}
else if(percent >=45 && percent <=49){
grade = "D+";
}
else if(percent >=50 && percent <=54){
grade = "C-";
}
else if(percent >=55 && percent<=59){
grade = "C";
}
else if(percent >=60 && percent <=64){
grade = "C+";
}
else if(percent >=65 && percent<=69){
grade = "B-";
}
else if(percent >=70 && percent <=74){
grade = "B";
}
else if(percent >=75 && percent <=79){
grade = "B+";
}
else if(percent >=80 && percent <=84){
grade = "A";
}
else if (percent >=85 && percent <=100){
grade = "A+";
}
request.setAttribute("Grade", grade);
%>
<table>
<tr>
<td><b>Course</b></td><td></td>
<td align="center"><%=request.getParameter("course") %>
</tr>
<tr>
<td><b>Aggregate Marks</b></td><td></td>
<td align="center"><%=total %></td>
</tr>
<tr>
<td><b>Grade</b></td><td></td>
<td align="center"><%=grade %></td>
</tr>
</table>
<%
}
%>
OUTPUT:

RESULT:

Thus the above program is verified.


EX.NO: 4
DATE : PURCHASE ORDER USING JSP

Aim:
To Design a Purchase Order form using Html form and JSP.

Algorithm:

Step 1: Start the process


Step 2: Create a web application by choosing file-new project-web-web application. Step
3: Design a form with fields like company name, date, payment type, item detail, cost
and quantity
Step 4: Create a separate JSP file by choosing file-new file.
Step 5: Create and link the jsp variable with the HTML variable.
Step 6: Using parseint function change the string value into integer value
Step 7: Run the program
Step 8: Stop the process
PROGRAM:

index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-
8"> <title>JSP Page</title>
</head>
<body bgcolor="pink">
<h1><center>SHREE DEPARTMENTAL STORE</center></h1>
<h1><center>8/38,Gandhi Nagar,Coimbatore</center></h1>
<h2><center>PURCHASE ORDER FORM</center></h2>
<form action="SimpleFormHandler.jsp"
method="get"> <table><tr>
<td>Company Name: <input type="text" name="cname"></td>
<td>Order Date <input type="text" name="odate"></td>
<tr><td>Payment Type:</td></tr>
<tr><td><input type="radio" checked name="payment"
value="cash">Cash</td> <td><input type="radio" name="payment"
value="card">Card</td> <tr> <td>
ITEM DETAILS </td>
<td><select name="itemtype">
<option value="lux">LUX</option>
<option value="hamam">HAMAM</option>
<option value="liril">LIRIL</option>
<option value="dove">DOVE</option>
<option value="himalaya">HIMALAYA</option>
select>
</td></tr>
<tr><td>COST</td><td><input type="text" name="cost"></td></tr>
<tr><td>Quantity</td><td><input type="text" name="qty"></td></tr>
<tr><td><input type="submit" name="submit"
value="order"></td></tr> </table>
</form>
</body>
</html>

SimpleFormHandler.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-
8"> <title>JSP Page</title>
</head>
<body>
<%
int total;
// Grab the variables from the form.
String cn = request.getParameter("cname");
String it = request.getParameter("itemtype");
String c = request.getParameter("cost");
String q = request.getParameter("qty");
%>
<%-- Print out the variables. --%>
<h1>Hello, <%=cn%>!</h1>
<%total=Integer.parseInt(c)*Integer.parseInt(q);
%> Total Cost is <b><%=total%> </b>
<br>Your Order is conformed!!!
</body>
</html>
OUTPUT:

RESULT:

Thus the above program is verified.


EX.NO: 5
DATE : EMPLOYEE PAYSLIP

Aim:
To Prepare a Employee pay slip using JSP

Algorithm:

Step 1: Start the process


Step 2: Create a web application by choosing file-new project-web-web application. Step
3: Design a form with fields like employee name, number , designation, basic pay, total
working day and present day.
Step 4: Create a separate JSP file by choosing file-new file.
Step 5: Create and link the jsp variable with the HTML variable.
Step 6: Using parseint function change the string value into integer value
Step 7: Calculate HRA,DA,TA,NPAY, GROSS PAY using the provided details.
Step 8: Run the program
Step 9: Stop the process
PROGRAM:

Index.jsp

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%--
The taglib directive below imports the JSTL library. If you uncomment it,
you must also add the JSTL library to the project. The Add Library... action
on Libraries node in Projects view can be used to add the JSTL 1.1 library.
--%>
<%--
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
--%>

<!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>Employee Payslip</title>
</head>

<body bgcolor="orange">
<h1><center>GANAPATHY TEXTTILES [P] LTD.</center></h1>

<h2><center>2,Ramanujam Nagar,Coimbatore</center></h2>
<h2><center>Employee Payslip</center></h2>

<form action="pgm5.jsp" method="get">


<table>
<tr>
<td>Employee Name: <input type="text" name="ename"></td>
<td>Employee N# <input type="text" name="eno"></td> </tr>

<tr> <td>
Desigination
<select name="jobtype">
<option value="manager">Manager</option>
<option value="accountant">Accountant</option>
<option value="Labout">Labour</option>

select>
</td></tr>
<tr><td>Basic Pay(per day)<input type="text" name="pay"></td>
<td>Total Working Days<input type="text" name="work"></td>
<td>No. Day Present<input type="text" name="present"></td>
</tr>
<tr><td><input type="submit" name="submit"
value="calculate"></td></tr> </table>
</form>
</body>
</html>
</body>
</html>
Pgm5.jsp

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%--
The taglib directive below imports the JSTL library. If you uncomment it,
you must also add the JSTL library to the project. The Add Library... action
on Libraries node in Projects view can be used to add the JSTL 1.1 library.
--%>
<%--
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
--%>

<!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>Employee Payslip</title>
</head>
<body>

<h1>Employee Payslip</h1>
<%
int total,hra,da,ta,npay,gpay;
String en = request.getParameter("ename");
String et = request.getParameter("eno");
String jt = request.getParameter("jt");
String p = request.getParameter("pay");
String w = request.getParameter("work");
String pr = request.getParameter("present");
%>
EMPLOYEE NAME : <%=en%>
EMPLOYEE CODE : <%=et%>
<table name=t width=60% height=60% border=1> <tr><td>Present
Days</td> <td>:</td><td> <%=pr%></td></tr>
<tr><td>Basic Pay</td><td>:</td> <td><%=p%></td></tr> ><
%total=Integer.parseInt(p)*Integer.parseInt(pr); %> <tr><td>Monthly
Pay</td><td>:</td> <td> <%=total%></td></tr>

<%hra=(total)*5/100; %>
<tr><td>HRA</td><td>:</td> <td> <%=hra%></td></tr>

<%da=(total)*7/100; %>
<tr><td>DA </td><td>:</td> <td> <%=da%></td></tr>

<%ta=(total)*5/100; %>
<tr><td>TA </td><td>:</td> <td> <%=ta%></td></tr>
<%gpay=total+hra+da; %>
<tr><td>Gross Pay </td><td>:</td> <td> <%=gpay%></td></tr>

<%npay=gpay-ta; %>
<tr><td>NET PAY </td><td>:</td> <td> <%=npay%></td></tr></table>
</body>
</html>
OUTPUT:

RESULT:

Thus the above program is verified.


EX.NO: 6
DATE : DATA MANIPULATION

Aim:
To Write a program using JDBC for creating a table, Inserting, Deleting records and list
out the records.

Algorithm:

Step 1: Start the process


Step 2: Create a table I oracle with desired fields.
Step 3: Connect the java and database using JDBC using getconnection attribute.
Step 4: Create a table using create table statement with statement.execute function
Step 5: Insert different values to the database using insert statement
Step 6: Using update statement update the old value to new value.
Step 7: Delete the row in the database using delete statement
Step 8: Display the result
Step 9: Stop the process.
PROGRAM:

To make a table in Oracle


CREATE TABLE emp(id int primary key,name varchar(15),department int,salary int,location
varchar(20))

emp.java

import java.io.*;
public class emp {

private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";


private static final String DATABASE_URL = "jdbc:mysql://localhost/hr";
private static final String USERNAME = "admin"; private static final
String PASSWORD = "secret";

public static void createTable(){


Connection connection = null;
Statement statement = null;
try {
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL,
USERNAME, PASSWORD);
statement = connection.createStatement();
//boolean b=statement.execute("DROP TABLE IF EXISTS emp");
boolean b=statement.execute("CREATE TABLE emp(id int primary key,name
varchar(15),department int,salary int,location varchar(20))");
if(b==true)
System.out.println("Tables created...");
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
System.exit(1);
} catch (ClassNotFoundException clsNotFoundEx)
{ clsNotFoundEx.printStackTrace();
System.exit(1);
} finally {
try {
statement.close();
connection.close();
} catch (Exception e) {
System.exit(1);
}
}
}

public static void createEmployee(int id, String name, int dept, int sal, String loc)
{ Connection connection = null;
PreparedStatement preparedStatement = null;
try {
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL,
USERNAME,PASSWORD);
preparedStatement = connection.prepareStatement("INSERT INTO emp
VALUES(?,?,?,?,?)");
preparedStatement.setInt(1, id);
preparedStatement.setString(2, name);
preparedStatement.setInt(3, dept);
preparedStatement.setInt(4, sal);
preparedStatement.setString(5, loc);
boolean b=preparedStatement.execute();
if(b==true)
System.out.println("1 record inserted...");
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
System.exit(1);
} catch (ClassNotFoundException clsNotFoundEx)
{ clsNotFoundEx.printStackTrace();
System.exit(1);
} finally {
try {
preparedStatement.close();
connection.close();
} catch (Exception e) {
System.exit(1);
}
}
}

public static void updateSalary(int id, int raise)


{ Connection connection = null;
PreparedStatement preparedStatement = null;
try {
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL,
USERNAME,PASSWORD);
preparedStatement = connection.prepareStatement("UPDATE emp SET
salary=salary+? WHERE id=?");
preparedStatement.setInt(1, raise);
preparedStatement.setInt(2, id);
boolean b=preparedStatement.execute();
System.out.println("Employee
updated…”); if(b==true)
System.out.println("$"+raise+" raised for emp id="+id);
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
System.exit(1);
} catch (ClassNotFoundException clsNotFoundEx)
{ clsNotFoundEx.printStackTrace();
System.exit(1);
} finally {
try {
preparedStatement.close();
connection.close();
} catch (Exception e) {
System.exit(1);
} } }

public static void deleteEmployee(int id)


{ Connection connection = null;
PreparedStatement preparedStatement =
null; try {
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL,
USERNAME,PASSWORD);
preparedStatement = connection.prepareStatement("DELETE FROM emp WHERE
id=?");
preparedStatement.setInt(1, id);
boolean b=preparedStatement.execute();
if(b==true)
System.out.println("1 record deleted...");
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
System.exit(1);
} catch (ClassNotFoundException clsNotFoundEx) {
clsNotFoundEx.printStackTrace();
System.exit(1);
} finally {
try {
preparedStatement.close();
connection.close();
} catch (Exception e) {
System.exit(1);
}} }

public static void readEmployee(int id) {


Connection connection = null;
Statement statement = null;
try {
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL,
USERNAME, PASSWORD);
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM emp WHERE
id="+id);
ResultSetMetaData metaData = resultSet.getMetaData();
int noCols = metaData.getColumnCount(); for (int i = 1; i
<= noCols; i++) {
if (i != 3)
System.out.printf("%-10s\t", metaData.getColumnName(i).toUpperCase());
}
System.out.println();
while (resultSet.next()) {
for (int i = 1; i <= noCols; i++) {
if (i != 3)
System.out.printf("%-10s\t", resultSet.getObject(i));
}
System.out.println();
}
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
System.exit(1);
} catch (ClassNotFoundException clsNotFoundEx)
{ clsNotFoundEx.printStackTrace();
System.exit(1);
} finally {
try {
statement.close();
connection.close();
} catch (Exception e) {
System.exit(1);
}}}

public static void main(String[] args) {


//createTable();
createEmployee(1234, "Larson", 123, 1200, "New Jersey");
createEmployee(5678, "Jones", 123, 1100, "New Jersey");
createEmployee(7890, "Kapil", 345, 1600, "Los Angeles");
createEmployee(2341, "Myers", 123, 1800, "New Jersey");
createEmployee(6784, "Bruce", 345, 2200, "Los Angeles");
createEmployee(9636, "Neumann", 123, 3200, "New
Jersey"); updateSalary(1234, 1000);
createEmployee(1111, "Lee", 123, 4400, "New Jersey");
deleteEmployee(1111);
readEmployee(6784);
}
}
OUTPUT:

RESULT:

Thus the above program is verified.


EX.NO: 7
DATE : HANDLE FORM DATA USING SERVLET

Aim:
To create a program using java servlet to handle form data.

Algorithm:

Step 1: Start the process


Step 2: Create a form with the fields username and password, and action as loginservlet.
Step 3: Create a web application using eclipse and name as loginservlet
Step 4: Create and link the variables into html variables.
Step 5: Using the writer.println function display the information entered in the form.
Step 6: Run the program
Step 7: Stop the process.
PROGRAM:

Loginform.html
<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>

Loginservlet
package net.codejava.servlet;
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;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet
{ protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// read form fields
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username: " + username);
System.out.println("password: " + password);
/ do some processing here...
/ get response writer
PrintWriter writer = response.getWriter();
// build HTML code
String htmlRespone = "<html>";
htmlRespone += "<h2>Your username is: " + username + "<br/>";
htmlRespone += "Your password is: " + password + "</h2>";
htmlRespone += "</html>";
/ return response
writer.println(htmlRespone);
}
}
OUTPUT:

RESULT:

Thus the above program is verified.


EX.NO: 8
DATE : TABLE HEADERS USING SERVLET

Aim:
To Write a simple Servlet program to create a table of all the headers it receives along
with their associated values

Algorithm:

Step 1: Start the process


Step 2: Create a web application by choosing file-new project-web-web application.
Step 3: To get a method use request.getmethod()
Step 4: To get a header information request.getheader function is used
Step 5: Use try, catch, throw function to display the information
Step 6: Run the program
Step 7: Stop the process
PROGRAM :

ShowRequestHeaders.java
package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
/** Shows all the request headers sent on the current request. */
public class ShowRequestHeaders extends HttpServlet { public void doGet(HttpServletRequest
request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Servlet Example: Showing Request Headers";
String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n"; out.println(docType + "<HTML>\n" + "<HEAD><TITLE>" + title +
"</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1
ALIGN=\"CENTER\">" + title + "</H1>\n" + "<B>Request Method: </B>" +
request.getMethod() + "<BR>\n" + "<B>Request URI: </B>" + request.getRequestURI() +
"<BR>\n" + "<B>Request Protocol: </B>" + request.getProtocol() + "<BR><BR>\n" +
"<TABLE BORDER=1 ALIGN=\"CENTER\">\n" + "<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Header Name<TH>Header Value");
Enumeration headerNames =
request.getHeaderNames();while(headerNames.hasMoreElements()) { String headerName =
(String)headerNames.nextElement(); out.println("<TR><TD>" + headerName); out.println("
<TD>" + request.getHeader(headerName) );
}
out.println("</TABLE>\n</BODY></HTML>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { doGet(request, response); } }
OUTPUT:

RESULT:

Thus the above program is verified.


EX.NO: 9
DATE : SESSIONS USING JSP

Aim:
To write a program in JSP by using session object

Algorithm:

Step 1: Start the process


Step 2: Create a web application by choosing file-new project-web-web application.
Step 3: Create session.jsp file to get the detail from the user
Step 4: Create output.jsp file to display the entered information by the user
Step 5: Use session.getattribute function to retrieve data from the other jsp file
Step 6: Run the program
Step 7: Stop the process.
PROGRAM:
session.jsp
<html>
<head>
<title>Passing the input value to a session variable</title>
</head>
<body>
<% String
uname=request.getParameter("inputname");
out.print("Welcome "+ uname);
session.setAttribute("sessname",uname); %>
<a href="output.jsp">Check Output Page Here </a>
</body>
</html>

output.jsp

<html>
<head>
<title>Output page: Fetching the value from session</title>
</head>
<body>
<%
String name=(String)session.getAttribute("sessname");
out.print("Hello User: You have entered the name: "+name);
%>
</body>
</html>
OUTPUT:

RESULT:

Thus the above program is verified.


EX.NO: 10
DATE : CLIENT SERVER APPLICATION USING RMI

Aim:
To write a program to build a simple Client Server application using RMI

Algorithm:

Step 1: Start the process.


Step2: Create an interface that specifies the service server is going to provide or
implement

Step 3: Bind the server implementation of the service with the service name

Step 4: Create client

Step 5: Compile all the files using standard javac command.


Step 6: Generate the stubs

Step 7: Copy Client.class, TimeServer.class and TimeServerImpl_Stub.class into the


client side machine.

Step 8: Copy all files except for the Client.class into the server machine.

Step 9: Start the rmiregistry.

Step 10: Run the BindServer.java program using java BindServer


Step 11: Run the Client.java program

Step 12: Stop the process.


PROGRAM:

import java.rmi.*;

public interface TimeatServer extends Remote{

public String showTime() throws RemoteException;

TimeServerImpl.java

import java.rmi.*;

import java.rmi.server.*;

import java.util.Calendar;

import java.util.GregorianCalendar;

public class TimeServerImpl extends UnicastRemoteObject implements

TimeatServer{ public TimeServerImpl() throws Exception {

public String showTime() throws RemoteException

{ Calendar calendar = new GregorianCalendar();

String am_pm;

int hour = calendar.get(Calendar.HOUR);

int minute = calendar.get(Calendar.MINUTE);

int second = calendar.get(Calendar.SECOND);

if(calendar.get(Calendar.AM_PM) == 0)

am_pm = "AM";
else

am_pm = "PM";

return "Current Time : " + hour + ":"

+ minute + ":" + second + " " + am_pm;

Bindserver.java

import java.rmi.*;

import java.rmi.server.*;

import java.util.logging.Level;

import java.util.logging.Logger;

public class BindServer {

public static void main(String[] args) {

try {

TimeServerImpl tsi= new TimeServerImpl();

Naming.bind("time", tsi);

} catch (Exception ex) {

ex.printStackTrace();

}
Client.java

import java.net.MalformedURLException;

import java.rmi.Naming;

import java.rmi.NotBoundException;

import java.rmi.RemoteException;

import java.util.logging.Level;

import java.util.logging.Logger;

public class Client {

public static void main(String[] args) throws NotBoundException

{ try {

String url="rmi://127.0.0.1/time";

TimeatServer ts=(TimeatServer) Naming.lookup(url);

System.out.println(""+ts.showTime());

} catch (MalformedURLException ex)

{ Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);

} catch (RemoteException ex) {

Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);

}
OUTPUT:

Current Time : 4:28:33 PM

RESULT:

Thus the above program is verified.

You might also like