Ajp Lab

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

Advanced Java Programming 201240107009

3160707

Practical-1
Aim : Implementing the two-way communication between server and client in java.

Code :
Client Side
import java.io.*;
import java.net.*;
import java.util.*;

public class client1


{
public static void main(String[] args) throws Exception
{
Socket s=new Socket("127.0.0.1",7888);
if(s.isConnected())
{
System.out.println("Connected to server");
}
DataInputStream msg=new DataInputStream(System.in);
String str="Start chat................................";
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF(str);
System.out.println(str);
DataInputStream din=new DataInputStream(s.getInputStream());
while(true)

1
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

{
System.out.print("Client:\t");
str=msg.readLine();
dout.writeUTF(str+"\n");
str=din.readUTF();
System.out.println("Server:\t"+str);
}
}
}

Server Side
import java.io.*;

2
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

import java.net.*;
import java.util.Scanner;
public class server1 {
public static void main (String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(7888);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
String str;
str=din.readUTF();
System.out.println("Client:\t"+str);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
DataInputStream msg=new DataInputStream(System.in);
while(true)
{
str=din.readUTF();
System.out.print("Client:\t"+str);
System.out.print("Server:\t");
str=msg.readLine();
dout.writeUTF(str);
}
}}
Output :

3
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

Practical-2

4
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

Aim : Implement TCP Server for transferring files using Socket and ServerSocket.
Code :
Client Side
import java.io.*;
import java.net.*;
public class client2 {
public static void main (String[] args) throws Exception
{
Socket s= new Socket("127.0.0.1",7777);
if(s.isConnected()
{
System.out.println("Connected to server");
}
FileOutputStream fout=new FileOutputStream("received.txt");
DataInputStream din=new DataInputStream(s.getInputStream());
int r;
while ((r=din.read())!=-1)
{
fout.write((char)r);
}
s.close();
}
}

Server Side

5
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

import java.io.*;
import java.net.*;
class server2
{
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(7777);
Socket s=ss.accept();
System.out.println("connected......");
FileInputStream fin=new FileInputStream("send.txt");
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
int r;
while((r=fin.read())!=-1)
{
dout.write(r);
}
System.out.println("\nFileTransfer Completed");
s.close();
ss.close();
}
}
Output :

6
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

Practical 3

7
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

Aim: Implement student registration form with enrollment number, first name, last name,
semester, contact number. Store the details in database.

index.html

<html>
<body>
<form action="RegisterServlet" method="post">
Enrolement_No:<input type="text" name="en"/><br/><br/>
First Name:<input type="text" name="fn"/><br/><br/>
Last Name:<input type="text" name="ln"/><br/><br/>
Semester :<input type="text" name="sm"/><br/><br/>
Contact No :<input type="text" name="cn"/><br/><br/>
<input type="submit" value="register"/>
</form>
</body>
</html>

RegisterServlet.java
import java.io.*;

8
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

import java.sql.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
public class RegisterServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int eno=Integer.valueOf(request.getParameter("en"));
String fname=request.getParameter("fn");
String lname=request.getParameter("ln");
String sem=request.getParameter("sm");
int phone=Integer.valueOf(request.getParameter("cn"));
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:1527/db1","root","1011");
PreparedStatement ps=con.prepareStatement(
"insert into registeruser values(?,?,?,?,?)");
ps.setInt(1,eno);
ps.setString(2,fname);
ps.setString(3,lname);
ps.setString(4,sem);
ps.setInt(4,phone);
int i=ps.executeUpdate();

9
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

if(i>0) {
out.print("You are successfully registered...");
}
else {
out.print("You are not successfully register...");
}
}catch (Exception e2) {System.out.println(e2);}
out.close();
}
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

10
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/
webapp_4_0.xsd">
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

OUTPUT:

11
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

Practical 4
Aim: Write a Servlet program to print system date and time.

12
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

DateSrv.java

import java.io.*;
import jakarta.servlet.*;
public class DateSrv extends GenericServlet
{
public void service(ServletRequest req, ServletResponse res) throws IOException,
ServletException
{
//set response content type
res.setContentType("text/html");
//get stream obj
PrintWriter pw = res.getWriter();
//write req processing logic
java.util.Date date = new java.util.Date();
pw.println("<h2>"+"Current Date & Time: " +date.toString()+"</h2>");
//close stream object
pw.close();
}
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>

13
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

<web-app version="4.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">
<servlet><servlet-name>DateSrv</servlet-name>
<servlet-class>DateSrv</servlet-class>
</servlet><servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>NewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DateSrv</servlet-name>
<url-pattern>/DateSrv</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
OUTPUT:

14
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

Practical 5
Aim: Implement cookies to store first name and last name using Java server pages.

15
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

index.html
<html>
<body>
<form action = "main.jsp" method = "Post">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>

main.jsp

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


<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));
// Set expiry date after 24 Hrs for both the cookies.
/* firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);*/
// Add both the cookies in the response header.
response.addCookie( firstName );

16
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

response.addCookie( lastName );
%>
<html>
<head>
<title>Setting Cookies</title>
</head>
<body>
<center>
<h1>Setting Cookies</h1>
</center>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>

OUTPUT:

17
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

Practical 6

18
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

Aim: Design a web page that takes the Username from user and if it is a valid username
prints
“Welcome Username”. Use JSF to implement.

index.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:c="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<h:form id="loginForm">
<h:outputLabel value="username" />
<h:inputText value="#{loginBean.username}" />
<h:outputLabel value="password" />
<h:inputSecret value="#{loginBean.password}"></h:inputSecret>
<h:commandButton value="Login” action="#{loginBean.login}"></h:commandButton>
</h:form>
</h:body>
</html>

LoginBean.java
import javax.faces.bean.ManagedBean;

19
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

@ManagedBean
public class LoginBean
{
String username;
String password;
public String getUsername() {return username;}
public void setUsername(String username) {this.username = username;}
public String getPassword() {return password;}
public void setPassword(String password) {this.password = password;}
public String login()
{
if(username.equals("java") && password.equals("jsfdemo"))
{return "Welcome Java";}
else{return "failure”;}
}
}

web.xml
<web-app>
<context-param>

20
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>
javax.faces.webapp.FacesServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
OUTPUT:

21
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

Practical 7
Aim: Case Study of Hibernate

22
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

Hibernate was started in 2001 by Gavin King with colleagues from Cirrus Technologies as an
alternative to using EJB2-style entity beans. The stable of Hibernate till July 16, 2014, is
hibernate 4.3.6. It is helpful for beginners and experienced persons.
Hibernate is a high-performance Object/Relational persistence and query service, which is
licensed under theopen source GNU Lesser General Public License (LGPL) and is free to
download. Hibernate not only takes care of the mapping from Java classes to database tables
(and from Java data types to SQL data types), but also provides data query and retrieval
facilities.

Hibernate Framework

Hibernate is a Java framework that simplifies the development of Java application to interact
with the database.
It is an open source, lightweight, ORM (Object Relational Mapping) tool. Hibernate
implements the specifications of JPA (Java Persistence API) for data persistence.
An ORM tool simplifies the data creation, data manipulation and data access. It is a
programming technique that maps the object to the data stored in the database.
The ORM tool internally uses the JDBC API to interact with the database.

Supported Datebases:

23
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

Hibernate supports almost all the major RDBMS. Following is list of few of the database
engines supported by Hibernate.
▪ HSQL Datebase Engine
▪ DB2/NT
▪ MySQL
▪ PosterSQL
▪ FrontBase
▪ Oracle
▪ Microsoft SQL Server Database
▪ Sybase SQL Server
▪ Informix Dynamic Server

Supported Technologies:
Hibernate supports a variety of other technologies, including followings:
▪ XDoclet Spring
▪ J2EE
▪ Eclipse Plug-ins
▪ Maven
Advantages of Hibernate Framework:
Following are the advantages of hibernate framework:
1) Open Source and Lightweight
Hibernate framework is open source under the LGPL license and lightweight.
2) Fast Performance
The performance of hibernate framework is fast because cache is internally used in hibernate
framework. There are two types of cache in hibernate framework first level cache and second
level cache. First level cache is enabled by default.

24
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

3) Database Independent Query


HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the
database independent queries. So you don't need to write database specific queries. Before
Hibernate, if database is changed for the project, we need to change the SQL query as well that
leads to the maintenance problem.
4) Automatic Table Creation
Hibernate framework provides the facility to create the tables of the database automatically. So
there is no need to create tables in the database manually.
5) Simplifies Complex Join
Fetching data from multiple tables is easy in hibernate framework.
6) Provides Query Statistics and Database Status
Hibernate supports Query cache and provide statistics about query and database status.
Hibernate Architecture:
The Hibernate architecture includes many objects such as persistent object, session factory,
transaction factory,
connection factory, session, transaction etc.

The Hibernate architecture is categorized in four layers.


▪Java application layer
▪Hibernate framework layer
▪Backhand api layer
▪Database layer

25
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

Hibernate Architecture:
This is the high level architecture of Hibernate with mapping file and configuration file.
Hibernate framework uses many objects such as session factory, session, transaction etc.
alongwith existing Java API such as JDBC (Java Database Connectivity), JTA (Java
Transaction API) and JNDI
(Java Naming Directory Interface)
Elements of Hibernate Architecture:
For creating the first hibernate application, we must know the elements of Hibernate
architecture. They are as follows:

26
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

SessionFactory
The SessionFactory is a factory of session and client of ConnectionProvider. It holds second
level cache (optional) of data. The org.hibernate.SessionFactory interface provides factory
method to get the object of Session.
Session
The session object provides an interface between the application and data stored in the database.
It is a short-lived object and wraps the JDBC connection. It is factory of Transaction, Query and
Criteria. It holds a first-level cache (mandatory) of data. The org.hibernate.Session interface
provides methods to insert, update and delete the object.It also provides factory methods for
Transaction, Query and Criteria.
Transaction
The transaction object specifies the atomic unit of work. It is optional. The
org.hibernate.Transaction interface provides methods for transaction management.

27
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

ConnectionProvider
It is a factory of JDBC connections. It abstracts the application from DriverManager or
DataSource. It is optional.
TransactionFactory
It is a factory of Transaction. It is optional.
Downloading Hibernate:
It is assumed that you already have the latest version of Java installed on your system.
Following are the simple steps to download and install Hibernate on your system −
Make a choice whether you want to install Hibernate on Windows, or Unix and then proceed to
the next step to download .zip file for windows and .tz file for Unix.
Download the latest version of Hibernate from http://www.hibernate.org/downloads.
At the time of writing this tutorial, I downloaded hibernate-distribution3.6.4.Final and when
you unzip the downloaded file, it will give you directory structure as shown in the following
image

Installing Hibernate:
Once you downloaded and unzipped the latest version of the Hibernate Installation file, you
need to perform following two simple steps. Make sure you are setting your CLASSPATH
variable properly otherwise you will face problem while compiling your application.
▪ Now, copy all the library files from /lib into your CLASSPATH, and change your classpath
variable to include all the JARs –

28
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

▪ Finally, copy hibernate3.jar file into your CLASSPATH. This file lies in the root directory of
the installation and is the primary JAR that Hibernate needs to do its work.

Hibernate Prerequisites
Following is the list of the packages/libraries required by Hibernate and you should install them
before starting with Hibernate. To install these packages, you will have to copy library files
from /lib into your CLASSPATH,and change your CLASSPATH variable accordingly.

29
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

Practical 8
Aim: Write Hibernate application to store customer records and retrieve the customer
record.
RegController.java

package com.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.dao.RegDAO;
import com.vo.RegVO;
/**
* Servlet implementation class RegController
*/
@WebServlet("/RegController")
public class RegController extends HttpServlet {
private static final long serialVersionUID = 1 L;
/**
* @see HttpServlet#HttpServlet()
*/

30
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

public RegController() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException,
IOException {
String flag = request.getParameter("flag");
if (flag.equals("Search")) {
Search(request, response);
}
if (flag.equals("Delete")) {
Delete(request, response);
Search(request, response);
}
if (flag.equals("Edit")) {
Edit(request, response);
}
if (flag.equals("Update")) {
Update(request, response);
Search(request, response);
}

31
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String flag = request.getParameter("flag");
if (flag.equals("Insert")) {
Insert(request, response);
response.sendRedirect("form.jsp");
}
}
protected void Insert(HttpServletRequest request, HttpServletResponse response) throws
ServletException,
IOException {
String fn = request.getParameter("fn");
String ln = request.getParameter("ln");
String cn = request.getParameter("cn");
String add = request.getParameter("add");
RegVO regVO = new RegVO();
regVO.setFn(fn);
regVO.setLn(ln);
regVO.setCn(cn);
regVO.setAdd(add);
RegDAO regDAO = new RegDAO();

32
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

regDAO.Insert(regVO);
}
protected void Search(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
RegDAO regDAO = new RegDAO();
List searchList = regDAO.Search();
HttpSession session = request.getSession();
session.setAttribute("data", searchList);
response.sendRedirect("search.jsp");
}
protected void Delete(HttpServletRequest request, HttpServletResponse response) throws
ServletException,
IOException {
int id = Integer.parseInt(request.getParameter("x"));
RegVO regVO1 = new RegVO();
regVO1.setId(id);
RegDAO regDAO = new RegDAO();
regDAO.Delete(regVO1);
}
protected void Edit(HttpServletRequest request, HttpServletResponse response) throws
ServletException,
IOException {
int id1 = Integer.parseInt(request.getParameter("y"));
RegVO regVO2 = new RegVO();
regVO2.setId(id1);

33
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

RegDAO regDAO = new RegDAO();


List ls1 = regDAO.Edit(regVO2);
HttpSession session = request.getSession();
session.setAttribute("data1", ls1);
response.sendRedirect("edit.jsp");
}
protected void Update(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
int idu = Integer.parseInt(request.getParameter("idupdate"));
String fn1 = request.getParameter("fn");
String ln1 = request.getParameter("ln");
String cn1 = request.getParameter("cn");
String add1 = request.getParameter("add");
RegVO regVO3 = new RegVO();
regVO3.setId(idu);
regVO3.setFn(fn1);
regVO3.setLn(ln1);
regVO3.setCn(cn1);
regVO3.setAdd(add1);
RegDAO regDAO = new RegDAO();
regDAO.Update(regVO3);
}
}

RegDAO.java

34
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

package com.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import com.vo.RegVO;
public class RegDAO {
public void Insert(RegVO regVO) {
SessionFactory sessionFactory = new
AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(regVO);
transaction.commit();
session.close();
}
public List Search() {
SessionFactory sessionFactory = new
AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

35
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

Query q = session.createQuery("from RegVO");


List searchList = q.list();
transaction.commit();
session.close();
return searchList;
}
public void Delete(RegVO regVO1) {
try {
SessionFactory sessionFactory = new
AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.delete(regVO1);
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public List Edit(RegVO regVO2) {
List ls1 = new ArrayList();
try {
SessionFactory sessionFactory = new
AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();

36
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

Transaction transaction = session.beginTransaction();


Query q = session.createQuery("From RegVO where id='" + regVO2.getId() + "'");
ls1 = q.list();
((RegDAO) session).Edit(regVO2);
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return ls1;
}
public void Update(RegVO regVO3) {
try {
SessionFactory sessionFactory = new
AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.update(regVO3);
transaction.commit();
session.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

37
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

RegVO.java

package com.vo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "hibernate_tbl")
public class RegVO {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "FirstName")
private String fn;
@Column(name = "LastName")
private String ln;
@Column(name = "Contact_Number")
private String cn;
@Column(name = "Address")
private String add;

38
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public String getFn() {
return fn;
}
public void setFn(String fn) {
this.fn = fn;
}
public String getLn() {
return ln;
}
public void setLn(String ln) {
this.ln = ln;
}
public String getCn() {
return cn;
}
public void setCn(String cn) {
this.cn = cn;
}
public String getAdd() {

39
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

return add;
}
public void setAdd(String add) {
this.add = add;
}
}

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/manual</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.vo.RegVO"/>
</session-factory>

40
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

</hibernate-configuration>

form.jsp File
<%@ 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">
<title>Insert title here</title>
</head>
<body>
<form action="RegController" method="post">
<table border="1px solid black">
<tr>
<td>First_Name: </td>
<td><input type="text" name="fn"></td>
</tr>
<tr>
<td>Last_Name: </td>
<td><input type="text" name="ln"></td>
</tr>
<tr>
<td>Contact_Number: </td>

41
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

<td><input type="text" name="cn"></td>


</tr>
<tr>
<td>Address: </td>
<td><input type="text" name="add"></td>
<td><input type="hidden" name="flag" value="Insert"></td>
</tr>
<tr>
<td><input type="submit" value="Save"></td>
</tr>
</table>
</form>
<a href="RegController?flag=Search">Search</a>
</body>
</html>

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

42
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">


<title>Insert title here</title>
</head>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<body>
<form action="RegController" method="get">
<table border="1px solid black">
<c:forEach var="i" items = "${sessionScope.data1}">
<input type=hidden name=idupdate value="${i.id}">
<tr>
<td>First_Name: </td>
<td><input type="text" name="fn" value="${i.fn}"></td>
</tr><tr>
<td>Last_Name: </td>
<td><input type="text" name="ln" value="${i.ln}"></td>
</tr>
<tr>
<td>Contact_Number: </td>
<td><input type="text" name="cn" value="${i.cn}"></td>
</tr><tr>
<td>Address: </td>
<td><input type="text" name="add" value="${i.add}"></td>
<td><input type="hidden" name="flag" value="Update"></td>
</tr><tr>
<td><input type="submit" value="Update"></td>

43
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

</tr>
</c:forEach>
</table>
</form>
</body>
</html>

search.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">
<title>Insert title here</title>
</head>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<body>
<table border="1px solid black">
<tr>
<th>Number</th>
<th>First Name</th>
<th>Last Name</th>
<th>Contact Number</th>
<th>Address</th>

44
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

<th>Action</th>
</tr>
<c:forEach items="${sessionScope.data}" var="i" varStatus="j">
<tr>
<td>${j.count}</td>
<td>${i.fn}</td>
<td>${i.ln}</td>
<td>${i.cn}</td>
<td>${i.add}</td>
<td><a href="RegController?flag=Delete&x=${i.id}">Delete</td>
<td><a href="RegController?flag=Edit&y=${i.id}">Edit</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>

Practical 9

Aim: Study and Implement MVC using Spring Framework.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"

45
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-
v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javatpoint</groupId>
<artifactId>SpringMVC</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringMVC Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>

46
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMVC</finalName>
</build>
</project>

HelloController.java

package com.javatpoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/")
public String display()
{
return "index";
}
}

web.xml

47
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

<?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>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd

48
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.demo " />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
</beans>
index.jsp
<html>
<body>
<p>Welcome to Spring MVC Tutorial</p>
</body>
</html>
OUTPUT:

49
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

Practical 10
Aim: Create a simple application of spring Framework.

Name.java

public class Name {


private String message;
public void setMessage(String message){
this.message = message;
}

50
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

public void getMessage(){


System.out.println("Your Name is : " + message);
}
}

MainApp.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
name obj = (name) context.getBean("name");
obj.getMessage();
}
}

Beans.xml

<?xml version = "1.0" encoding = "UTF-8"?>


<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "name" class = "com.name">

51
SPEC- BAKROL
Advanced Java Programming 201240107009
3160707

<property name = "message" value = " Parthiv Patel "/>


</bean>
</beans>

OUTPUT:

Your Name is: Parthiv Patel

52
SPEC- BAKROL

You might also like