Advance Java File
Advance Java File
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));
}
/**
* @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:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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
<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.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();
/**
* @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>");
/**
* @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"%>
Index.jsp
OUTPUT:
Accept User.jsp
<%-- Set the value of the created bean using form data --%>
<jsp:setProperty name="dsm" property="user" />
<jsp:setProperty name="dsm" property="pass" />
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;
OUTPUT:
Add_num.jsp
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;
double pprice=Double.parseDouble(request.getParameter("price"));
int pqty=Integer.parseInt(request.getParameter("quantity"));
//MyProductBean product=new MyProductBean(pprice, pqty);
MyProductBean.java
package com.example;
//Simple Bean
public class MyProductBean { private double price; private int qty;
private double billAmt;
public MyProductBean() {
}
}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;
double pprice=Double.parseDouble(request.getParameter("price"));
int pqty=Integer.parseInt(request.getParameter("quantity"));
//MyProductBean product=new MyProductBean(pprice, pqty);
@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;
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
</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;
}
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 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
result.jsp
</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"/>'>
import com.example.dao.Admin;
import com.opensymphony.xwork2.ActionSupport;
@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";
}
<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 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;
}
import java.sql.ResultSet;
import com.example.dao.Admin;
import com.opensymphony.xwork2.ActionSupport;
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;
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.
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;
<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: