java lab manual
java lab manual
LIST OF EXPERIMENTS
1. To implement program with Commandline arguments,
2. Inheritance
3. To implement program with Polymorphism
4. Interface
5. Abstract classes
6. Upcasting and downcasting
1. Construct a Servlet program to print a welcome message and its number of user visiting page
2. Construct a Servlet program to validate the user login
3. Construct a servlet to handle sessions using URL-rewriting
4. Implement a program with session management using servlet
5. Develop a program in cookie and identify cookie information using servlets
6. Write a program to display CRUD application using Servlet with Databases
1. Implement a program to display date and time in JSP
2. Write a JSP program to include and forward web pages
3. Write a JSP program to display user details from HTML web page
4. Write a program to implement implicit objects in JSP
5. Write a program to display CRUD application using JSP with Databases
6. Create a program to display the values of User information using Hibernate.
1
Department of Computer Science and Engineering
Regno is:101
Name is:CSE
java Mark is:75 C
Mark is:85
R mark is:95
Total is:255
Average is:85.0
Remarks is:Pass in all Subjects
2. Inheritance
class Box
{
double width,height,depth;
Box()
{height=10; width=10; depth=20; }
2
Department of Computer Science and Engineering
Box(double l)
{
width=height=depth=l;
}
Box(double w,double h,double d)
{
width=w;
height=h;
depth=d; }
Box(Box ob)
{ width=ob.width;
height=ob.height;
depth=ob.depth;
}
double volume()
{ System.out.print("The volume of Box is:");
return (width*height*depth);
}
}
class BoxWeight extends Box
{
double weight;
BoxWeight()
{super(); }
BoxWeight(double l)
{super(l);
weight=l;
}
BoxWeight(double w,double h,double d,double w1)
{ super(w,h,d);
weight=w1; }
BoxWeight(BoxWeight ob)
{ super(ob);
weight=ob.weight;
}
}
3
Department of Computer Science and Engineering
class Bank {
//int roi;
int getroi()
{ return 2;
}
}
class SBI extends Bank
{ int getroi()
{
return 4;
}
}
class HDFC extends Bank
{ int getroi()
{ return 5;
}
} class poly
{
public static void main(String[] args)
{
double p,n,r,r1,r2,si;
double ci;
Scanner s=new Scanner(System.in);
System.out.println("Enter p,n,r");
p=s.nextInt();
n=s.nextInt(); Bank b=new Bank();
r=b.getroi(); si=(p*n*r)/100;
double amt=p+si;
ci=p*Math.pow((1+r/100),n);
System.out.println("Amt is:"+amt+"\n"+"CI is:"+ci);
SBI sb=new SBI();
r1=sb.getroi();
si=(p*n*r1)/100;
ci=p*Math.pow((1+r1/100),n);
System.out.println("SI is:"+si+"\n"+"CI is:"+ci);
HDFC h=new HDFC();
4
Department of Computer Science and Engineering
r2=h.getroi();
si=(p*n*r2)/100;
ci=p*Math.pow((1+r2/100),n);
System.out.println("SI is:"+si+"\n"+"CI is:"+ci);
}
}
4. Interface public
interface int1 { int
regno=101;
void input();
String compute();
void display(String s1);
}
interface int2 extends int1
{ void
display();
}
import java.util.Scanner;
5
Department of Computer Science and Engineering
}
public void display(String s)
{ System.out.println("Reg no is:"+regno);
System.out.println("Total is:"+tot);
System.out.println("Avg is:"+avg);
System.out.println("Remarks"+s);
}
public static void main(String[] args)
{ int1 i1=new stuint();
i1.input();
String s1=i1.compute();
i1.display(s1); }
}
5. Abstract classes
return rem;
}
}
6
Department of Computer Science and Engineering
{
result r=new result();
r.getdata1();
r.s1=r.display();
r.getdata2();
r.s2=r.display();
if((r.s1.equals("pass")) && (r.s2.equals("pass")))
{ System.out.println("Overall Pass in Subjects");
}
else
{ System.out.println("Overall Fail in Subjects");
}
}
}
class Alliance
{ }
class ACED extends Alliance {
static void method(Alliance
a)
{ if(a instanceof ACED)
{ ACED d=(ACED)a;
System.out.println("Student of ACED");
}
}}
class ASOB extends Alliance {
static void method(Alliance
a)
{ if(a instanceof ASOB)
{ ASOB d=(ASOB)a;
System.out.println("Student of ASOB");
} }
} class downcast { public static void
main(String[] args)
{ Alliance a1=new ACED();
Alliance a2=new ASOB();
ACED.method(a1);
ASOB.method(a2);
}
}
import java.util.Scanner;
7
Department of Computer Science and Engineering
{ Scanner s;
int bal,amt; String m;
fund(String s)
{ bal=500;
m=s;
System.out.println(m);
}
void compute()throws fund
{
try
{
System.out.println("Enter Amount");
s=new Scanner(System.in);
amt=s.nextInt();
if(bal<amt)
throw new fund("Insufficient");
else
bal=bal-amt;
System.out.println(bal);
}
catch(fund e)
{
System.out.println(e.getMessage());
}
finally{
}
}
} class ex1
{
9
Department of Computer Science and Engineering
10
Department of Computer Science and Engineering
<car>
<year> 1985 </year>
<model> HYUNDAI </model>
<color> Blue </color>
<engine>
<number_of_cylinders> 4 cylinder
</number_of_cylinders>
<fuel_system> fuel injected </fuel_system>
</engine>
<number_of_doors> 4 door </number_of_doors>
<transmission_type> 4 speed manual </transmission_type>
<accessories radio = "yes" air_conditioning = "yes"
power_windows = "no" power_steering = "yes"
power_brakes = "yes" />
</car>
</car_catalog>
11
Department of Computer Science and Engineering
<city> Indore</city>
</s>
</student>
Stud.xsl
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h1 align="center">Student Basic Details</h1>
<table border="3" align="center" >
<tr>
<th>Name</th>
<th>Branch</th>
<th>Age</th>
<th>City</th>
</tr>
<xsl:for-each select="student/s">
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="branch"/></td>
<td><xsl:value-of select="age"/></td>
<td><xsl:value-of select="city"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet> Output:
C. Write a Xml program to display student details using xsd schema structure.
Order.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="order">
<xs:complexType>
<xs:sequence>
<xs:element name="orderperson" type="xs:string"/>
12
Department of Computer Science and Engineering
<xs:element name="ordername">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="item" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="note" type="xs:string" minOccurs="0"/>
<xs:element name="quantity" type="xs:positiveInteger"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="orderid" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>
Order.xml
<?xml version="1.0" encoding="UTF-8"?>
<order orderid="T5987" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="Order.xsd">
<orderperson>John Smith</orderperson>
<ordername>
<name>Jeremiah</name>
<address>Langgt 23</address>
<city>Mumbai</city>
<country>India</country>
</ordername>
<item>
<title>Service Arch</title>
<note>Special Edition</note>
<quantity>2</quantity>
<price>100.90</price>
</item>
<item>
<title>Advanced Java</title>
<quantity>3</quantity>
<price>90.55</price>
</item>
</order>
13
Department of Computer Science and Engineering
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
14
Department of Computer Science and Engineering
9. Develop a project using Objects, Methods and Classes with its databases.
10. Write a JDBC specification to insert a record into the Employee database.
import java.sql.*;
//maysql.connector.jar -> jre/lib/ext file public
class sql1 {
//Class.forName("oracle.jdbc.driver.OracleDriver");
//Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
// String database="student.mdb";//Here database exists in the current directory
// String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};
//DBQ=" + database + ";DriverID=22;READONLY=true";
// Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Connection c=DriverManager.getConnection("jdbc:odbc:mydsn");
Statement stmt=con.createStatement();
stmt.executeUpdate("drop table emp5;");
stmt.executeUpdate("create table emp5(eno int(5),ename varchar(20),esal int(5), edes varchar(10))");
15
Department of Computer Science and Engineering
16
Department of Computer Science and Engineering
records updated
Records Updated using Prepared Statement
1 nasan ellil
2 Gary Larson
3 Stan Lee
12. Write a JDBC transaction specification to establish the connection with the Mysql
import java.sql.*;
class DBbatup
{
public static void main(String args[])
{
Connection con;
try
{ Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/my123","root","root");
Statement stmt=null;
try{
con.setAutoCommit(false);
stmt = con.createStatement(); stmt.executeUpdate("update stud1 set
lname='John' where rollno=101");
System.out.println("Row updated successfully");
}
finally {
if(stmt != null) {
stmt.close();
}
}
17
Department of Computer Science and Engineering
finally
{ }
con.commit();
} catch(Exception e)
{ System.out.println("Error"+e.getMessage());
}
finally
{ }
} }
Row updated successfully
Two Records Updated using Callable Statement
101 AAA John
103 bbb ccc
102 Gary Larson
104 Stan Lee
13. Construct a Servlet program to print a welcome message and its number of user visiting page
import java.io.IOException;
Import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
18
Department of Computer Science and Engineering
}
else
{
Heading="Welcome Once again";
cnt=new Integer(cnt.intValue()+1);
}
session.setAttribute("cnt", cnt);
out.println("<h1>Welcome to session Program: You are Visiting this site as :"+cnt +
" Visitor </h1>");
out.println("<h1>You are Working Servlet Program at " + request.getContextPath () +" <br/><br/>"+Heading);
out.println("</h1> <h2>Your Hidden Session ID is:"+session.getId()+" :ID</h2>");
out.println("</body>");
out.println("</html>");
} finally
{
out.close();
}
}
}
<!DOCTYPE html>
<html><head><meta charset="ISO-8859-1">
<title>Servlet Program for Login</title></head>
<body>
<form name="frm" method="get" action="Ex2">
<h1 style="font-size:40px; font-variants:small-caps; font-weight:bolder">Login Registration Page </h1>
User name is: <input type=text name=username><br/>
Password is: <input type=password name=pass><br/>
<input type= submit value=Enter>
</form></body></html>
import java.io.*;
import javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse;
@WebServlet("/Ex2")
public class Ex2 extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
PrintWriter out=response.getWriter();
String user;
String pwd;
19
Department of Computer Science and Engineering
try{
response.setContentType("text/html");
user=request.getParameter("username");
pwd=request.getParameter("pass"); out.println("<html><body><h1>");
out.println("Welcome to Servlet Servlet Program <br/>");
out.println("Username is: "+user);
out.println("<br/>Password is: "+pwd);
out.println("</h1></body></html>");
out.println(".................Successful Execution. ........... ");
}
catch(Exception e)
{
out.println(e.getMessage());
}
}}
<!DOCTYPE html>
<html><head><meta charset="ISO-8859-1">
<title>URL - reWriting</title></head>
<body>
<form action="Ex4" method="get">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="submit"/>
</form> </body> </html>
20
Department of Computer Science and Engineering
String n = request.getParameter("userName");
out.close();
}
catch (Exception e) {
System.out.println(e);
} } }
response.setContentType("text/html");
PrintWriter out = response.getWriter(); String n =
request.getParameter("uname");
out.print("Good. ... This is " + n+"University");
out.close(); }
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
21
Department of Computer Science and Engineering
index.jsp <html>
<head>
<title>JSP forward action tag example</title>
</head>
<body>
<p align="center">My main JSP page</p>
<jsp:forward page="display.jsp" />
</body>
</html>
display.jsp
<html>
<head>
<title>Display Page</title>
</head>
<body>
Hello this is a display.jsp Page
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>
</body>
</html>
printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
18. Write a program to display CRUD application using JSP with Databases
index.jsp <!DOCTYPE
html>
22
Department of Computer Science and Engineering
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP CRUD Example</title>
</head>
<body>
<h1>JSP CRUD Example</h1>
<a href="adduserform.jsp">Add User</a>
<a href="viewusers.jsp">View Users</a>
</body>
</html>
adduserform.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add User Form</title>
</head>
<body>
<jsp:include page="userform.html"></jsp:include>
</body>
</html>
userform.html
<a href="viewusers.jsp">View All Records</a><br/>
<h1>Add New User</h1>
<form action="adduser.jsp" method="post">
<table>
<tr><td>Name:</td><td><input type="text" name="name"/></td></tr> <tr><td>Password:</td><td>
<input type="password" name="password"/></td></tr>
<tr><td>Email:</td><td><input type="email" name="email"/></td></tr>
<tr><td>Sex:</td><td>
<input type="radio" name="sex" value="male"/>Male
<input type="radio" name="sex" value="female"/>Female </td></tr>
<tr><td>Country:</td><td>
<select name="country" style="width:155px">
<option>India</option>
<option>Pakistan</option>
<option>Afghanistan</option>
<option>Berma</option>
<option>Other</option>
</select>
</td></tr>
<tr><td colspan="2"><input type="submit" value="Add User"/></td></tr>
</table>
</form>
23
Department of Computer Science and Engineering
adduser.jsp
<%@page import="com.javatpoint.dao.UserDao"%>
<jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
<%
int i=UserDao.save(u);
if(i>0){
response.sendRedirect("adduser-success.jsp");
}else{
response.sendRedirect("adduser-error.jsp");
}
%>
User.java
package com.javatpoint.bean;
public class User { private
int id;
private String name,password,email,sex,country;
//generate getters and setters
}
UserDao.java package
com.javatpoint.dao; import
java.sql.*; import
java.util.ArrayList; import
java.util.List; import
com.javatpoint.bean.User;
public class UserDao {
public static Connection getConnection(){
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","","");
}catch(Exception e){System.out.println(e);}
return con;
}
public static int save(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"insert into register(name,password,email,sex,country) values(?,?,?,?,?)");
ps.setString(1,u.getName()); ps.setString(2,u.getPassword());
ps.setString(3,u.getEmail()); ps.setString(4,u.getSex());
ps.setString(5,u.getCountry()); status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int update(User u){
24
Department of Computer Science and Engineering
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"update register set name=?,password=?,email=?,sex=?,country=? where id=?");
ps.setString(1,u.getName()); ps.setString(2,u.getPassword());
ps.setString(3,u.getEmail()); ps.setString(4,u.getSex());
ps.setString(5,u.getCountry()); ps.setInt(6,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int delete(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("delete from register where id=?");
ps.setInt(1,u.getId()); status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static List<User> getAllRecords(){
List<User> list=new ArrayList<User>();
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from register");
ResultSet rs=ps.executeQuery();
while(rs.next()){
User u=new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
u.setPassword(rs.getString("password"));
u.setEmail(rs.getString("email"));
u.setSex(rs.getString("sex"));
u.setCountry(rs.getString("country"));
list.add(u);
}
}catch(Exception e){System.out.println(e);}
return list;
}
public static User getRecordById(int id){
User u=null;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from register where id=?");
ps.setInt(1,id);
ResultSet rs=ps.executeQuery();
while(rs.next()){
u=new User();
25
Department of Computer Science and Engineering
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
u.setPassword(rs.getString("password"));
u.setEmail(rs.getString("email"));
u.setSex(rs.getString("sex"));
u.setCountry(rs.getString("country"));
}
}catch(Exception e){System.out.println(e);}
return u;
}
}
adduser-success.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add User Success</title>
</head>
<body>
<p>Record successfully saved!</p>
<jsp:include page="userform.html"></jsp:include>
</body>
</html>
adduser-error.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add User Error</title>
</head>
<body>
<p>Sorry, an error occurred!</p>
<jsp:include page="userform.html"></jsp:include>
</body>
</html>
viewusers.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>View Users</title>
</head>
<body>
<%@page import="com.javatpoint.dao.UserDao,com.javatpoint.bean.*,java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Users List</h1>
<%
26
Department of Computer Science and Engineering
List<User> list=UserDao.getAllRecords();
request.setAttribute("list",list);
%>
<table border="1" width="90%">
<tr><th>Id</th><th>Name</th><th>Password</th><th>Email</th>
<th>Sex</th><th>Country</th><th>Edit</th><th>Delete</th></tr>
<c:forEach items="${list}" var="u">
<tr><td>${u.getId()}</td><td>${u.getName()}</td><td>${u.getPassword()}</td>
<td>${u.getEmail()}</td><td>${u.getSex()}</td><td>${u.getCountry()}</td>
<td><a href="editform.jsp?id=${u.getId()}">Edit</a></td>
<td><a href="deleteuser.jsp?id=${u.getId()}">Delete</a></td></tr>
</c:forEach>
</table>
<br/><a href="adduserform.jsp">Add New User</a>
</body>
</html>
editform.jsp <!DOCTYPE
html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Edit Form</title>
</head>
<body>
<%@page import="com.javatpoint.dao.UserDao,com.javatpoint.bean.User"%> <%
String id=request.getParameter("id");
User u=UserDao.getRecordById(Integer.parseInt(id));
%>
<h1>Edit Form</h1>
<form action="edituser.jsp" method="post">
<input type="hidden" name="id" value="<%=u.getId() %>"/>
<table>
<tr><td>Name:</td><td>
<input type="text" name="name" value="<%= u.getName()%>"/></td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password" value="<%= u.getPassword()%>"/></td></tr>
<tr><td>Email:</td><td>
<input type="email" name="email" value="<%= u.getEmail()%>"/></td></tr>
<tr><td>Sex:</td><td>
<input type="radio" name="sex" value="male"/>Male
<input type="radio" name="sex" value="female"/>Female </td></tr> <tr><td>Country:</td><td>
<select name="country">
<option>India</option>
<option>USA</option>
<option>Pakistan</option>
<option>Australia</option>
<option>England</option>
</select>
</td></tr>
27
Department of Computer Science and Engineering
edituser.jsp
<%@page import="com.javatpoint.dao.UserDao"%>
<jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
<%
int i=UserDao.update(u);
response.sendRedirect("viewusers.jsp");
%> deleteuser.jsp
<%@page import="com.javatpoint.dao.UserDao"%>
<jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
<%
UserDao.delete(u);
response.sendRedirect("viewusers.jsp");
%>
19. Create a program to display the values of User information using Hibernate
28
Department of Computer Science and Engineering
Now we will add the required dependencies for Hibernate. Here we will use Maven’s feature of dependency
management in pom.xml. pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javacodegeeks.example</groupId>
<artifactId>HibernateMappingExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
</dependencies>
</project>
Let’s create a hibernate configuration file under resources directory in the project.
hibernate.cfg.xml
“Create a console configuration” checkbox on the screen as shown above, to configure Hibernate Console.
The hibernate.cfg.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/hbtutorial</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
29
Department of Computer Science and Engineering
</session-factory>
</hibernate-configuration>
Once you have selected the checkbox for “Create a console configuration”, click Next to go on the screen shown
below for hibernate console and click Finish.
Open Hibernate Console Configuration view in eclipse and it will show database and all the tables of that
database.
import java.util.Set;
30
Department of Computer Science and Engineering
import java.sql.Date;
public Employee() {
}
31
Department of Computer Science and Engineering
Employee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Jul 11, 2016 10:24:48 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.javacodegeeks.example.Employee" table="EMPLOYEE">
<id name="id" type="java.lang.Long">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="firstname" type="java.lang.String">
<column name="FIRSTNAME" />
</property>
<property name="lastname" type="java.lang.String">
<column name="LASTNAME" />
</property>
<many-to-one name="department" class="com.javacodegeeks.example.Department" fetch="join">
<column name="DEPARTMENT_ID" />
</many-to-one>
</class>
</hibernate-mapping>
Department.hbm.xml
32
Department of Computer Science and Engineering
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Jul 11, 2016 10:24:48 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.javacodegeeks.example.Department" table="DEPARTMENT">
<id name="id" type="java.lang.Long">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="departmentName" type="java.lang.String">
<column name="DEPT_NAME" />
</property>
<set name="employees" table="EMPLOYEE" inverse="false" lazy="true">
<key>
<column name="DEPARTMENT_ID" />
</key>
<one-to-many class="com.javacodegeeks.example.Employee"/>
</set>
</class>
</hibernate-mapping>
import org.hibernate.HibernateException;
import org.hibernate.Session; import
org.hibernate.SessionFactory; import
org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import
org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
33
Department of Computer Science and Engineering
hbTest.insertEmployee(1,"Mark","Johnson","Sales",1);
hbTest.insertEmployee(2,"Jill","Johnson","Marketing",2);
}
private long insertEmployee(int id, String firstname, String lastname, String deptName, int deptId)
{
Session session = factory.openSession();
Transaction tx = null;
Long empIdSaved = null;
try {
tx = session.beginTransaction();
Department d = new Department();
d.setDepartmentName(deptName);
d.setId(new Long(deptId));
session.save(d);
Employee e = new Employee();
e.setFirstname(firstname);
e.setLastname(lastname);
e.setId(new Long(id));
e.setDepartment(d);
empIdSaved = (Long) session.save(e);
tx.commit();
} catch(HibernateException ex) {
if(tx != null) tx.rollback();
ex.printStackTrace();
} finally {
session.close();
}
return empIdSaved;
34
Department of Computer Science and Engineering
Test.java
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee s=(Employee)factory.getBean("e");
s.show();
}
}
20. Create an application with restful Web Services Project with Spring Boot
Step 1: Download the Spring Tool Suite (STS) from https://spring.io/tools3/sts/all and extract it.
Step 2: Launch the STS.
Step 3: Click on File menu -> New -> Spring Starter Project ->
35
Department of Computer Science and Engineering
If the Spring Starter Project is not enlisted, then click on Other at the bottom of the menu. A dialog box
appears on the screen. Type Spring Starter Project in the Wizards text box and click on the Next button.
Step 4: provide the name, group, and package of the project. We have provided:
Name: restful-web-services
Group: com.javatpoint
Package: com.javatpoint.server.main
Click on the Next button.
36
Department of Computer Science and Engineering
Step 6: We can see the project structure in the project explorer window.
Step 7: Go to the Maven Repository https://mvnrepository.com/ and add Spring Web MVC, Spring Boot
DevTools, JPA, and H2 dependencies in the pom.xml. After adding the dependencies, the pom.xml file
looks like the following:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
37
Department of Computer Science and Engineering
<groupId>com.javatpoint</groupId>
<artifactId>restful-web-services</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>restful-web-services</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-archiver</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<build> <plugins> <plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin> </plugins> </build> </project>
Step 8: Now open the RestfulWebServicesApplication.java file and Run the file as Java Application.
package com.javatpoint.server.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RestfulWebServicesApplication
{ public static void main(String[] args)
{ SpringApplication.run(RestfulWebServicesApplication.class, args);
}
}
38