Prepared by Dr. M V S Peri Sastry for use by Students

Note: Please do NOT copy and paste/compile etc., It may NOT work .
Do read, understand and type-in afresh in Eclipse etc., for trouble free working.

1) A) Construct a Servlet program to Display “This is Your First JAVA Servlet Program”

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("<html<head<title>Dr Sastrys Servlet</title</head<body bgcolor=cyan > ");
out.println("<br<h1> This is Your First JAVA Servlet Program</h1<br>");
out.println("</body<html>");
out.flush();
out.close();
}
}
------
save in c:\tomcat7\webapps\FirstServlet/WEB-INF/classes as FirstServlet.java
then in CMD compile it with command below
C:\Program Files (x86)\Java\jdk1.7.0_45\bin>javac -cp C:\tomcat7\lib\servlet-api.jar C:\tomcat7\
webapps\FirstServlet\WEB-INF\classes\FirstServlet.java
C:\Program Files (x86)\Java\jdk1.7.0_45\bin>
------
Then create (copy&modify) web.xml in webapps\WEB-INF parallel to classes
web.xml can be as below:
<web-app>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
</web-app>
------
Then Start Tomcat and
in web browser type http://localhost:8080/FirstServlet/FirstServlet
It works and Displays Welcome to First Servlet
------

1B) Write a program to display current date using JSP.

<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 37.1: clock.jsp -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv = "refresh" content = "60" />
<title>A Simple JSP Example</title>
<style type = "text/css">
.big { font-family: helvetica, arial, sans-serif;
font-weight: bold;
font-size: 2em; }
</style>
</head>
<body>
<p class = "big">Simple JSP Example</p>
<table style = "border: 6px outset;">
<tr
<td style = "background-color: black;">
<p class = "big" style = "color: cyan;">
<!-- JSP expression to insert date/time -->
<%= new java.util.Date() %>
</p>
</td>
</tr
</table>
</body>

2) Construct a WebApp for login with index.html and servlet validate.java with static(fixed) userid
and password. (No database).

----index.html------
html
head
meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"
titleDr Peris WebApp Login jsp and validate jsp Example</title
</head
body
center
b
h3
Dr Peri Sastrys WebApp Login jsp and validate Example
brbrbrbr
</h3
h3
Welcome to Qualia Internet Solutions
form name="a1" action="FirstServlet1" method="post"
br
User ID : input type="text" name="name" value="" />
brbr
Password:
input type="password" name="password" />
brbr
input type="submit" name="submit" value="submit" />
</form
br
</h3
</b
</center
</body
</html
------validate.java servlet------
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class validate extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String nam1=request.getParameter("name");
String pwd1=request.getParameter("password");
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("This is Dr Sastry's JAVA jsp; Welcome " + nam1+ "<br<hr>");
if (pwd1=="") out.println("<font color= red > error: Password NOT given<br</font>");
else out.println("<font color=blue> You typed-in password=" + pwd1);
if (nam1=="") out.println("<font color= red > error: User ID NOT given<br</font>");
if (nam1.equals("perisastry") & pwd1.equals("perisastry"))
out.println("<br> <h1>Welcome "+ nam1+"</h1>");
else out.println("<font color= red <h1>Please Check User ID / Password! </h1<br</font>");
out.flush();
out.close(); } }
------web.xml------
<?xml version="1.0" encoding="UTF-8"?>
<web-app
<display-name>FirstServlet1</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FirstServlet1</servlet-name>
<servlet-class>FirstServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet1</servlet-name>
url-pattern>/FirstServlet1</url-pattern>
</servlet-mapping>
</web-app

3) Construct two JSPs to create and handle session variables.(In JSP1 you use session object’s
method setAttribute and in JSP2 you use getAttribute).

3) Session Example 1

------folder name------sessionexample --it has files—index.html—SaveName.jsp—NextPage.jsp---
------index.html------
<HTML>
<BODY>
<form method=post action="SaveName.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20>
<P<INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
------SaveName.jsp------
<HTML>
<%@ page session = "true" %>
<% request.getSession(); %>
<BODY>
<%
String name = (String) request.getParameter( "username" );
session.setAttribute( "theName", name );
%>
br
<h3>Hello your name is saved in session variable</h3>
br
<A HREF="NextPage.jsp">Click here to display Your Name in Next Screen</A>
</BODY>
</HTML>
------NextPage.jsp------
<HTML>
<%@ page session = "true" %>
<% request.getSession(); %>
<BODY>
<%
String name1=(String) session.getAttribute( "theName" ) ;
%>
Hello,
br
<%= name1 %>
</BODY>
</HTML>

3) Session Example 2

------folder name------stest --it has—files—begin.jsp—s1.jsp—s2.jsp—s3.jsp---logout1.jsp-----
------begin.jsp------
<html>
<title>
Dr Sastry's on_line test
</title>
<body bgcolor = cyan >
<%@ page session = "true" %>
<h2>
center
To Start </h2>
<h2>SESSION TEST&nbsp</h2>
<h2> devised by Dr. Peri Sastry</h2>
br
Click on the Button below
brbr
<% String peri = "peri" ; String peri3;
session = request.getSession(true);
session.setAttribute("userid" , peri);
%>
<form action = "s1.jsp" method = "post" >
<input type = "submit" name = "name1" value = "DrSastry" >
</input>
</form> </center
<% peri3 = (String) session.getAttribute("userid");
out.println("<h3>" + peri3 + " see session there ? </h3>");
%>
br
session variable names now= <%= session.getAttributeNames()%>
</body>
</html>
------s1.jsp------
<html>
<title>
Dr Sastry's on_line test
</title>
<body bgcolor = cyan >
<%@ page session = "true" %>
<h4>
center
To Start </h4>
<h4>session TEST&nbsp; </h4>
<h4> devised by Dr. Peri Sastry</h4>
Click on the Button below
<% String peri = request.getParameter("name1") ;
String peri3;
session = request.getSession(true);
session.setAttribute("userid" , peri);
String val = (String)session.getValue("userid");
String value = val;
session.setAttribute("user",value);
Integer vcount = (Integer)session.getAttribute("counter");
if(vcount==null)
{
vcount = new Integer(1);
session.setAttribute("counter",vcount);
}
else
{
vcount = new Integer(vcount.intValue()+1);
session.setAttribute("counter",vcount);
}
%>
count= <%= vcount %> <br
user= <%= session.getAttribute("user") %>
<form action = "s2.jsp" method = "post" >
<input type = submit value = "click to go to s2" >
</input>
</form> </center
<% peri3 = (String) session.getAttribute("userid");
out.println("<h3>" + peri3 + " see session there ? </h3>");
%>
session? <%= peri3 %>
session variable names now= <%= session.getAttributeNames()%>
</body>
</html>
------s2.jsp------
<html>
<title> Dr Sastry's on_line test </title>
<body bgcolor = yellow >
<%@ page session = "true" %>
<h4>
center
To Start </h4>
<h4>session TEST&nbsp</h4>
<h2> devised by Dr. Peri Sastry</h2>
Click on the Button below
<form action = "s3.jsp" method = "post" >
<input type = submit value = "click to go to s3" >
</input>
</form> </center
<%
Integer vcount = (Integer)session.getAttribute("counter");
vcount = new Integer(vcount.intValue());
%>
user = <%= session.getAttribute("user") %>
count= <%= vcount %> <br
</body>
</html>
------s3.jsp------
<html>
<title>
Dr Sastry's on_line test
</title>
<body bgcolor = "wheat" >
<%@ page session = "true" %>
<h4>
center
To Start </h4>
<h4>session TEST&nbsp</h4>
<h4> devised by Dr. Peri Sastry</h4>
Click on the Button below
<% String peri = "peri" ; String peri3;
session = request.getSession(true);
session.setAttribute("userid" , peri);
String val = (String)session.getValue("userid");
String value = val;
session.setAttribute("user",value);
Integer vcount = (Integer)session.getAttribute("counter");
if(vcount==null)
{
vcount = new Integer(1);
session.setAttribute("counter",vcount);
}
else
{
vcount = new Integer(vcount.intValue()+1);
session.setAttribute("counter",vcount);
}
%>
count= <%= vcount %> <br
user= <%= session.getAttribute("user") %>
<form action = "s1.jsp?name1=SastryGaaru" method = "post" >
<input type = submit value = "click to go to s1" >
</input>
</form> </center
<% peri3 = (String) session.getAttribute("userid");
out.println("<h3>" + peri3 + " see session there ? </h3>");
%>
session? <%= peri3 %>
<% Integer ni = new Integer(10); %>
<% if ( vcount.intValue() > ni.intValue() ) response.sendRedirect("logout1.JSP"); %>
</body>
</html>
------logout1.jsp------
<html>
<title>user is forced to log out</title>
<body bgcolor = "red" >
<h3> <b> <center> *** Warning: You are logged out for count > 10 ***
br
Please consult your Teacher
center</b> </h3>
Breach of Previlege Detected <br
invalidating session <br
<% session.invalidate(); %>
</body>
</html>

4) Construct a program to implement Servlet chaining using RequestDispatcher.

Folder---has files ---Dispatcher1.jsp----second.jsp---and web.xml---in WEB-INF--
------Dispatcher1.jsp------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1"
titleThis JSP dispatches request to second.jsp</title
</head
body
h1
This JSP dispatches request to second.jsp
br
<%!
String sname123="Sastry";
%>
<%
request.getSession();
session.setAttribute( "arg1", sname123);
RequestDispatcher rd1 = request.getRequestDispatcher("second.jsp");
rd1.forward(request, response);
%>
</h1
</body
</html
------second.jsp------
html
head
meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"
titleInsert title here</title
</head
body
h2
I am now in second.jsp
br
<% request.getSession();
%>
<%= new java.util.Date() %>
br
<% String snam1= (String) session.getAttribute("arg1");
out.println( snam1); %>
</h2
</body
</html> ------wewb.xml----in WEB-INF-----
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>RequestDispatcher1</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app

5) A) Write a java program to establish connection with the SQL server Database test.
B) Write a java program to insert a record into the Employee table.

5 A)----establish connection with the SQL server Database testdb1—and list records in Table_1-----
package jdbc4mssql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;
public class jdbc4mssql {
public jdbc4mssql() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String USER = "sa";
String PASS = "Alliance@123";
Connection con = null;
String connectionUrl="jdbc:sqlserver://localhost:1433;databaseName=testdb1;";
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con=DriverManager.getConnection(connectionUrl,"sa","Alliance@123");
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT * FROM Table_1";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
int sid=rs.getInt("id");
String sfn=rs.getString("uname");
String sln=rs.getString("pwd");
System.out.println("ID="+sid + "; Fname="+sfn +"; Lname="+ sln);
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
} } }
------5 B example---------JDBC with MSsql server in CLC4 lab ------
package mssqlserverjdbc1;
import java.sql.*;
public class jdbctest1 {
final static String URL = "jdbc:sqlserver://localhost:1433;databaseName=test";
final static String USER = "sa";
final static String PASS = "sa@123";
static Connection con = null;
static Statement stmt = null;
static Statement stmt2 = null;
static ResultSet rs = null;
public static void main(String[] args) {
try {
// other mysql driver is com.mysql.jdbc.Driver or org.gjt.mm.mysql.Driver
String qry ="INSERT INTO employee Values(9,'Dr.PeriSastryACED-it-testing')";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con= DriverManager.getConnection(URL,USER,PASS);
System.out.println("Connection Established");
stmt = con.createStatement();
stmt.executeUpdate(qry);
System.out.println("Data Inserted");
String SQL1="SELECT * from employee";
stmt2=con.createStatement();
rs=stmt2.executeQuery(SQL1);
while (rs.next()) {
int sid=rs.getInt("id");
String sname=rs.getString("name");
System.out.println("ID="+sid+" Name is " + sname);
}
System.out.println("Data DISPLAYED");
con.close();
}
catch(ClassNotFoundException e) { e.printStackTrace(); }
catch(SQLException e) { e.printStackTrace(); }
finally { System.out.println("connection closed"); } } }

7 B) JDBC Example, simple jsp to do CRUD operations using MySql ------

<%@ page import="java.sql.*"%>
<%
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
//Connection con = DriverManager.getConnection("jdbc:mysql://localhost/db_name","db_login","db_password");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test","root","");
out.println("Database connection was Successful ... retrieving information<brbr>");
%>
<%
/******************
java.sql.Statement st1 = con.createStatement();
String querycreate = "Create table hotel ( category varchar(50), inventoryid varchar(50), company varchar(50), description varchar(50), cost varchar(50) ) " ;
st1.executeUpdate(querycreate);
st1.close();
out.println("Table hotel was successfuly created<brbr>------<brbr>");
************************/
%>
<%
java.sql.Statement st2 = con.createStatement();
String queryinsert = "INSERT INTO hotel VALUES ( 'rooms','SD','Rooms Rates:','Smoking Double','45') " ;
st2.executeUpdate(queryinsert);
st2.close();
out.println("Values in Table hotel were successfuly inserted<brbr>------<brbr>");
%>
<%
out.println("Reading Values from Table hotel <brbr>------<brbr>");
java.sql.Statement st = con.createStatement();
String query = "SELECT * FROM hotels" ;
ResultSet rs;
rs = st.executeQuery("SELECT * FROM hotel");
while(rs.next())
{ for(int i=1;i<=5;i++)
{ out.print("<b<font color=red>" + rs.getString(i) + "</font</b<brbr>"); } }
%>
<%
/********************
java.sql.Statement st3 = con.createStatement();
String querydelete = "DROP table hotel" ;
st3.executeUpdate(querydelete);
st3.close();
out.println("Table hotel is successfuly deleted<brbr>------<brbr>");
*****************/
%>
<%
con.close();
out.println("<brbr> Information is retrieved and Database connection is closed");
%>

8)

Loginappwithservlets 06-09-2016

1)  Start Eclipse
2)  Select JavaEE perspective (click icon JavaEE in right top corner) OR by Window -> Open perspective -> other ->JavaEE
3)  File -> New -> Dynamic Web Project
4)  Type-in ProjectName like loginappwithservlets
Select new runtime ApacheTomcat7 or so (Tomcat Server) and set Configuration as Default for Apache Tomcat
5)  Next à Next à check Generate web.xml deployment descriptor ->Finish
6)  Now your dynamic web project loginappwithservlets appears in Project Explorer
7)  Now expand nodes of the project(click triangle on LHS of project name)
8)  Right Click Java Resources/src New-> servlet (towards end of context menu list 3rd from bottom )
9)  Give package name as loginwithservlets
10) Class Name LoginServlet à next à next à Uncheck doPost (and keep only doGet checked)
11) Finish
12) Right click on Java Resourcesà srcà Right Click on loginwithservlets package and new servlet
13) Repeat steps 8, 9, 10, 11 but give new servlet name as LogoutServlet
14) Right click on WebContent folder à newà HTML file -> (file name change as index.html from NewFile.html ànextà Finish
15) Right click project -> Build Path -> Configure Build Path ->Libraries Tab
Add External jars (second button on RHS)à select servlet-api.jar from c:\Tomcat7\Lib folder
16) Your files all are ready , but you have to do modifications / insertion of code as given below under each file name
17) index.html full code as given below
18) LoginServlet and LogoutServlet, code appearing as bold and italics
19) Right click on index.html and run on Server and test the webapp
20) All the best
------index.html------in WebContent folder------
<!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=ISO-8859-1"
titleDr Peris WebApp Login With Servlets Example</title
</head
body
center
b
h3
Dr Peri Sastrys Login With Servlets Example
brbrbrbr
</h3
h3
Welcome
form name="frm1" action="LoginServlet" method="GET"
br
UserID:
input type="text" name="username" value="" />
brbr
PassWord:
input type="password" name="password" value="" />
brbr
input type="submit" name="submit" value="submit" />
</form
br
</h3
</b
</center
</body
</html
------LoginServlet-— in Java Resources folder------
package loginwithservlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {