Advanced Java File

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

Vaish College of Engineering

Advance java practical file

SUBMITTED TO: SUBMITTED BY:


Gourav Patel
152/CSE/19
INDEX
S. No. List of Programs Remarks

1.
JDBC_Connection_Demo.java

2.
Write a program to implement JSP.

3. Program to insert data into table using JSP.

4.
Program to show validation of user using servlet.

5. Program of calling one servlet by another servlet.

6. 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


operation of database using jdbc java.
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
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(SQLException e)
{
e.printStackTrace();
}
catch(Exception i)
{
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 :
” Mozilla Firefox
File Edit View History Bookmarks 5crapBook Tools Help

.g http:}jocahost:7001}s1run3?namz .

Most Visited Getting Started , Latest Headlines @ Facebook

hCCp://localhost:...abcde&pass=abcde —

user is invalid through service method

Done
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();
         
    }
}
PROGRAM NO: 9
AIM: Develop a Hibernate application to store Feedback of Website Visitor in
MySQL Database.

create
database
feedback
db;
create
table
GuestBo
ok(
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?
zeroDateTimeBehavior=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

AIM: 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(Exception 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

You might also like