0% found this document useful (0 votes)
2 views60 pages

Web Dev Randeep

The document outlines a series of programming tasks related to web development using Java and JSP, including creating web pages, configuring Apache Tomcat, and implementing Java Beans and Socket Programming. It provides code examples and instructions for various applications such as a student registration system, a client-server program, and database connectivity using JDBC. The tasks are designed for students in the Department of Computer Applications at Maharaja Surajmal Institute, affiliated with GGSIP University.

Uploaded by

p5mdnd229q
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views60 pages

Web Dev Randeep

The document outlines a series of programming tasks related to web development using Java and JSP, including creating web pages, configuring Apache Tomcat, and implementing Java Beans and Socket Programming. It provides code examples and instructions for various applications such as a student registration system, a client-server program, and database connectivity using JDBC. The tasks are designed for students in the Department of Computer Applications at Maharaja Surajmal Institute, affiliated with GGSIP University.

Uploaded by

p5mdnd229q
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

MAHARAJA SURAJMAL INSTITUTE

Affiliated to GGSIP Umiversity & NAAC ‘A+’ Grade accredited

DEPARTMENT OF COMPUTER APPLICATIONS


Web Development with Java & JSP Lab (BCAP-315)

SUBMITTED BY: SUBMITTED TO:


RANDEEP SINGH ARORA MR. MANPREET SINGH
(05521202021) (ASSISTANT PROFESSOR)
2

INDEX

S.no Program Signature


1. Create a webpage that prints your name to the screen, print your name in Tahoma
font, print a definition list with 5 items, Create links to five different pages, etc.

2. Program to demonstrate swing components.


3. Configure Apache Tomcat and write a hello world JSP page.

4. Write a java program that connects a database using JDBC and does add, delete and
retrieve operations.

5. Create and develop a web application using JSF.


6. Write a program to implement a Java Beans to set and get values.

7. Create a Java application to demonstrate Socket Programming in Java.

8. Write a program to retrieve hostname—using methods in Inetaddress class.

9. Write a client-server program which displays the server machine’s date and time on
the client machine.

10. Create a table in the database containing the columns to store book details like:
book name, authors, description, price and URL of the book’s cover image. Using JSP
and JDBC retrieve details in the table and display them on the webpage.

11. Write a program to create a login page using Java Beans. Also validate the username
and password from the database.

12. Create a form for inputting text and uploading image using struts.

13. Create a Student Registration application using Hibernate.

14. Write a program to implement MVC using Spring Framework.


3

1 Create a webpage that print your name to the screen,


print your name in ‘Tohoma’ font , print a definition list with
5 items, creates links to five different pages.

CODE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Webpage</title>
<style> body , font-family:
'Tahoma', sans-serif;
-
</style>
</head>
<body>
<h1 style="font-family: 'Tahoma', sans-serif;">Ansh Shokeen</h1>
<h2>Definition List</h2>
<dl>
<dt>Item 1</dt>
<dd>Cake</dd> <dt>Item
2</dt>
<dd>Donut</dd>
<dt>Item 3</dt>
<dd>Dosa</dd>
4

<dt>Item 4</dt>
<dd>Rice</dd>
<dt>Item 5</dt>
<dd>Apple</dd>
</dl>
<!-- Step 3: Links to Five Different Pages -->
<h2>Links to Five Different Pages</h2>
<ul>
<li><a href="page1.html">Page 1</a></li>
<li><a href="page2.html">Page 2</a></li>
<li><a href="page3.html">Page 3</a></li>
<li><a href="page4.html">Page 4</a></li>
<li><a href="page5.html">Page 5</a></li>
</ul>
</body>
</html>
5

Output:
6

2 Program to Demonstrate Swing Component.

import javax.swing.*; import java.awt.*;


import java.awt.event.ActionEvent; import
java.awt.event.ActionListener; public class
SwingDemo ,
public static void main(String*+ args) ,
SwingUtilities.invokeLater(() -> ,
createAndShowGUI();
-);
-
private static void createAndShowGUI() , JFrame frame = new
JFrame("Swing Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200); frame.setLayout(new FlowLayout());
JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField(15); JButton
button = new JButton("Say Hello");
button.addActionListener(new ActionListener() ,
@Override
public void actionPerformed(ActionEvent e) ,
String name = textField.getText();
JOptionPane.showMessageDialog(frame, "Hello, " + name + "!");
-
-);
frame.add(label);
frame.add(textField);
frame.add(button); //
7

Display the frame


frame.setVisible(true);
-

Output:
8

3 Configure Apache Tomcat and write, hello world servlet


page.

Step-1 Install the Setup of Apache Tomcat.

Step 2 Select all the options.

Step-3 Install the Application.


9

Step-4 Go to the Browser and write http://localhost:8080/

SOURCE CODE
10
11

Q-4 Write a program that connects to a database using


JDBC and does add, delete and retrieve operations.

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
class Mysql ,
public static void main(String*+ args) ,
String url="jdbc:mysql://localhost:3386/"jdbcdemo";
String username="root";
String password="";
try ,
Class.forName("com.mysql.cj,jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username,
passowrd);
statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuerry(sql:"select * from
student");
while (resultSet.next()) ,
system.out.println(resultSet.getInt(columnindex
1)+""+resultSet.getString(Columindex 2)+resultSet.getInt())
-
connection.close();
-
- catch( Exception e),
System.out.println(e);
12

-
-
Step – 1 Open Xampp and run the Server
Step – 2 Now make a table name “Student” and fill the entries.

To Delete the Data from the table. public


static void main(String*+ args) , Main
main = new Main(); main.deleteid(2);

OUTPUT:

Q-5 Create and develop a web application using jsf.


13

Step-1 Create a file 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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint.test</groupId>
<artifactId>helloworld</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>helloworld 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>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.7</version>
</dependency>
14

<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.7</version>
</dependency>
</dependencies>
<build>
<finalName>helloworld</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step-2 Prepare Eclipse Project
Step-3 Import Project in Eclipse
15

Step-4 Configure Faces Servlet in web.xml


<?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" xmlns:web =
"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id = "WebApp_ID"
version="2.5">
<welcome-file-list>
<welcome-file>faces/home.xhtml</welcome-file>
</welcome-file-list>
<!--
FacesServlet is main servlet responsible to handle all request.
It acts as central controller.
This servlet initializes the JSF components before the JSP is displayed.
-->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
16

<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>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>
Step-5 Create a jsf File.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
17

<title>JSF Tutorial!</title>
</head>

<body>
#,helloWorld.getMessage()-
</body>
</html>
Step-6 Run the Application.
18

Q-6 Write a program to implement a Java Bean to set and


get values.
Step-1 Create a file and save it as Person.java
public class person , private String firstName;
private String lastName; public String
getFirstName() , return firstName;
-
public void setFirstName (String firstname, String firstName)
,
this.firstName=firstName;
-
public String getlastName() ,
return lastName;
-
public void setLastName String lastName1) ,
this.lastName=lastName;
-
-
Step -2 Create another file and save it as Studentbean.java
public class CreateAJavaBean, public static void main
(String*+ args) ,
Person person=new Person();
person.SetFirstname("Stephon"); person.SerLastname("Withrow");
System.out.println("Java bean data:" + person.getFirstName() + "" + person.getLastName);
-
-
Step – 3 Open a command prompt and navigate to the directory containing your new Java
programs. Then type in the command to compile the Java bean source and hit Enter.
19

Step – 4 Type in the command to compile the Java application to instantiate the Java bean
and hit Enter.

Step – 5 You are ready to test your Java program. Type in the command to run the Java
runtime launcher and hit Enter. Observe the data from your Java bean.
20

Q-7 Create a java application to demonstrate Socket


Programming in Java. Step-1 Establish the Connection.
Now create a java file.
import java.net.*; import
java.io.*; public class
ClientProgram
,
private Socket socket = null; private
DataInputStream input = null; private
DataOutputStream out = null; //
constructor to put ip address and port
public Client(String address, int port)
,
try
,
socket = new Socket(address, port);
System.out.println("Connected"); input = new
DataInputStream(System.in); out = new
DataOutputStream(socket.getOutputStream());
-
catch(UnknownHostException u)
,
System.out.println(u);
-
catch(IOException i)
,
System.out.println(i);
21

-
String line = "";
while (!line.equals("Over"))
,
try
,
line = input.readLine(); out.writeUTF(line);
-
catch(IOException i)
,
System.out.println(i);
-
-
try
,
input.close(); out.close();
socket.close();
-
catch(IOException i)
,
System.out.println(i);
-
-
public static void main(String args*+) , Client
client = new Client("127.0.0.1", 5000);
-
-
Step – 2 Write a program to implement socket connection at server side.
22

import java.net.*;
import java.io.*; public
class ServerSide
,
private Socket socket = null; private
ServerSocket server = null; private
DataInputStream in = null; public
Server(int port)
,
// starts server and waits for a connection try,
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ..."); socket =
server.accept();
System.out.println("Client accepted"); in =
new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = ""; while
(!line.equals("Over"))
,
try
,
line = in.readUTF(); System.out.println(line);
-
catch(IOException i)
,
System.out.println(i);
-
23

-
System.out.println("Closing connection");
socket.close(); in.close();
-
catch(IOException i), System.out.println(i);
-
-
public static void main(String args*+),
Server server = new Server(5000);
-
-
Step- 3 When you run the server side script, it will start and wait for the client to get started.

Step-4 Next, the client will get connected and inputs the request in the form of a string.

Step-5 When the client sends the request, the server will respond back.
24

Q-8 Write a program to retrieve hostname – using method


Inetaddress class.
import java.net.InetAddress;
import java.net.UnknownHostException;
public class JavaInetAddressGetHostNameExample1 ,
public static void main(String*+ args) ,
try ,
InetAddress id = InetAddress.getLocalHost();
System.out.println( id.getHostName());
- catch (UnknownHostException e) ,
-
-
-

OUTPUT:
25

Q-9 Write a client-server program which displays the


server machine’s date and time on the client machine.

//Data Client.Java
import java.io.*; import
java.net.*; class
DateClient
,
public static void main(String args*+) throws Exception
,
Socket soc=new Socket(InetAddress.getLocalHost(),5217);
BufferedReader in=new BufferedReader(new
InputStreamReader(soc.getInputStream() ));
System.out.println(in.readLine());
-
-

//DataServer.Java
import java.net.*;
import java.io.*; import
java.util.*; class
DateServer
,
public static void main(String args*+) throws Exception
,
ServerSocket s=new ServerSocket(5217);
while(true)
,
26

System.out.println("Waiting For Connection ...");


Socket soc=s.accept();
DataOutputStream out=new DataOutputStream(soc.getOutputStream());
out.writeBytes("Server Date: " + (new Date()).toString() + "\n"); out.close();
soc.close();
-
-
-
27

Q-10 Create a table in the database containing the columns


to store book details like: book name, authors, description,
price and URL of the book’s cover image. Using JSP and
JDBC retrieve details in the table and display them on the
webpage.

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


8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
28

<div align = center>


<h1>User Login</h1>
</div>
<form action=LoginServlet method=post>
<table>
<tr> <td> Enter Name: </td><td><input type=text name=txtName></td></tr>
<tr> <td> Enter Password: </td><td><input type=password name=txtPwd></td></tr>
<tr> <td><td><input type=submit value=Login></td><td><input type=reset></td></tr>
</table>
</form>
</body>
</html>
Step- 4 Create servlet Class. package msi; import
java.io.IOException; import java.io.PrintWriter;
import java.sql.Connection; import
java.sql.DriverManager; import
java.sql.PreparedStatement; import
java.sql.ResultSet; import java.sql.SQLException;
import jakarta.servlet.RequestDispatcher; import
jakarta.servlet.ServletException; import
jakarta.servlet.http.HttpServlet; import
jakarta.servlet.http.HttpServletRequest; import
jakarta.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/ public class LoginServlet extends HttpServlet ,
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
29

HttpServletResponse response) throws


ServletException, IOException ,

try ,
PrintWriter out = response.getWriter();
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/msi",
"root", "root");
String n = request.getParameter("txtName");
String p = request.getParameter("txtPwd");
PreparedStatement ps = con.prepareStatement("select uname from login
where uname=? and password=?"); ps.setString(1,n); ps.setString(2,p);
ResultSet rs = ps.executeQuery();
if(rs.next()) ,
RequestDispatcher
rd=request.getRequestDispatcher("welcome.jsp");
rd.forward(request,response);
-
else ,
out.println("<font color=red size=18>Login Failed!!<br>");
out.println("<a href=login.jsp>Try Again!!</a>");
-
- catch (ClassNotFoundException e) ,
e.printStackTrace();
- catch (SQLException e) ,
e.printStackTrace();
-
-
-
30

Step – 5 Create Welcome.jsp file.


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Login Successful1!</h1>
</body>
</html>
31

Output
32
33

Q-11 Write a program to create a login page using Java


Beans. Also validate the username and password from the
database.

Step:1 Create a web page "login.jsp" to login the user.


<html>
<head>
</head>
<body>
<form name="loginform" method="post" action="loginbean.jsp">
<br><br>
<table align="center"><tr><td><h2>Login Authentication</h2></td></tr></table>
<table width="300px" align="center" style="border:1px solid
#000000;backgroundcolor:#efefef;">
<tr><td colspan=2></td></tr>
<tr><td colspan=2>&nbsp;</td></tr>
<tr>
<td><b>Login Name</b></td>
<td><input type="text" name="userName" value=""></td>
</tr>
<tr>
<td><b>Password</b></td>
<td><input type="password" name="password" value=""></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Submit"></td>
34

</tr>
<tr><td colspan=2>&nbsp;</td></tr>
</table>
</form>
</body>
</html>
Step:2 To create a "loginbean.jsp" to set the parameter of the login.
<%@ page language="Java" import="java.sql.*" %>
<HTML>
<HEAD><TITLE>DataBase Search</TITLE></HEAD>
<BODY>
<jsp:useBean id="db" scope="request" class="logbean.LoginBean" >
<jsp:setProperty name="db" property="userName"
value="<%=request.getParameter("userName")%>"/>
<jsp:setProperty name="db" property="password"
value="<%=request.getParameter("password")%>"/>
</jsp:useBean>
<jsp:forward page="hello">
<jsp:param name="username" value="<%=db.getUserName()%>" />
<jsp:param name="password" value="<%=db.getPassword()%>" />
</jsp:forward>
</body> </html>
Step:3 To create a "LoginBean.java" to mapping the parameter of "loginbean.jsp".
package logbean; public class LoginBean , String userName=""; String password="";
public String getUserName() , return userName;
-
public void setUserName(String userName) , this.userName =
userName;
35

-
public String getPassword() , return
password;
-
public void setPassword(String password) , this.password =
password;
-
-
Step:4 To create a Servlet "login.java" for validate the user login. import java.io.*;
import javax.servlet.*; import javax.servlet.http.*; import javax.sql.*; import
java.sql.*; public class login extends HttpServlet, public void
doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException,IOException, response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "user_register";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
String username="";
String userpass="";
String strQuery= "";
Statement st=null;
ResultSet rs=null;
HttpSession session = request.getSession(true); try ,
36

Class.forName(driver).newInstance(); conn =
DriverManager.getConnection(url+dbName,userName,password);
if(request.getParameter("username")!=null && request.getParameter("username")!=""
&& request.getParameter("password")!=null
&&
request.getParameter("password")!="")
,
username = request.getParameter("username").toString(); userpass =
request.getParameter("password").toString(); strQuery="select * from
userregister where
username='"+username+"' and password='"+userpass+"'";
System.out.println(strQuery); st = conn.createStatement(); rs
= st.executeQuery(strQuery); int count=0; while(rs.next())
,
session.setAttribute("username",rs.getString(2)); count++;
-
if(count>0)
,
response.sendRedirect("welcome.jsp");
-
else
,
response.sendRedirect("login.jsp");
-
-
else
,
response.sendRedirect("login.jsp");
37

-
System.out.println("Connected to the database"); conn.close();
System.out.println("Disconnected from database"); -
catch (Exception e) , e.printStackTrace();
-
-
-
Step :5 To create the webpage "welcome.jsp" to display the message after successful
message.
<HTML>
<HEAD><TITLE>Welcome</TITLE></HEAD>
<BODY>
<br><br><br><br>
<table align="center" style="border:1px solid #000000;">
<%
if(session.getAttribute("username")!=null && session.getAttribute("username")!="")
,
String user = session.getAttribute("username").toString();
%>
<tr><td align="center"><h1>Welcome <b><%= user%></b></h1></td></tr>
<%
-
%>
</table> </body>
38
39

Q-12 Create a form for inputting text and uploading image


using struts.

Step-1 Create UserImage.jsp


<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Upload User Image</title>
</head>
<body>
<h2>
Struts2 File Upload & Save Example without Database
</h2>
<s:actionerror />
<s:form action="userImage" method="post" enctype="multipart/form-data">
<s:file name="userImage" label="Image" />
<s:submit value="Upload" align="center" />
</s:form>
</body>
</html>
Step – 2 Create Success User Image.jsp
<%@ page contentType="text/html; charset=UTF-8"%><%@ taglib prefix="s"
uri="/struts-tags"%>
<html>
<head>
<title>Success: Upload User Image</title>
40

</head>
<body>
<h2>
Struts2 File Upload Example
</h2>
User Image: <s:property value="userImage" /><br/>
Content Type:<s:property value="userImageContentType" /><br/>
File Name: <s:property value="userImageFileName" /><br/>
Uploaded Image: <img src="userimages/<s:property value="userImageFileName"/>"
width="100" height="100" />
</body>
</html>
Step – 3 Create the action class package
com.javatpoint; import java.io.File; import
javax.servlet.http.HttpServletRequest; import
org.apache.commons.io.FileUtils; import
com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport,


private File userImage; private String
userImageContentType; private String
userImageFileName;

public String execute() ,


try ,
String filePath =
ServletActionContext.getServletContext().getRealPath("/").concat("userimages");
41

System.out.println("Image Location:" + filePath);//see the server console for actual


location
File fileToCreate = new File(filePath,userImageFileName);
FileUtils.copyFile(userImage, fileToCreate);//copying source file to new file

return SUCCESS;
-
public File getUserImage() ,
return userImage;
-
public void setUserImage(File userImage) ,
this.userImage = userImage;
-
public String getUserImageContentType() ,
return userImageContentType;
-

public void setUserImageContentType(String userImageContentType) ,


this.userImageContentType = userImageContentType;
-
public String getUserImageFileName() ,
return userImageFileName;
-
public void setUserImageFileName(String userImageFileName) ,
this.userImageFileName = userImageFileName;
-
-
Step – 4 Create struts.xml
42

<struts>
<package name="fileUploadPackage" extends="struts-default">
<action name="userImage" class="com.javatpoint.FileUploadAction">
<interceptor-ref name="fileUpload">
<param name="maximumSize">2097152</param>

<param name="allowedTypes">
image/png,image/gif,image/jpeg,image/pjpeg
</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">SuccessUserImage.jsp</result>
<result name="input">UserImage.jsp</result>
</action>
</package>
</struts>
43

Q-13 Create a Student Registration application using


Hibernate.

Step - 1 MySQL Database Setup


CREATE TABLE `users` (
`id` int(3) NOT NULL,
`first_name` varchar(20) DEFAULT NULL,
`last_name` varchar(20) DEFAULT NULL,
`username` varchar(250) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
SELECT * FROM mysql_database.Student:
Step – 2 Create a JPA Entity - User.java
package net.javaguides.hibernate.model;
import java.io.Serializable; 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
44

@Table(name = "users") public class User


implements Serializable , private static final
long serialVersionUID = 1 L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "user_name")
private String username;
@Column(name = "password")
private String password; public
String getFirstName() , return
firstName;
-
public void setFirstName(String firstName) ,
this.firstName = firstName;
-
public String getLastName() ,
return lastName;
-
public void setLastName(String lastName) ,
this.lastName = lastName;
45

-
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;
-
-
Step – 3 Create UserDao to Save Registered User into Database package
net.javaguides.hibernate.dao;

import org.hibernate.Session; import


org.hibernate.Transaction;

import net.javaguides.hibernate.model.User; import


net.javaguides.hibernate.util.HibernateUtil;

public class UserDao ,


46

public void saveUser(User user) , Transaction transaction = null; try


(Session session = HibernateUtil.getSessionFactory().openSession())
,
// start a transaction transaction =
session.beginTransaction();
// save the student object
session.save(user);
// commit transaction
transaction.commit(); -
catch (Exception e) , if
(transaction != null) ,
transaction.rollback();
-
e.printStackTrace();
-
-
-
Step – 4 Hibernate Java-Based Configuration package
net.javaguides.hibernate.util; import java.util.Properties; import
org.hibernate.SessionFactory; import
org.hibernate.boot.registry.StandardServiceRegistryBuilder; import
org.hibernate.cfg.Configuration; import
org.hibernate.cfg.Environment; import
47

org.hibernate.service.ServiceRegistry; import
net.javaguides.hibernate.model.User;
/**
* Java based configuration
* @author ramesh Fadatare
* */
public class HibernateUtil ,
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() ,
if (sessionFactory == null) , try ,
Configuration configuration = new Configuration();
// Hibernate settings equivalent to hibernate.cfg.xml's properties
Properties settings = new Properties();
settings.put(Environment.DRIVER, "com.mysql.jdbc.Driver");
settings.put(Environment.URL,
"jdbc:mysql://localhost:3306/demo?useSSL=false");
settings.put(Environment.USER, "root");
settings.put(Environment.PASS, "root");
settings.put(Environment.DIALECT,
"org.hibernate.dialect.MySQL5Dialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS,
"thread"); settings.put(Environment.HBM2DDL_AUTO,
"create-drop"); configuration.setProperties(settings);
configuration.addAnnotatedClass(User.class);
48

ServiceRegistry serviceRegistry = new


StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Java Config serviceRegistry created");
sessionFactory =
configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
- catch (Exception e) ,

e.printStackTrace();
-
-
return sessionFactory;
-
-
Step – 5 Create a UserController.java package
net.javaguides.hibernate.web;

import java.io.IOException;

import javax.servlet.RequestDispatcher; import


javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse;
49

import net.javaguides.hibernate.dao.UserDao; import


net.javaguides.hibernate.model.User;

/**
* @email Ramesh Fadatare
*/

@WebServlet("/register")
public class UserController extends HttpServlet , private
static final long serialVersionUID = 1 L; private UserDao
userDao;

public void init() ,


userDao = new UserDao();
-

protected void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException , register(request,
response);
-

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException ,
response.sendRedirect("register.jsp");
50

private void register(HttpServletRequest request, HttpServletResponse


response) throws IOException, ServletException ,
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String username = request.getParameter("username");
String password = request.getParameter("password");

User user = new User();


user.setFirstName(firstName);
user.setLastName(lastName);
user.setUsername(username);
user.setPassword(password);

userDao.saveUser(user);

RequestDispatcher dispatcher =
request.getRequestDispatcher("register-success.jsp");
dispatcher.forward(request, response);
-
-
Step – 6 Create a View - register.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
51

<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>

<link rel="stylesheet"

href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.
min.css"
integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZ
w1T" crossorigin="anonymous">
</head>

</head>
<body>
<div class="container">
<div class="row text-center" style="color: tomato;">
<h2>User Registration with JSP, Servlet and Hibernate</h2>
</div>
<hr>
<div class="row col-md-10 col-md-offset-3">

<div class="card card-body">

<h2>User Register Form</h2>


52

<div class="col-md-8 col-md-offset-3">

<form action="<%=request.getContextPath()%>/register" method="post">

<div class="form-group">
<label for="uname">First Name:</label> <input type="text"
class="form-control" id="uname" placeholder="First Name"
name="firstName" required>

</div>

<div class="form-group">
<label for="uname">Last Name:</label> <input type="text"
class="form-control" id="uname" placeholder="last Name"
name="lastName" required>
</div>

<div class="form-group">
<label for="uname">User Name:</label> <input type="text"
class="form-control" id="username" placeholder="User Name"
name="username" required>
</div>

<div class="form-group">
53

<label for="uname">Password:</label> <input type="password"


class="form-control" id="password" placeholder="Password"
name="password" required>
</div>

<button type="submit" class="btn btn-primary">Submit</button>

</form>
</div>
</div>
</div>
</div>
</body>
</html>
Step – 7 Create a View - register-success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>

<link rel="stylesheet"
54

href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.
min.css" integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZ
w1T" crossorigin="anonymous">
</head>

</head>
<body>
<div class="container">
<div class="row col-md-10 col-md-offset-3">
<div class="card card-body">
<h1>User successfully registered!</h1>
</div>
</div>
</div>
</body>
</html>
Step – 8 Run the Application and Demo OUTPUT:
55
56

Q-14 Write a program to implement MVC using Spring


Framework.

Step – 1 Create 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/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/springwebmvc -
->
<dependency>
57

<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>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>

</dependencies>
<build>
<finalName>SpringMVC</finalName>
</build>
</project>
Step – 2 Create the controller class package com.javatpoint; import
org.springframework.stereotype.Controller; import
org.springframework.web.bind.annotation.RequestMapping;
@Controller public class
HelloController ,
@RequestMapping("/")
public String display()
,
58

return "index";
-
-
Step – 3 Provide the entry of controller in the web.xml file
<?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>
Step – 4 Define the bean in the xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
59

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
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.javatpoint" />

<!--Provide support for conversion, formatting and validation -->


<mvc:annotation-driven/>

</beans>
Step- 5 Display the message in the JSP page
<html>
<body>
<p>Welcome to Spring MVC Tutorial</p>
</body>
</html>
60

You might also like