AJ Practical File

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

VAISH COLLEGE OF ENGINEERING, ROHTAK

Department of Computer Science & Engineering


B.Tech

Advanced Java
Practical File

Submitted by - Submitted to –
Ms. Urvashi
Asst. Prof. (CSE)
Sr. Experiment Name Date Signature
No
1 Write a program for JDBC connection.
2 Write a program to implement JSP.
3 Write a program to insert data into table using JSP
4 Write a Program to Show Validation of User Using
Servlet
5 Write a Program of calling one servlet by another
servlet.
6 Write a Program to design simple Login page using
Struts.
7 Write a Program to implement Struts.
8 Write a Program to implement Hibernation
9 Develop a Hibernate application to store Feedback of
Website Visitor in mysql Database.

10 Write a Program to implement all the CRUD


operations of database using jdbc java.
11 Create a simple Calculator Application using Servlet.
12 Create a registration servlet in Java using JDBC.
Accept the details such as Username, Password,
Email, and Country from the user using HTML
Form and store the registration details in the
database.

13 Design a JDBC application using Servlet/JSP to


demonstrate the concept of ResultSetMetaData.
14 Develop a simple JSP application to display values
obtained from the use of intrinsic objects[Implicit
Objects] of various types.

15 Develop a simple JSP application to pass values from


one page to another with validations. (Name-txt, age-
txt, hobbies-checkbox, email-txt, genderradio button)

PROGRAM NO: 1
Aim : JDBC Connection Demo.java

Import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet; import
java.sql.SQLException;
import java.sql.Statement;

public class JDBC_Connection_Demo


{
/* static block is executed when a class is loaded into memory
* this block loads MySQL's JDBC driver
*/
static {
try
{
// loads com.mysql.jdbc.Driver into memory
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException cnf)
{
System.out.println("Driver could not be loaded: " + cnf);
}
}

public static void main(String[] args)


{
String connectionUrl = "jdbc:mysql://localhost:3306/EXPDB";
String dbUser = "root";
String dbPwd = "mysql";
Connection conn;
ResultSet rs;
String queryString = "SELECT ID, NAME FROM EXPTABLE";
try
{
conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
Statement stmt = conn.createStatement();

// INSERT A RECORD
stmt.executeUpdate("INSERT INTO EXPTABLE (NAME) VALUES (\"TINU K\")");

// SELECT ALL RECORDS FROM EXPTABLE


rs = stmt.executeQuery(queryString);

System.out.println("ID \tNAME");
System.out.println("============"); while(rs.next())
{
System.out.print(rs.getInt("id") + ".\t" + rs.getString("name"));
System.out.println();
}
if (conn != null)
{
conn.close();
conn = null;
}
}
catch (SQLException sqle)
{
System.out.println("SQL Exception thrown: " + sqle);
}
}
} //JDBC_Connection_Demo ends here

OUTPUT:
------
ID NAME
============
1. ANUSHKA K
2. GARVITA K
3. TINU

PROGRAM NO: 2

Aim : Write a Program To Implement JSP


Step 1) Create a folder in Tomcat’s webapps folder, say examples.
Step 2) Write the following program and save like an html file, with extension jsp, say
“time.jsp” in the above created folder
<html>
<head>
<title> Current TIme
</title>
</head>
<body>
<table align='center' >
<tr>
<td>
<b>Current Date and Time</b>
</td>
<td>
<%=new java.util.Date()%>
</td>
</tr>
</table>
</body>
</html>

Step 3) Start the Tomcat Service Runner in “C:\Program Files\Apache Software Foundation\Tomcat
6.0\bin”

Step 4) Open the web browser and type the following URL to run the servlet from any client system:

http://localhost:8080/examples/time.jsp

or

http:// <IP address of server>


/examples/time.jsp

and press enter.


OUTPUT:
PROGRAM NO: 3

AIM : Program To Insert Data Into Table Using JSP

import java.sql.*; import java.awt.*;


import java.awt.event.*; class
TestDB1
{
public static void main(String ss[])
{ try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection("jdbc:odbc:mydsn","system","mca6");
String t1="China"; int
t2=422;
Statement s=c.createStatement();
s.executeUpdate("lNSERT lNTO emp " + "VALUES
('chinaaaaaaa',200000001)"); ResultSet result1=s.executeQuery("SELECT *
FROM emp"); while(result1.next())
{
System.out.println("name : "+result1.getString(1));
System.out.println("salary : "+result1.getString(2));
}
System.out.println("after insertion");

} catch(SQLExceptione)
{
e.printStackTrace();
} catch(Exceptioni)
{
System.out.println(i);
}
}
}
OUTPUT:

PROGRAM NO: 4

AIM : Program To Show Validation Of User Using Servlet

RequestServlet.java
import
javax.servlet.http.*;
import javax.servlet.*;
import java.io.*; import
java.sql.*;
public class RequestServlet extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse
res)throws ServletException,lOException {
res.setContentType("textƒhtml"); PrintWriter
out=res.getWriter();
out.println("<html><body>");
String name=req.getParameter("name");
String pass=req.getParameter("pass");
if(name.equals("ABCDE")&& pass.equals("123456"))
out.println("user is valid through service method");
else out.println("user is invalid through service method");
out.println("<ƒbody><ƒhtml>"); }

public void doPost(HttpServletRequest req, HttpServletResponse


res)throws ServletException,lOException {
res.setContentType("textƒhtml"); PrintWriter
out=res.getWriter();
out.println("<html><body>");
String name=req.getParameter("name");
String pass=req.getParameter("pass");
if(name.equals("ABCDE")&& pass.equals("123456"))
out.println("user is valid through get method");
else out.println("user is invalid through get mathod");
out.println("<ƒbody><ƒhtml>");

} public void doGet(HttpServletRequest req, HttpServletResponse res)throws


ServletException,lOException {
res.setContentType("textƒhtml"); PrintWriter out=res.getWriter();
out.println("<html><body>");
String name=req.getParameter("name"); String
pass=req.getParameter("pass");
if(name.equals("ABCDE")&& pass.equals("123456")) out.println("user is valid through
get method");
else out.println("user is invalid through get mathod");
out.println("<ƒbody><ƒhtml>"); }
}

Login.html
<html>
<body>
<form action="run3" method="get"> enter your name:
<input type="text" name="name"ƒ>
<br> enter your password:
<input type="password" name="pass"ƒ>
<br>
<input type="submit"ƒ>
<ƒbody>
<ƒhtml>

Web.xml
<web−app>
<servlet>
<servlet−name>RequestServlet<ƒservlet−name>
<servlet−class>RequestServlet<ƒservlet−class>
<ƒservlet>
<servlet−mapping>
<servlet−name>RequestServlet<ƒservlet−name>
<url−pattern>ƒrun3<ƒurl−pattern>
<ƒservlet−mapping>
<ƒweb−app>
OUTPUT :
PROGRAM NO: 5

AIM : Program Of Calling One Servlet By Another Servlet

RequestDispatcher2.java

import javax.servlet.http.*;
import javax.servlet.*; import
java.io.*;
public class RequestDispatcher2 extends HttpServlet
{ public void doGet(HttpServletRequest req, HttpServletResponse res)throws
ServletException,lOException {
res.setContentType("textƒhtml");
PrintWriter out=res.getWriter();
out.println("<html><body>"); String
s="before dispatcher";
out.println(s);
try
{

RequestDispatcher rd=req.getRequestDispatcher("ƒrun2");
rd.include(req,res);

}
catch(Exception e)
{ out.println("exception");
}
out.println("after dispatcher");
out.println("<ƒbody><ƒhtml>"); }
}
DemoServlet2.java

import javax.servlet.http.*;
import javax.servlet.*; import
java.io.*;
public class DemoServlet2 extends GenericServlet
{ public void service(ServletRequest req, ServletResponse res)throws
ServletException,lOException {
res.setContentType("textƒhtml"); PrintWriter
out=res.getWriter();
out.println("<html><body>");
out.println("hello servlet with GenericServlet");
out.println("<ƒbody><ƒhtml>"); }
}

Web.xml

<web−app>
<servlet>
<servlet−name>RequestDispatcher2<ƒservlet−name>
<servlet−class>RequestDispatcher2<ƒservlet−class>
<ƒservlet>
<servlet−mapping>
<servlet−name>RequestDispatcher2<ƒservlet−name>
<url−pattern>ƒrun7<ƒurl−pattern>
<ƒservlet−mapping>
<servlet>
<servlet−name>DemoServlet2<ƒservlet−name>
<servlet−class>DemoServlet2<ƒservlet−class>
<ƒservlet>
<servlet−mapping>
<servlet−name>DemoServlet2<ƒservlet−name>
<url−pattern>ƒrun2<ƒurl−pattern>
<ƒservlet−mapping>
<ƒweb−app>

OUTPUT:
PROGRAM NO: 6
AIM: Program to design simple Login page using Struts.

Login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>Login</title>
</head>
<body>
<div align="center">
<h2>Login Form</h2>
<s:form action="doLogin" method="post">
<s:textfield name="user.email" label="E-mail" />
<s:password name="user.password" label="Password" />
<s:submit value="Login" />
</s:form>
</div>
</body>
</html>

User.java

package net.codejava.struts;

public class User { private


String email;
private String password;

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public String getPassword() { return


password;
}

public void setPassword(String password) {


this.password = password;
}
}

LoginAction.java

package net.codejava.struts;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionSupport;

@Action(
value = "login", results = {
@Result(name = "success", location = "/WEB-INF/jsp/Login.jsp")
}
)
public class LoginAction extends ActionSupport {
// empty
}

DoLoginAction.java

package net.codejava.struts;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionSupport;

@Action(
value = "doLogin", results = {
@Result(name = "input", location = "/WEB-INF/jsp/Login.jsp"),
@Result(name = "success", location = "/WEB-INF/jsp/Welcome.jsp")
}
)
public class DoLoginAction extends ActionSupport {
private User user;

public String execute() {


if ("nimda".equals(user.getPassword()))
{ return SUCCESS;
} else { return
INPUT;
}
}

public User getUser() { return


user;
}
public void setUser(User user) {
this.user = user;
}

Welcome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" 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>Welcome Home</title>
</head>
<body>
<div align="center">
<h1>Welcome Home!</h1>
</div>
</body>
</html>

OUTPUT:
PROGRAM NO: 7
AIM: Write a Program to implement Struts.

input.jsp

<%@taglibprefix="s"uri="/struts-tags"%>
<%@pagelanguage="java"contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<met ahttp-equiv="Content-Type"content="text/html; charset=ISO-8859-1">
<title>Struts2 beginner example application</title>
</head>
<body>
<center>
<h2>Calculate sum of two numbers</h2>
<s:form action="calculateSumAction"method="post">
<s:textfield name="x"size="10"label="Enter X"/>
<s:textfield name="y"size="10"label="Enter Y"/>
<s:submit value="Calculate"/>
</s:form>
</center>
</body>
</html>

Struts action class

Package net.codejava.struts;

Import com.opensymphony.xwork2.ActionSupport;

Public class SumAction extends ActionSupport {


Private int x;
Private int y;
Private int sum;

Public String calculate() {


sum = x + y;
return SUCCESS;
}

// setters and getters for x, y, and sum:

Public int getX() {


Return x;
}

Public void setX(intx) {


this.x = x;
}

Public int getY() {


Return y;
}

Public void setY(inty) {


this.y = y;
}

Public int getSum() {


Return sum;
}

Public void setSum(intsum) {


this.sum = sum;
}
}

Result.jsp

<%@taglibprefix="s"uri="/struts-tags"%>
<%@pagelanguage="java"contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPEhtmlPUBLIC"-//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">
<title>Sum Result</title>
</head>
<body>
Sum of <s:property value="x"/>
and <s:property value="y"/> is:
<s:property value="sum"/>
</body>
</html>
PROGRAM NO: 8

AIM: Write a Program to implement Hibernation.

package com.mycompany;

import java.io.Serializable; import


org.hibernate.Session; import
org.hibernate.SessionFactory; import
org.hibernate.cfg.Configuration; import
org.hibernate.service.ServiceRegistry; import
org.hibernate.service.ServiceRegistryBuilder;

public class ContactManager { public


static void main(String[] args) {
// loads configuration and creates a session factory
Configuration configuration = new Configuration().configure();
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistryserviceRegistry = registry.buildServiceRegistry();
SessionFactorysessionFactory = configuration.buildSessionFactory(serviceRegistry);

// opens a new session from the session factory


Session session = sessionFactory.openSession();
session.beginTransaction(); // persists two new
Contact objects
Contact contact1 = new Contact("Nam", "hainatuatgmail.com", "Vietnam", "0904277091");
session.persist(contact1);
Contact contact2 = new Contact("Bill", "billatgmail.com", "USA", "18001900");
Serializable id = session.save(contact2);
System.out.println("created id: " + id);

// loads a new object from database


Contact contact3 = (Contact) session.get(Contact.class, new Integer(1));
if (contact3 == null) {
System.out.println("There is no Contact object with id=1");
} else {
System.out.println("Contact3's name: " + contact3.getName());
}
// loads an object which is assumed exists
Contact contact4 = (Contact) session.load(Contact.class, new Integer(4));
System.out.println("Contact4's name: " + contact4.getName());

// updates a loaded instance of a Contact object


Contact contact5 = (Contact) session.load(Contact.class, new Integer(5));
contact5.setEmail("info1atcompany.com");
contact5.setTelephone("1234567890"); session.update(contact5);
// updates a detached instance of a Contact object
Contact contact6 = new Contact(3, "Jobs", "jobsatapplet.com", "Cupertino", "0123456789");
session.update(contact6);

// deletes an object
Contact contact7 = new Contact();
contact7.setId(7); session.delete(contact7);
// deletes a loaded instance of an object
Contact contact8 = (Contact) session.load(Contact.class, new Integer(8));
session.delete(contact8);

// commits the transaction and closes the session


session.getTransaction().commit(); session.close();

}
}

OUTPUT:
PROGRAM NO: 9
AIM : Develop a Hibernate application to store Feedback of Website Visitor in MySQL
Database.

create
database
feedback
db; create
table
GuestBook(
vno int PRIMARY KEY AUTO_INCREMENT,
vname varchar(5 0), msg varchar(1 00), mdate
varchar(5 0) )

GuestBookBean.java package
mypack; import
javax.persistence.*;
@Entity
@Table(name="gues tbook") public class
GuestBookBean implements
java.io.Serializable { @Id
@GeneratedValue
@Column(name="
vno") private Integer
visitorNo;
@Column(name="
vname") private String
visitorName;
@Column(name="
msg") private
String msg;
@Column(name="
mdate") private String
msgDate; public
GuestBookBean() {
}
public Integer getVisitorNo() { return
visitorNo; } public String getVisitorName()
{ return
visitorName; } public String getMsg() { return msg; }
public String getMsgDate() { return msgDate; }
public void setVisitorNo(Integer vn) { visitorNo = vn ; }
public void setVisitorName(String vn) {
visitorName =
vn; } public void setMsg(String m) { msg = m;
}
public void setMsgDate(String md) { msgDate=md; }
}
Source packages →new → others→select category Hibernate →Hibernate

Configuration
Wizard
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/feedbackdb?zeroDateTimeBeha
vior=co nvertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>

<mapping class="mypack.GuestBookBean" />


</session-factory> </hibernate-configuration>

--------------------------------
index.html---------------------------------------------------
<h1>Website Feedback Form for google.con </h1>
<form action="fb.jsp" >

Enter Your Name: <input type="text" name="name" ><br>


Enter Your Message : <textarea rows="10" cols="50" name="message" ></textarea><br> <input
type="submit" value="Submit My FeedBack " >
</form>
-------------------------------- fb.jsp---------------------------------------------------
<%@page import="org.hibernate.*, org.hibernate.cfg.*, mypack.*" %>
<%! SessionFactory sf;
org.hibernate.Session hibSession;
%>
<%
sf = new
Configuration().configure().buildSessionFactory();
hibSession = sf.openSession(); Transaction
tx = null;
GuestBookBean gb = new GuestBookBean();
try{
tx = hibSession.beginTransaction(); String
username =
request.getParameter("name"); String usermsg =
request.getParameter("message"); String nowtime =
""+new java.util.Date(); gb.setVisitorName(username);
gb.setMsg(usermsg); gb.setMsgDate(no wtime);
hibSession.save(g b); tx.commit(); out.println("Thank You
for your valuable feedback. ...... ");
}catch(Exception
e){out.println(e);}
hibSession.close();
%>
PROGRAM NO: 10

AIMn: Write a Program to implement all the CRUD operations of database


using jdbc java.

package MyJdbc;

import java.sql.*;
import java.util.ArrayList; import java.util.Scanner;

public class MyJdbc {


static final String USER = "root"; static final String PASS = "12345678";

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


"jdbc:mysql://localhost/"; Connection conn = null;
Statement stmt = null; MyJdbc(){
// Connection conn = null; //
Statement stmt = null; try{
//STEP 2: Register JDBC driver
// Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to database..."); conn =
DriverManager.getConnection(DB_URL, USER, PASS);

//STEP 4: Execute a query System.out.println("Creating database..."); stmt = conn.createStatement();

String sql = "CREATE DATABASE IF NOT EXISTS User ";


stmt.executeUpdate("Use User"); createTable(); System.out.println("Database
created successfully...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace(); }catch(E
xception e){ //Handle errors for
Class.forName
e.printStackTrace();
}finally{} }
void createTable() throws SQLException {

stmt.executeUpdate("CREATE TABLE IF NOT EXISTS USERSTABLE(" + "NAME


varchar(20)," + "CONTACT varchar(20)," + "ADDRESS varchar(20)," +
"UNIVERSITY_NAME varchar(20)" + ")");
}

void insertIntoTable(UserDetails x) throws SQLException { stmt.executeUpdate("Insert into


userstable values(" +
"'"+x.name +"','"+ x.contactno+"','"+
x.address+"','"+ x.universityName+"'"+
")");
}
ArrayList<UserDetails> read() throws SQLException { ArrayList<UserDetails>m=new
ArrayList<UserDetails>(); ResultSet r= stmt.executeQuery("Select * from Userstable");
while(r.next()){
m.add(new UserDetails(r.getString("name"), r.getString("address"), r.getString("university_name"),
r.getString("contact"))); } return m; }
void delete(String contact_no) throws SQLException { stmt.executeUpdate("Delete from userstable
where contact= '"+contact_no+"'"); System.out.println("\nDeleted Successfully.");
}
void update() throws SQLException { Scanner s=new Scanner(System.in); System.out.println("Enter
your new details"); System.out.print("Name : ");
String nn=s.nextLine(); System.out.print("Address : ");
String na=s.nextLine(); System.out.print("University Name : ");
String nu=s.nextLine(); System.out.print("Contact no. : "); String nno=s.nextLine();
stmt.executeUpdate("Update userstable set " +
"name="+nn+",address="+na+",university_name="+nu+",contact=" + nno+"
where contact="+nno);
} } class Main{ public static void main(String[] args) throws SQLException { MyJdbcdb=new
MyJdbc(); System.out.println("1. To Insert into the Database"); System.out.println("2. To read from
the Database"); System.out.println("3. To update from the Database"); System.out.println("4. To
delete into the Database"); System.out.print("Enter your choice : "); Scanner s=new
Scanner(System.in);

int c=s.nextInt(); switch(c)


{ case 1: String n,a,cn,u;
System.out.println("Enter your Details. ");s.nextLine(); System.out.print(" Name : ");

n=s.nextLine(); System.out.print(" Contact no : "); cn=s.nextLine();


System.out.print(" Address : "); a=s.nextLine(); System.out.print("
Univeresity Name : ");

u=s.nextLine();
UserDetails user=new UserDetails(n,a,u,cn); db.insertIntoTable(user);

break; case 2:
System.out.println("Name " +
" Contact no " + "Address " + "University Name");
ArrayList<UserDetails>arr=db.read();
if(arr.isEmpty()) System.out.println("Nothing to show."); else for
(UserDetailsur:arr
){
System.out.println(ur.name+" " + ur.contactno+" " + ur.address+" " +
ur.universityName+" ");

} break; case
3 : db.update();
break; case 4 :
System.out.print("Enter contact no. : "); s.nextLine();
String no=s.nextLine(); db.delete(no); break; default:
System.out.println("Thank you");
} }}
INSERTION

READ

UPDATING
BEFORE UDATING:

AFTER UPDATING

DELETING

AFTER DELETING
PROGRAM NO. 11

Aim : Create a simple Calculator Application using Servlet.

<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
</head>
<body>
<form action="Calculator"
method="GET">
Enter number1:
<input type="text"
name="n1"/><br><br>
Enter number2:
<input type="text" name="n2"/><br><br>
Operator
<select name="op">
<option value="Addition">Addition</option>
<option value="Subtraction">Subtraction</option>
<option value="multiplication">multiplication</option>
<option value="division">division</option>
</select>
<input type="submit" value="calculate" />
</form>
</body>
</html>
Calculator.java file
import java.io.*; import javax.servlet.*; import
javax.servlet.http.*; public class Calculator extends
HttpServlet { public void doGet(HttpServletRequest
request, HttpServletResponse response) throws
ServletException, IOException
{ response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n1 = request.getParameter("n1");
String n2 = request.getParameter("n2");
String op =
request.getParameter("op");
switch (op) { case
"Addition":
out.println("Answer = "+(Integer.parseInt(n1)
+ Integer.parseInt(n2))); break; case
"Subtraction":
out.println("Answer = "+(Integer.parseInt(n1)
- Integer.parseInt(n2))); break; case
"multiplication":
out.println("Answer = "+(Integer.parseInt(n1)
* Integer.parseInt(n2))); break;
default:
out.println("Answer = "+(Integer.parseInt(n1)
/ Integer.parseInt(n2))); break;
}

}
}

OUTPUT:
PROGRAM NO. 12

Aim : Create a registration servlet in Java using JDBC. Accept the details such
as
Username, Password, Email, and Country from the user using HTML Form
and store the registration details in the database.

Index . Html
<!DOCTYPE html>
<html>
<head>
<title>Practical 3</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
</head>
<body>
<h1>Practical 3.A</h1> <br>
<form action="addData" method="post">
Username : <input type='text' name='username'> <br><br>
Password: <input type='password' name='psd'> <br><br>
Email : <input type='email' name='email'> <br><br>
Country : <input type='text' name='country'> <br><br>

<input type='submit' value='Submit'>

</form>
</body> </html>

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

public class addData extends HttpServlet{

public void doPost(HttpServletRequest req,HttpServletResponse res) throws


IOException,ServletException{ res.setContentType("text/html"); PrintWriter out =
res.getWriter();
try{
String username,password,email,country; username= req.getParameter("username");
password= req.getParameter("psd"); email= req.getParameter("email"); country=
req.getParameter("country");

Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","")
;
out.print("<h1>Connected</h1>");
String query = "insert into userdetails values(?,?,?,?)";

PreparedStatement ps = con.prepareStatement(query);

ps.setString(1,username); ps.setString(2,password); ps.setString(3,email);


ps.setString(4,country); ps.executeUpdate(); con.close(); out.println("<h3>data
Inserted
Successfully</h3>");

}
catch(Exception e){ out.println(e);

} }

OUTPUT:
PROGRAM NO. 13
Aim: Design a JDBC application using Servlet/JSP to demonstrate the concept of
ResultSetMetaData.

Resultset.java

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

public class Resultset extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException
{ response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out =
response.getWriter()) {

ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", "");
String query = "select * from userdetails";
Statement st = con.createStatement();

rs = st.executeQuery(query);

ResultSetMetaData rsmd = rs.getMetaData();

out.print("Table Name : " + rsmd.getTableName(1)); out.print("<br>"); out.print("Total


Count : " + rsmd.getColumnCount()); out.print("<br>"); for (int i = 1; i <
rsmd.getColumnCount(); i++) { out.print(rsmd.getColumnName(i) + " : " +
rsmd.getColumnTypeName(i));
out.print("<br>");

} catch (Exception e) {

}
}
}

OUPTPUT:
PROGRAM NO. 14
Aim : Develop a simple JSP application to display values obtained from the use of
intrinsic objects[Implicit Objects] of various types.

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
// out object int num1 = 55; int num2 = 100; out.println("<br>Nu m1 is " + num1);
out.println("<br>Nu m2 is " + num2);
%>
</body>
</html>

// request object index.html


<!DOCTYPE html>

<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="result.jsp" >

Name : <input type="text" name="name">


<br>
Age : <input type="number" name="age">
<br>
<input type="submit" value="submit">
</form>
</body>
</html>
Result.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String name = request.getParameter("name"); int age
=Integer.parseInt(request.getParameter("age"));

out.print("Name : "+name); out.print("Age : "+age);


%>
</body>
</html>

Output :
// response
Response.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>

<%
response.sendRedirect("https://www.google.com/");
%>
</body>
</html>
PROGRAM NO. 15
Aim : Develop a simple JSP application to pass values from one page to another with
validations. (Name-txt, age-txt, hobbies-checkbox, email-txt, genderradio button)

formresult.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="result.jsp" >

Name : <input type="text" name="name">


<br>
Age : <input type="number" name="age">
<br>
Hobbies : <br>
<input type="checkbox" name="hobbies" value="Dancing"> Dancing<br>
<input type="checkbox" name="hobbies" value="Swiming"> Swiming <br>
<input type="checkbox" name="hobbies" value="Playing">Playing<br>
<br>
Email : <input type="email" name="email">
<br>
Gender : Male <input type="radio" name="gender" value="Male"> Female <input type="radio"
name="gender" value="FeMale">
<br>
<input type="submit" value="submit">
</form>
</body>
</html>
Result.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String name = request.getParameter("name");
String email = request.getParameter("email"); int age =
Integer.parseInt(request.getParameter("age"));

String gender = request.getParameter("gender");


String hobbies[] = request.getParameterValues("hobbies");
out.print("<br>Name : " + name); out.print("<br>Age : " + age); out.print("<br>email : " +
email); out.print("<br>gender : " + gender); out.println("<br>Hobbies : "); for
(String str : hobbies)
{ out.println(str + ",");
}
%>
</body>
</html>

OUTPUT:

You might also like