0% found this document useful (0 votes)
24 views65 pages

Advance Java File

The document outlines multiple servlet programs including an OddEvenServlet that checks if the sum of two numbers is odd or even, a HelloWorldServlet that displays a simple greeting, and cookie handling servlets for setting and getting cookies. It also includes a session tracking servlet that manages student data and a JSP page for user authentication. Each program is accompanied by necessary web.xml configurations and HTML forms for user interaction.

Uploaded by

MEGHDEEP KAUR
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)
24 views65 pages

Advance Java File

The document outlines multiple servlet programs including an OddEvenServlet that checks if the sum of two numbers is odd or even, a HelloWorldServlet that displays a simple greeting, and cookie handling servlets for setting and getting cookies. It also includes a session tracking servlet that manages student data and a JSP page for user authentication. Each program is accompanied by necessary web.xml configurations and HTML forms for user interaction.

Uploaded by

MEGHDEEP KAUR
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/ 65

Program 1: Create a Servlet to show that whether the added number

are Odd or Even

OUTPUT:

OddEvenServlet file

package com.example;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
* Servlet implementation class OddEvenServlet
*/
//@WebServlet("/OddEvenServlet")
public class OddEvenServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public OddEvenServlet() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at:
").append(request.getContextPath());
PrintWriter pw = response.getWriter();
int aa = Integer.parseInt(request.getParameter("a"));
int bb = Integer.parseInt(request.getParameter("b"));
int cc = aa + bb;
pw.write("Sum of Numbers is: " +cc+" and it is: "+ checkEven(cc));
}

private String checkEven(int cc) {


// TODO Auto-generated method stub
if (cc % 2 == 0)
return "Even";
else
return "Odd";
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}

Web.xml file

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://jakarta.ee/xml/ns/jakartaee"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd" version="6.0">
<servlet>
<description/>
<display-name>OddEvenServlet</display-name>
<servlet-name>OddEvenServlet</servlet-name>
<servlet-class>com.example.OddEvenServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>OddEvenServlet</servlet-name>
<url-pattern>/OddEvenServlet</url-pattern>
</servlet-mapping>
<display-name>ServletSumOddEvenCheck</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

Index.xml file
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Demonstration of HttpServletRequest and HttpServletResponse</h2>
<form action="OddEvenServlet" method="post">
Enter A: <input type="text" name="a" /><br /> Enter B: <input
type="text" name="b" /><br /> <input type="submit"
name="Submit"
value="Check Sum Even or Odd" />
</form>
</body>
</html>
Program 2: Create a Simple Hello World Application in Servlet.

OUTPUT:

1. First, create a Java class that extends HttpServlet:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().println("<html><head><title>Hello World
Servlet</title></head><body>");
response.getWriter().println("<h1>Hello World!</h1>");
response.getWriter().println("</body></html>");
}
}

2. Next, you need to map this servlet in the web.xml deployment descriptor file. Here's
how you do it:
Create a web.xml file in the WEB-INF directory of your web application if it
doesn't exist, and add the following configuration

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


<web-app 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"
version="4.0">

<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

</web-app>
Program 3: Implementation of the concept of Cookies.

OUTPUT:

GetCookie Servlet

package com.example;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
* Servlet implementation class GetCookieServlet
*/
public class GetCookieServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public GetCookieServlet() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at:
").append(request.getContextPath());
try {
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();

// Reading cookies
Cookie c[] = request.getCookies();
// Displaying User name value from cookie

pwriter.print("Cookie1 UserName: " + c[0].getValue());


// Displaying user password value from cookie
pwriter.print("<br/> Cookie2 UserPassword: " +
c[1].getValue()+"<br/>");

//Alternative Code to print Cookie Name and Cookie Value


for(int i=0;i<c.length;i++)
pwriter.print("CookieName: "+c[i].getName()+" &
CookieValue: "+c[i].getValue()+"<br/>");
pwriter.close();

pwriter.close();
} catch (Exception exp) {
System.out.println(exp);
}
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}

SetCookie Servlet
package com.example;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
* Servlet implementation class SetCookieServlet
*/
public class SetCookieServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public SetCookieServlet() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at:
").append(request.getContextPath());
try {
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();

String name = request.getParameter("userName");


String password = request.getParameter("userPassword");
pwriter.print("Hello " + name);
pwriter.print(" Your Password is: " + password);

// Creating two cookies


Cookie c1 = new Cookie("userName", name);
Cookie c2 = new Cookie("userPassword", password);

// Adding the cookies to response header


response.addCookie(c1);
response.addCookie(c2);
pwriter.print("<h2> Welcome User!!! </h2>");
pwriter.print("<br><a href='GetCookieServlet'> Get
Cookies</a>");
pwriter.close();
} catch (Exception exp) {
System.out.println(exp);
}
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}

Web.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://jakarta.ee/xml/ns/jakartaee"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd" version="6.0">
<servlet>
<description/>
<display-name>SetCookieServlet</display-name>
<servlet-name>SetCookieServlet</servlet-name>
<servlet-class>com.example.SetCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SetCookieServlet</servlet-name>
<url-pattern>/SetCookieServlet</url-pattern>
</servlet-mapping>
<display-name>ServletGetSetCookies</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description/>
<display-name>GetCookieServlet</display-name>
<servlet-name>GetCookieServlet</servlet-name>
<servlet-class>com.example.GetCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetCookieServlet</servlet-name>
<url-pattern>/GetCookieServlet</url-pattern>
</servlet-mapping>
</web-app>
Program 4: Implementation of the Concept of Session Tracking

OUTPUT:

SessionTracking Servlet

package servlets;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import models.Student;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
/**
* Servlet implementation class StudentServlet
*/
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public StudentServlet() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at:
").append(request.getContextPath());
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet StudentServlet</title>");
out.println("</head>");
out.println("<body>");

// List to hold Student objects


ArrayList<Student> std = new ArrayList<Student>();

// Adding members to the list. Here we are


// using the parameterized constructor of
// class "Student.java"
std.add(new Student("Daljeet Singh", 44, "PhD"));
std.add(new Student("Amanpartap Singh", 43, "B.Tech"));
std.add(new Student("Prabhjot Kaur", 40, "MSc"));
std.add(new Student("Rohit Verma", 44, "M.Tech"));
std.add(new Student("Harmandeep Singh", 24, "M.B.B.S"));

// Setting the attribute of the request object


// which will be later fetched by a JSP page
request.setAttribute("data", std);

// Creating a RequestDispatcher object to dispatch


// the request the request to another resource
RequestDispatcher rd =
request.getRequestDispatcher("stdlist.jsp");

// The request will be forwarded to the resource


// specified, here the resource is a JSP named,
// "stdlist.jsp"
rd.forward(request, response);
out.println("</body>");
out.println("</html>");
}
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}

Stdlist.jsp

<%@page import="models.Student"%>
<%@page import="java.util.ArrayList"%>

<%@ page contentType="text/html; charset=ISO-8859-1"%>


<%@ 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>
</head>
<body>
<h1>Displaying Student List</h1>
<table border="1" width="500" align="center">
<tr bgcolor="00FF7F">
<th><b>Student Name</b></th>
<th><b>Student Age</b></th>
<th><b>Course Undertaken</b></th>
</tr>
<%-- Fetching the attributes of the request object
which was previously set by the servlet
"StudentServlet.java"
--%>
<%
ArrayList<Student> std = (ArrayList<Student>)
request.getAttribute("data");
for (Student s : std) {
%>
<%-- Arranging data in tabular form --%>
<tr>
<td><%=s.getName()%></td>
<td><%=s.getAge()%></td>
<td><%=s.getCourse()%></td>
</tr>
<%
}
%>
</table>
<hr />
</body>
</html>

Index.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>JSP Session Tracking</title>
</head>
<body>
<form action="StudentServlet">
<pre>
Demonstration of Getting Attribute Values in JSP
Student Data is stored in a session variable of type ArrayList using
setAttribute()
and displayed using getAttribute() in JSP
</pre>
<input type="submit" value="Get Data">
</form>
</body>
</html>
Program 5: Create a Servlet to authenticate the User Credentials in
JSP.

OUTPUT:

Accept User.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>Accept User Page</title>
</head>
<body>
<h1>Verifying Details</h1>
<%-- Include the ValidateUser.java class whose method
boolean validate(String, String) we will be using
--%>
<%-- Create and instantiate a bean and assign an id to
uniquely identify the action element throughout the jsp
--%>
<jsp:useBean id="dsm" class="model.ValidateUser" />

<%-- Set the value of the created bean using form data --%>
<jsp:setProperty name="dsm" property="user" />
<jsp:setProperty name="dsm" property="pass" />

<%-- Display the form data --%>


The Details Entered Are as Under
<br />
<p>
Username :
<jsp:getProperty name="dsm" property="user" /></p>
<p>
Password :
<jsp:getProperty name="dsm" property="pass" /></p>

<%-- Validate the user using the validate() of


ValidateUser.java class
--%>
<%
if (dsm.validate("MeghSukh", "MeghSukh1313")) {
%>
Welcome! You are a VALID USER
<br />
<%
} else {
%>
Error! You are an INVALID USER
<br />
<%
}
%>
</body>
</html>
Index.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>Login Page</title>
</head>
<body>
<h1>User Details</h1>
<h2>User Validation in JSP</h2>
<%-- The form data will be passed to acceptuser.jsp
for validation on clicking submit
--%>

<form method="get" action="acceptuser.jsp">


Enter Username : <input type="text" name="user"><br /> <br />
Enter Password : <input type="password" name="pass"><br /> <input
type="submit" value="SUBMIT">
</form>
</body>
</html>
Program 6: Create a Program to implement the concept of Get Set
Session.

OUTPUT:

Index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Servlet Session Management</title>
</head>
<body>
<form action="SetSessionServlet">
User Name:<input type="text" name="userName" /><br />
Password:<input
type="password" name="userPassword" /><br /> <input
type="submit"
value="Set Session Data" />
</form>
</body>
</html>

Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://jakarta.ee/xml/ns/jakartaee"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd" version="6.0">
<display-name>ServletSetGetSession1</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.jsp</welcome-file>
<welcome-file>default.htm</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>UseSessionServlet</display-name>
<servlet-name>UseSessionServlet</servlet-name>
<servlet-class>com.example.UseSessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UseSessionServlet</servlet-name>
<url-pattern>/UseSessionServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>SetSessionServlet</display-name>
<servlet-name>SetSessionServlet</servlet-name>
<servlet-class>com.example.SetSessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SetSessionServlet</servlet-name>
<url-pattern>/SetSessionServlet</url-pattern>
</servlet-mapping>
</web-app>
Program 7: Create a Servlet to handle HTTP Requests and Responses.

OUTPUT:

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");

// Create HTML content to be sent as the response


String htmlResponse = "<html><head><title>Hello
Servlet</title></head><body>";
htmlResponse += "<h1>Hello, Servlet!</h1>";
htmlResponse += "<p>This is a simple servlet example.</p>";
htmlResponse += "</body></html>";

// Write the HTML content to the response


response.getWriter().write(htmlResponse);
}
}
Program 8: Create a Servlet to Add Two Numbers on Server side and
display the result on Client Side.

OUTPUT:

Add_num.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%! int a, b, c; %>
<%
try{
a=Integer.parseInt(request.getParameter("a"));
b=Integer.parseInt(request.getParameter("b"));
}catch(Exception e){
out.print(e);
}
%>
<h1>Add Two Numbers JSP Example</h1>
<% c=a+b;
%>
<h3>Sum of a and b is:<%= c %></h3>
</body>
</html>

Index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Add Two Numbers in JSP</title>
</head>
<body>
<form action="add_num.jsp" method="post">
Enter A: <input type="text" name="a"><br /> Enter B: <input
type="text" name="b"><br />
<input type="submit" name="submit" value="ADD">
</form>
</body>
</html>
Program 9: Illustrate the concept of Java Server Pages (JSP).

OUTPUT:

index.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>
</head>
<body>
This is my Home Page
<form action="LoginServ" method="post">
Enter username:<input type="text" name="username"><br>
<br>
Enter password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>jsp</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>com.example.LogServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>

LoginServlet.java
package com.example;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public LogServ() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.getWriter().append("Served at:
").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{ // TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out= response.getWriter(); String
n=request.getParameter("username");String
p=request.getParameter("password");
if(n.equals("Parveen") && p.equals("123456"))
{
out.write("<h2>We are MCA Students</h2>");
out.write("Hello " +n);
}
else
{
out.print("Sorry username or password error");
}
}
}
Program 10: Create a JavaBean by using Bean Developer Kit (BDK).
index.html
<!DOCTYPE html>

<html>

<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div><h1>Calculating Bill using Simple Bean</h1></div>
<!--Simply Replace the value of action to -->
<form action="SBServlet" method="POST">
Enter Price: <input type="text" name="price" placeholder="Enter Price"/><br/>
Enter Quantity: <input type="text" name="quantity" placeholder="Enter Quantity"/><br/>
<input type="submit" value="Click to Generate Bill"/><br/>

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

BillServletSB.java
package com.example;

import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
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(name = "BillServletSB", urlPatterns = {"/SBServlet"})


public class BillServletSB extends HttpServlet {

//EJB Stateless implementation

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException { response.setContentType("text/html;charset=UTF-
8");

double pprice=Double.parseDouble(request.getParameter("price"));
int pqty=Integer.parseInt(request.getParameter("quantity"));
//MyProductBean product=new MyProductBean(pprice, pqty);

MyProductBean product=new MyProductBean();


product.setPrice(pprice); product.setQty(pqty); product.calBill();
System.out.println("Bill"+product.getBillAmt());

try (PrintWriter out = response.getWriter()) {


/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>"); out.println("<head>");
out.println("<title>BillServlet Simple Bean</title>"); out.println("</head>");
out.println("<body>");
out.println("<h1>Your Bill calculated using Simple Bean is:"+product.getBillAmt() +
"</h1>");
out.println("</body>"); out.println("</html>");
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

MyProductBean.java
package com.example;

//Simple Bean
public class MyProductBean { private double price; private int qty;
private double billAmt;

public double getPrice() {


return price;
}

public void setPrice(double price) {


this.price = price;
}

public int getQty() {


return qty;
}
public void setQty(int qty) {
this.qty = qty;
}

public double getBillAmt() {


return billAmt;
}

public void setBillAmt(double billAmt) {


this.billAmt = billAmt;
}

public MyProductBean() {
}

public MyProductBean(double price, int qty) {


this.price = price;
this.qty = qty;
}
public void calBill(){
this.billAmt= this.price*this.qty;
}

}OUTPUT:
Program11: Implementation of various types of beans like Session Bean and
Entity Bean.

index.html
<!DOCTYPE html>

<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div><h1>Calculating Bill using Enterprise Java Bean(EJB)</h1></div>
<!--Simply Replace the value of action to -->
<form action="EJBServlet1" method="POST">
Enter Price: <input type="text" name="price" placeholder="Enter Price"/><br/>
Enter Quantity: <input type="text" name="quantity" placeholder="Enter Quantity"/><br/>
<input type="submit" value="Click to Generate Bill"/><br/>

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

BillServletEJB.java
package com.example;

import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJB;


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(name = "BillServletEJB", urlPatterns = {"/EJBServlet1"})


public class BillServletEJB extends HttpServlet {

//EJB Stateless implementation @EJB


BillSessionBean product;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html;charset=UTF-
8");

double pprice=Double.parseDouble(request.getParameter("price"));
int pqty=Integer.parseInt(request.getParameter("quantity"));
//MyProductBean product=new MyProductBean(pprice, pqty);

//MyProductBean product=new MyProductBean();


product.setPrice(pprice); product.setQty(pqty); product.calBill();
System.out.println("Bill"+product.getBillAmt());

try (PrintWriter out = response.getWriter()) {


/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>"); out.println("<head>");
out.println("<title>BillServlet EJB</title>"); out.println("</head>"); out.println("<body>");
out.println("<h1>Your Bill using EJB is:"+product.getBillAmt() +
"</h1>");
out.println("</body>"); out.println("</html>");
}
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { processRequest(request, response);
}

@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

BillSessionBean.java
package com.example;

import javax.ejb.Stateless;

//for EJB application @Stateless


public class BillSessionBean {

// Add business logic below. (Right-click in editor and choose


// "Insert Code > Add Business Method")
private double price; private int qty; private double billAmt;

public BillSessionBean(double price, int qty) {


this.price = price;
this.qty = qty;
}
public BillSessionBean() {
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQty() {
return qty;
}

public void setQty(int qty) {


this.qty = qty;
}

public double getBillAmt() {


return billAmt;
}

public void setBillAmt(double billAmt) {


this.billAmt = billAmt;
}

public void calBill(){ billAmt=this.price*this.qty;


}

OUTPUT:
Program 12: Introduction to Struts platform with basic connectivity.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>Struts2LoginDBApp</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class> org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="login" class="com.example.LogIn">
<result name="success">/stu_details.jsp</result>
<result name="failure">/error.jsp</result>
</action>
<action name="register" class="com.example.Student">
<result name="success">/welcome.jsp</result>
<result name="failure">/error.jsp</result>
</action>
</package>
</struts>
login.jsp

<%@ taglib uri="/struts-tags" prefix="s" %>


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login</title>
</head>
<body>
<div style="align:center">
<h1>Student Login Form</h1>
<s:form action="login" method="post">
<s:textfield name="stuname" label="User Name"/>
<s:password name="stupass" label="Password"/>
<s:submit value="Login"/>
<s:reset value="Reset"/>
</s:form>
<a href="register.jsp">New User Register Here</a>
</div>

</body>
</html>

error.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>Error</title>
</head>
<body>
There is Error in User name/Password
</body>
</html>
register.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Student Registration</title>
</head>
<body>
<div align="center">
<h1>Student Registration Form</h1>
<s:form action="register" >
<s:textfield name="stuname" label="Student Name" />
<s:textfield name="rollno" label="Roll Number" />
<s:textfield name="course" label="Course" />
<s:textfield name="technology" label="Technology" />
<s:textfield name="city" label="City" />
<s:password name="stupass" label="Password"/>
<s:submit value="Save Details"/>
</s:form>
</div>
</body>
</html>
welcome.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Welcome</title>
</head>
<body>
Welcome <s:property value="stuname"/>
Your details are saved to the database successfully Congratulations!!!
<a href="login.jsp">Goto Login Page</a>

</body>
</html>
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getTechnology() {
return technology;
}
public void setTechnology(String technology) {
this.technology = technology;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStupass() {
return stupass;
}
public void setStupass(String stupass) {
this.stupass = stupass;
}

public String execute() {


try {
Connection con=DBConnection.getConnection();
String sql="select * from student where stuname=? and stupass=?"; PreparedStatement
ps=con.prepareStatement(sql); ps.setString(1, getStuname());
ps.setString(2, getStupass());

ResultSet rs=ps.executeQuery();
if(rs.next()) {
setStuname(rs.getString("stuname")); setRollno(rs.getInt("rollno"));
setCourse(rs.getString("course")); setTechnology(rs.getString("technology"));
setCity(rs.getString("city")); setStupass(rs.getString("stupass")); return "success";
}
else {
return "failure";
}

}catch(Exception e) {
e.printStackTrace();
}
return "failure";
}

}
Student.java
package com.example;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class Student { private String stuname; private int rollno; private String course;
private String technology; private String city; private String stupass;

public String getStuname() {


return stuname;
}
public void setStuname(String stuname) {
this.stuname = stuname;
}
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getTechnology() {
return technology;
}
public void setTechnology(String technology) {
this.technology = technology;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStupass() {
return stupass;
}
public void setStupass(String stupass) {
this.stupass = stupass;
}
public Student() {
super();

}
public Student(String stuname, int rollno, String course, String technology, String city, String
stupass) {
super();
this.stuname = stuname;
this.rollno = rollno; this.course = course; this.technology = technology; this.city = city;
this.stupass = stupass;
}
@Override
public String toString() {
return "Student [stuname=" + stuname + ", rollno=" + rollno + ", course=" + course + ",
technology="+ technology + ", city=" + city + ", stupass=" + stupass + "]";
}
public String execute() {
int i=0;
try {
Connection con=DBConnection.getConnection();
String sql="insert into student(stuname,rollno,course,technology,city,stupass)
values(?,?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(sql); ps.setString(1, getStuname());
ps.setInt(2, getRollno()); ps.setString(3, getCourse()); ps.setString(4, getTechnology());
ps.setString(5, getCity()); ps.setString(6, getStupass()); int n=ps.executeUpdate();
System.out.println("No Error after insertion. Record inserted:
"+n);
}catch(Exception e) {
e.printStackTrace();
}
if(i==0)
return "success";
else
return "failure";
}

OUTPUT:
Program 13: Deploying first sample program using MVC architecture in struts.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>Struts2App</display-name>
<welcome-file-list>
<welcome-file>input.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name> struts2
</filter-name>
<filter-class> org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="Struts2App" extends="struts-default">
<action name="calculateSumAction" class="com.struts.SumAction" method="calculate">
<result name="success">/result.jsp</result>
<result name="input">/input.jsp</result>
</action>
</package>
</struts>
input.jsp

<%@ taglib uri="/struts-tags" prefix="s" %>


<%@ 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>
</head>
<body>
<h1>Addition Of 2 Numbers</h1>
<s:form action="calculateSumAction" method="post">
<s:textfield name="a" size="10" label="Enter A" />
<s:textfield name="b" size="10" label="Enter B" />
<s:submit value="Add" />
</s:form>
</body>
</html>

result.jsp

<%@ taglib uri="/struts-tags" prefix="s" %>


<%@ 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>
</head>
<body>
<h2> Sum of Two Numbers</h2>
Sum is <s:property value="sum" />

</body>
</html>
package com.struts;

import com.opensymphony.xwork2.ActionSupport;
public class SumAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private int a; private int b; private int sum;
public String calculate() { sum=a+b;
//String SUCCESS = null;
return SUCCESS;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
public int getSum() {
return sum;
}
public void setSum() {
this.sum= sum;
}
}

SumAction.java
OUTPUT:
Program 14: Implementing database connectivity in struts.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>Struts2CRUD</display-name>
<welcome-file-list>
<welcome-file>register.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter- class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-
class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="registeruser" class="com.example.action.RegisterAction">
<result name="REGISTER">/register.jsp</result>
</action>
<action name="select" class="com.example.action.SelectAction">
<result name="SELECT">/select.jsp</result>
</action>
<action name="updatedetails" class="com.example.action.UpdateAction">
<result name="UPDATE">/update.jsp</result>
</action>
<action name="deleterecord" class="com.example.action.DeleteAction">
<result name="DELETE">/delete.jsp</result>
</action>
</package>
</struts>
register.jsp
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<style type="text/css">
.button-register {
background-color: green; color: white;
}
.button-select {
background-color: #000000; color: white;
margin-left: 30%;
}
</style>
</head>
<body>
<h2>Struts 2 Create, Read, Update and Delete (CRUD) Example using JDBC</h2>
<a href="select"><button class="button-select" type="button">Select</button></a>
<s:form action="registeruser" method="post">
<s:textfield label="Full Name" name="uname" />
<s:textfield label="Email" name="uemail" />
<s:password label="Password" name="upass" />
<s:textfield label="Designation" name="udeg" />
<s:submit cssClass="button-register" value="Register" />
</s:form>
<s:if test="ctr>0">
<span style="color: green;"><s:property value="msg" /></span>
</s:if>
<s:else>
<span style="color: red;"><s:property value="msg" /></span>
</s:else>
</body>
</html>
select.jsp
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>Select</title>
<style>
table, td, th {
border: 1px solid black;
}

table {
border-collapse: collapse;
width: 60%; height: 30px;
}
th {

.button-update {
background-color: #008CBA; color: white;
}

.button-delete {
background-color: red; color: white;
}
</style>
</head>
<body>
<h2>Struts 2 Create, Read, Update and Delete (CRUD) Example using JDBC</h2>
<div style="margin-top: 40px;">
<s:if test="noData==true">
<table>
<thead>
<tr style="background-color: #E0E0E1;">
<th>Sr.No.</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
<th>Designation</th>
<th>Action</th>
</tr>
</thead>
<s:iterator value="beanList">
<tr>
<td><s:property value="srNo" /></td>
<td><s:property value="uname" /></td>
<td><s:property value="uemail" /></td>
<td><s:property value="upass" /></td>
<td><s:property value="udeg" /></td>
<td><a

href="updatedetails.action?submitType=updatedata&uemail=<s:property value="uemail"/>">
<button class="button-
update">Update</button> </a> <a

href="deleterecord.action?uemail=<s:property value="uemail"/>">
<button class="button-
delete">Delete</button>
</a></td>
</tr>
</s:iterator>
</table>
</s:if>
<s:else>
<div style="color: red;">No Data Found.</div>
</s:else>
<br> <a href="register.jsp"><button class="button-register"
type="button">Register</button></a>
</div>
</body>
</html>

update.jsp
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>Update</title>
</head>
<body>
<h2>Struts 2 Create, Read, Update and Delete (CRUD) Example using JDBC</h2>
<form action=updatedetails method="post">
<pre>
<b>Name: </b><input type="text" name="uname"
value='<s:property value="uname"/>'>
<b>Email: </b><input type="email" name="uemail"
value='<s:property value="uemail"/>'>
<input type="hidden" name="uemailhidden" value='<s:property value="uemail"/>'>
<b>Password: </b><input type="password" name="upass"
value='<s:property value="upass"/>'>

<b>Designation: </b><input type="text" name="udeg"


value='<s:property value="udeg"/>'>
<button name="submitType" value="update" type="submit">Update</button>
</pre>
</form>
<s:if test="ctr>0">
<span style="color: red;"><s:property value="msg" /></span>
</s:if>
<s:else>
<span style="color: red;"><s:property value="msg" /></span>
</s:else>
<br>
<a href="select"><button class="button-select" type="button">Select</button></a>
</body>
</html>
package com.example.action;

import com.example.dao.Admin;
import com.opensymphony.xwork2.ActionSupport;

public class DeleteAction extends ActionSupport{


/**
*
*/
private static final long serialVersionUID = 1L;

String uemail, msg; Admin dao = new Admin();

@Override
public String execute() throws Exception {
try {
int isDeleted = dao.deleteUserDetails(uemail);
if (isDeleted > 0) {
msg = "Record deleted successfully";
} else {
msg = "Some error";
}
} catch (Exception e) { e.printStackTrace();
}
return "DELETE";
}

public String getUemail() {


return uemail;
}

public void setUemail(String uemail) {


this.uemail = uemail;
}

public String getMsg() {


return msg;
}

<span><s:property
public value="msg"
void setMsg(String msg) {/></span><br><br>
<a href="select">
this.msg = msg;
}<button type="button">Select</button>
}
</a>
</body>
</html>
RegisterAction.java
package com.example.action;
import com.example.dao.Admin;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private String uname, uemail, upass, udeg;
private String msg = ""; Admin admin = null;
int ctr = 0;
public String execute() throws Exception { admin = new Admin();
try {
ctr = admin.registerUser(uname, uemail, upass, udeg);
if (ctr > 0) {
msg = "Registration Successfull";
} else {
msg = "Some error";
}
} catch (Exception e) { e.printStackTrace();
}
return "REGISTER";
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUemail() {
return uemail;
}
public void setUemail(String uemail) {
this.uemail = uemail;
}
public String getUpass() {
return upass;
}
public void setUpass(String upass) {
this.upass = upass;
}
public String getUdeg() {
return udeg;
SelectAction.java
package com.example.action;

import java.sql.ResultSet; import java.util.ArrayList; import java.util.List;

import com.example.bean.UserBean;
import com.example.dao.Admin;
import com.opensymphony.xwork2.ActionSupport;

public class SelectAction extends ActionSupport { private static final long serialVersionUID
= 1L; ResultSet rs = null;
UserBean bean = null; List<UserBean> beanList = null; Admin admin = new Admin();
private boolean noData = false; @Override
public String execute() throws Exception {
try {
beanList = new ArrayList<UserBean>(); rs = admin.select();
int i = 0;
if (rs != null) {
while (rs.next()) {
i++;
bean = new UserBean(); bean.setSrNo(i); bean.setUname(rs.getString("UNAME"));
bean.setUemail(rs.getString("UEMAIL"));

bean.setUpass(rs.getString("UPASS").replaceAll("(?s).", "*"));
bean.setUdeg(rs.getString("UDEG"));beanList.add(bean);
}
}
if (i == 0) {
noData = false;
} else {
noData = true;
}
} catch (Exception e) { e.printStackTrace();
}
return "SELECT";
}
public List<UserBean> getBeanList() {
return beanList;
}

public void setBeanList(List<UserBean> beanList) {


this.beanList = beanList;
}

public boolean isNoData() {


return noData;
}

public void setNoData(boolean noData) {


this.noData = noData;
UpdateAction.java
package com.example.action;

import java.sql.ResultSet;

import com.example.dao.Admin;
import com.opensymphony.xwork2.ActionSupport;

public class UpdateAction extends ActionSupport {


private static final long serialVersionUID = 1L;
private String uname = "", uemail = "", upass = "", udeg = "", uemailhidden = "";
private String msg = ""; ResultSet rs = null; Admin dao = new Admin(); String submitType;
@Override
public String execute() throws Exception {
try {
if (submitType.equals("updatedata")) {
rs = dao.fetchUserDetails(uemail.trim());
if (rs != null) {
while (rs.next()) {
uname = rs.getString("UNAME"); uemail = rs.getString("UEMAIL");
Userbean.java
package com.example.bean;

public class UserBean {


// generate getter and setters
private String uname, uemail, upass, udeg;
int srNo;

public String getUname() {


return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUemail() {
return uemail;
}
public void setUemail(String uemail) {
this.uemail = uemail;
}
public String getUpass() {
return upass;
}
public void setUpass(String upass) {
this.upass = upass;
}
public String getUdeg() {
return udeg;
}
public void setUdeg(String udeg) {
this.udeg = udeg;
}
public int getSrNo() {
return srNo;
}
public void setSrNo(int srNo) {
this.srNo = srNo;
}
Admin.java
package com.example.dao;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Admin {
// method for create connection
public static Connection getConnection() throws Exception {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
return
DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/strut", "root", "1999");
} catch (Exception e) { e.printStackTrace(); return null;
}
}
// method for save user data in database
public int registerUser(String uname, String uemail, String upass, String udeg) throws Exception {
int i = 0;
try
{
String sql = "INSERT INTO struts2crud VALUES (?,?,?,?)"; PreparedStatement ps =
getConnection().prepareStatement(sql);
ps.setString(1, uname); ps.setString(2, uemail); ps.setString(3, upass); ps.setString(4, udeg); i =
ps.executeUpdate(); return i;
} catch (Exception e) { e.printStackTrace(); return i;
} finally {
if (getConnection() != null) {
getConnection().close();
}
}
}
// method for fetch saved user data
public ResultSet select() throws SQLException, Exception { ResultSet rs = null;
try {
String sql = "SELECT UNAME,UEMAIL,UPASS,UDEG FROM
struts2crud";
PreparedStatement ps =
getConnection().prepareStatement(sql);
rs = ps.executeQuery();
return rs;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (getConnection() != null) {
getConnection().close();
}
}
}
// method for fetch old data to be update
public ResultSet fetchUserDetails(String uemail) throws
SQLException, Exception {
ResultSet rs = null; try {
String sql = "SELECT UNAME,UEMAIL,UPASS,UDEG FROM
struts2crud WHERE UEMAIL=?";
PreparedStatement ps =
getConnection().prepareStatement(sql);
ps.setString(1, uemail); rs = ps.executeQuery(); return rs;
} catch (Exception e) { e.printStackTrace(); return null;
} finally {
if (getConnection() != null) {
getConnection().close();
}
}
}
// method for update new data in database
public int updateUserDetails(String uname, String uemail, String upass, String udeg, String
uemailhidden)
throws SQLException, Exception { getConnection().setAutoCommit(false); int i = 0;
try {
String sql = "UPDATE struts2crud SET UNAME=?,UEMAIL=?,UPASS=?,UDEG=? WHERE
UEMAIL=?";
PreparedStatement ps =
getConnection().prepareStatement(sql);
ps.setString(1, uname); ps.setString(2, uemail); ps.setString(3, upass); ps.setString(4, udeg);
ps.setString(5, uemailhidden); i = ps.executeUpdate();
return i;
} catch (Exception e) { e.printStackTrace(); getConnection().rollback(); return 0;
} finally {
if (getConnection() != null) {
getConnection().close();
}
}
}
// method for delete the record
public int deleteUserDetails(String uemail) throws SQLException, Exception {
getConnection().setAutoCommit(false);
int i = 0;
try {
String sql = "DELETE FROM struts2crud WHERE UEMAIL=?"; PreparedStatement ps =
getConnection().prepareStatement(sql);
ps.setString(1, uemail); i = ps.executeUpdate(); return i;
} catch (Exception e) { e.printStackTrace(); getConnection().rollback(); return 0;
} finally {
if (getConnection() != null) {
getConnection().close();
}
}
}
}

OUTPUT:
Program 15: Creating one sample application in struts.

index.jsp
<%@ taglib uri="/struts-tags" prefix="a" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Bill Of Product</title>
</head>
<body>
<center>
<a:form action="product" style=" background-color:pink; ">
<h1>Bill OF PRODUCTS</h1>
<a:textfield label="Enter Product Price" name="one" ></a:textfield>
<a:textfield label="Quantity" name="two"></a:textfield>
<a:submit value="Submit" style="margin-left:140px;"></a:submit>
</a:form>
</center>
</body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>firststruts1</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class> org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="a" %>
<!DOCTYPE html>

<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<DIV style="color:white; background-color:grey; font-size:20px;">
<h1>BILL Calculator</h1>
<hr>
Product Price:<a:property value="one"/><BR> Product Quantity:<a:property
value="two"/><BR>
Product Total price:<a:property value="price"/><BR>
</DIV>
</center>
</body>
</html>

struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="product" class="com.example.ProductAction">
<result name="success"> welcome.jsp
</result>
</action>
</package>
</struts>
ProductAction.java
package com.example;

import com.opensymphony.xwork2.ActionSupport;

public class ProductAction extends ActionSupport{

private static final long serialVersionUID = 1L;


private int one; private int two; private float price; public int getOne() {
return one;
}
public void setOne(int one) {
this.one = one;
}
public int getTwo() {
return two;
}
public void setTwo(int two) {
this.two = two;
}

public float getPrice() {


return price;
}
public void setPrice(float price) {
this.price = price;
}
public String execute() { price=one*two; return "success";
}

OUTPUT:
Program 16: Introduction to Hibernate framework.

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.

ORM Tool
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.
What is JPA?
Java Persistence API (JPA) is a Java specification that provides certain
functionality and standard to ORM tools. The javax.persistence package
contains the JPA classes and interfaces.
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.
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.
Need of Hibernate Framework
Hibernate is used to overcome the limitations of JDBC like:
1. JDBC code is dependent upon the Database software being used i.e. our
persistence logic is dependent, because of using JDBC. Here we are
inserting a record into Employee table but our query is Database software-
dependent i.e. Here we are using MySQL. But if we change our Database
then this query won’t work.

2. If working with JDBC, changing of Database in middle of the project is


very costly.
3. JDBC code is not portable code across the multiple database software.
4. In JDBC, Exception handling is mandatory. Here We can see that we are
handling lots of Exception for connection.

5. While working with JDBC, There is no support Object-level relationship.


6. In JDBC, there occurs a Boilerplate problem i.e. For each and every project
we have to write the below code. That increases the code length and reduce
the readability.

To overcome the above problems we use ORM tool i.e. nothing but Hibernate
framework. By using Hibernate we can avoid all the above problems and we
can enjoy some additional set of functionalities.
Program 17: Creating simple Hibernate application.
<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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>HibernateProjWithMaven1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.32.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
</dependencies>
</project>

App.java
package com.example;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class App {

public static void main(String[] args) {


// TODO Auto-generated method stub System.out.println("Project Started");

SessionFactory factory=new Configuration().configure().buildSessionFactory();


System.out.println(factory); System.out.println(factory.isClosed());
}
}
hibernate.cfg.xml

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


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/mydb1</property>
<property name="connection.username">root</property>
<property name="connection.password">1999</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>

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

OUTPUT:

You might also like