Advance Java Assignment
Advance Java Assignment
Algorithm :-
Step 1 :- Start
Step 2 :- Send request from html page.
Step 3 :- Create a Class and extend HttpServlet Class.
Step 4 :- Define service() method and declare IOException.
Step 5 :- Take parameter using HttpServletRequest object getParameter()
method.
Step 6 :- Show the values using PrintWriter object which is returned from the
HttpServletResponse Object’s getWriter() method.
Step 7 :- Stop
Source Code :-
Index.html :-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="input">
Name:<input type="text" name="a"><br>
Age:<input type="text" name="b"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Servlet :-
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("/input")
public class Main extends HttpServlet{
public void service(HttpServletRequest re,HttpServletResponse rs) throws IOException {
rs.getWriter().print("Name="+re.getParameter("a")+"<br>Age="+re.getParameter("b"));
}
}
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>A1</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>
Output :-
Discussion :-
We have sent a request to the servlet using get method from index.html file. Then we took the input
from the HttpServletRequest object using the getParameter() method, after that we print the data
using the PrintWriter object’s print() method which we got from the HttpServletResponse object.
The IOException is declared and it tells that IOException might occur due to failed or interrupted I/O
operations.
Assignment 2 :-
Write a program to display the image using servlet.
Algorithm :-
Step 1 :- Start
Step 2 :- Send request from html page.
Step 3 :- Create a Class and extend HttpServlet Class and declare IOException.
Step 4 :- Define service() method.
Step 5 :- When Servlet is called get HttpServletResponse object.
Step 6 :- Show the image using PrintWriter object obtained from
HttpServletResponse object’s getWriter() method.
Step 7 :- Stop
Source Code :-
Index.html :-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="showImg"><input type="submit" value="Show Image"></form>
</body>
</html>
Servlet :-
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("/showImg")
public class Main extends HttpServlet{
public void service(HttpServletRequest re,HttpServletResponse rs) throws IOException {
String img="welcome.png";
rs.getWriter().print("<!DOCTYPE html><html><head></head><body><img
src="+img+"></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>A2</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>
Output :-
Discussion :-
We have sent a request to the servlet using get method from index.html file, when we got the
request we show the image using PrintWriter object’s print() method which we got from the
HttpServletResponse object. The IOException is declared and it tells that IOException might occur
due to failed or interrupted I/O operations.
Assignment 3 :-
Write an program on session tracking to print session
Id , session creation time and last accessed time.
Algorithm:-
Step 1 :- Start
Step 2 :- Create a Class and extend HttpServlet Class and declare IOException.
Step 3 :- Define service() method.
Step 4 :- When Servlet is called get HttpServletResponse object.
Step 5 :- Get the Session Object from HttpServletResponse object using
getSession() method.
Step 6 :- Print the session id ,creation time, last accessed time using
HttpServletResponse object’s getWriter() method.
Step 7 :- Stop
Source Code :-
Servlet Code:-
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/servlet")
public class Main extends HttpServlet {
public void service(HttpServletRequest req,HttpServletResponse res) throws
IOException {
HttpSession s=req.getSession();
res.getWriter().println(
"Session Id : "+s.getId()+
"<br>Creation Time : "+s.getCreationTime()+
"<br>Last Accessed Time : "+s.getLastAccessedTime());
}
}
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>A3</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>
Output :-
Discussion :-
We have sent a request to the servlet, from there we print the the session information using the
Session object which we got using the HttpServletRequest object’s getSession() method. The
IOException is declared and it tells that IOException might occur due to failed or interrupted I/O
operations.
Assignment 4 :-
Source Code :-
Index.html :-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="welcome" method="post">
<div>Id</div>
<input type="email" name="email">
<div>Password</div>
<input type="password" name="psw">
<input type="submit" value="Log In">
</form>
</body>
</html>
Main.java :-
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/welcome")
public class Main extends HttpServlet {
public void service(HttpServletRequest req,HttpServletResponse res) throws
IOException {
String mail=req.getParameter("email");
String psw=req.getParameter("psw");
try {
if(mail.equals("admin@gmail.com") && psw.equals("password")) {
Cookie c=new Cookie("log","true");
res.addCookie(c);
res.getWriter().println("<html><body>Welcome User<form
action=\"logout\"><input type=\"submit\" value=\"Log Out\"></form></body></html>");
}
}catch(NullPointerException e) {
try{
for(Cookie o:req.getCookies()) {
if(o.getName().equals("log")) {
res.getWriter().println("<html><body>Welcome User<form
action=\"logout\"><input type=\"submit\" value=\"Log Out\"></form></body></html>");
}
}
}catch(NullPointerException e1) {
res.sendRedirect("index.html");
}
}
}
}
Logout.java :-
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/logout")
public class logout extends HttpServlet {
public void service(HttpServletRequest
req,HttpServletResponse res) throws IOException {
for(Cookie c:req.getCookies()) {
if(c.getName().equals("log")) {
c.setMaxAge(0);
res.addCookie(c);
res.sendRedirect("index.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>A4</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>
Output :-
Discussion :-
We have sent some data from the index.html file to the main.class servlet class. In there we
validate the data and create a cookie if necessary and show the welcome page. In that page
a logout button can be found and if the user click on it sends a request to logout.class
servlet class. In there we destroy the cookie and send the user to the index,html page.
We also have declared the IOException if any IO related exception occurs.
Assignment 5:-
Write a servlet program using JDBC to do the CRUD
(SQL Insert, Select, Update, and Delete) operation
into the database.
Algo :-
Step 1 :- Start.
Step 2 :- Send data from insert.html, delete.html, update.html or show.html
page.
Step 3 :- Create 4 classes and extend those to HttpServlet Class.
Step 4 :- Get data from HttpServletRequest Object.
Step 5 :- Create connection with database using jdbc.
Step 6 :- Execute insert, delete, update, select query respectively using the
data we got from HttpServletrequest object.
Step 7 :- Show Data If needed.
Step 8 :- Stop.
Source Code :-
Index.html :-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="http://localhost:8081/A5/insert.html">Insert<a><br>
<a href="http://localhost:8081/A5/update.html">Update<a><br>
<a href="http://localhost:8081/A5/delete.html">Delete<a><br>
<a href="http://localhost:8081/A5/show.html">Show<a><br>
</body>
</html>
Insert.html:-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="insert" method="post">
Name : <input type="text" name="name"><br>
ID : <input type="text" name="id"><br>
Password : <input type="password" name="pass"><br>
<input type="submit" value="add">
</form>
</body>
</html>
Update.html :-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="update" method="post">
Old ID : <input type="text" name="oldid"><br>
New Name : <input type="text" name="name"><br>
New ID : <input type="text" name="id"><br>
New Password : <input type="password" name="pass"><br>
<input type="submit" value="update">
</form>
</body>
</html>
show.html :-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="select">
<input type="submit" value="show data">
<form>
</body>
</html>
Delete.html :-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="delete">
ID : <input type="text" name="id"><br>
<input type="submit" value="delete">
</form>
</body>
</html>
Insert.java :-
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
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("/insert")
public class Insert extends HttpServlet{
@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/assignment","root","pass
word");
java.sql.Statement st=con.createStatement();
PreparedStatement ps=con.prepareStatement("insert into a8 values(?,?,?)");
ps.setString(1,req.getParameter("id"));
ps.setString(2,req.getParameter("name"));
ps.setString(3,req.getParameter("pass"));
if(ps.executeUpdate()==1)
resp.getWriter().print("Added");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Update.java :-
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
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("/update")
public class Update extends HttpServlet {
public void service(HttpServletRequest req,HttpServletResponse resp)throws
IOException,ServletException{
String query="update a8 set id=?,name=?,pass=? where id=?";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/assignment","root","password");
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1, req.getParameter("id"));
stmt.setString(2, req.getParameter("name"));
stmt.setString(3,req.getParameter("pass"));
stmt.setString(4, req.getParameter("oldid"));
if(stmt.executeUpdate()==1) {
resp.getWriter().print("Details Updated");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e1)
{
e1.printStackTrace();
}
}
}
Select.java :-
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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("/select")
public class Select extends HttpServlet {
catch(ClassNotFoundException e1)
{
e1.printStackTrace();
}
resp.getWriter().print(s);
}
}
Delete.java :-
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
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("/delete")
public class Delete extends HttpServlet{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/assignment","root","password");
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1,req.getParameter("id"));
if(stmt.executeUpdate()==1)
resp.getWriter().println("|ID Deleted");
}
catch(SQLException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e1)
{
e1.printStackTrace();
}
}
}
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>A5</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>
Output :-
Discussion :-
We send data from insert.html page to insert.java and it stores the data in the database. Also from
update.html we can update the data which is done by the update.java. delete.java file is used to
delete a certain data. Show.html is used to show all the data from the database which is done by
select.java file. We also used SQLException ,ClassNotFoundException so that we can identify what
error occurred if any occurred;
Assignment 6 :-
Write a program to display the applet using jsp.
Algo :-
Step 1 :- Start.
Step 2 :- Create a class which extends applet.
Step 3 :- Set Layout to null.
Step 4 :- Create a button and add it to the class.
Step 5 :- Set Background colour.
Step 6 :- Create a jsp file.
Step 7 :- Add the class file using <jsp:plugin>
Step 8 :- Stop.
Source Code :-
Applet :-
ButtonMoveApplet.java
import java.io.*;
import java.awt.*;
import java.util.*;
import java.applet.*;
import java.awt.event.*;
public class ButtonMoveApplet extends Applet {
Button move;
Random r;
public void init() {
setLayout(null);
move = new Button("Click me");
add(move);
move.reshape(10,10,70,30);
r = new Random();
setBackground(Color.red);
setForeground(Color.yellow);
}
public void paint(Graphics g){
g.drawString("Welcome JSP-Applet",100,100);
}
public boolean action(Event evt, Object whatAction) {
if (!(evt.target instanceof Button))
return false;
String buttonLabel = (String)whatAction;
if (buttonLabel == "Click me") {
move.reshape(Math.abs(r.nextInt())%(size().width-70),
Math.abs(r.nextInt())%(size().height-30),70,30);
repaint();
}
return true;
}
}
JSP :-
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Mouse Move</title>
</head>
<body bgcolor="yellow">
<h1>Mouse Move Example</h1>
<h2> JSP PLUGIN </h2>
<jsp:plugin type="applet" code="ButtonMoveApplet.class"
width="400" height="400">
<jsp:fallback>
<p>Unable to load</p>
</jsp:fallback>
</jsp:plugin>
</body>
</html>
Output :-
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>A6</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>
Discussion :-
An applet is a program written in the Java programming language that can be included in an HTML
page. Here we created a applet and a jsp file we then added the applet to jsp and show it using a
web browser.
Assignment 7 :-
Write a program in JSP to design the Employee
Registration form and store form parameters into the
MySQL database.
Algo :-
Step 1 :- Start.
Step 2 : - Create a html file and a jsp file.
Step 3 :- Send data from html form.
Step 4 :- Import java.sql package using page directive tag in jsp file.
Step 5 :- Get Employee data using request object.
Step 6 :- Connect to database server using jdbc.
Step 7 :- Execute insert query using the data we got from the request object.
Step 8 :- Stop.
Source Code :-
Index.html :-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script>
function validate(){
var id=document.querySelector("#id").value;
var name=document.querySelector("#name").value;
var mail=document.querySelector("#mail").value;
var sal=document.querySelector("#sal").value;
var pin=document.querySelector("#pin").value;
var data=document.querySelector("#data");
if(id=="" || name=="" || mail=="" || sal=="" || pin==""){
document.querySelector("#submit").style.display="none";
data.innerHTML="All Fields Must Be Filled";
}else{
document.querySelector("#submit").style.display="block";
data.innerHTML="Ok";
}
}
</script>
</head>
<body>
<form action="registration.jsp" method="post">
Employee Id : <input type="text" name="id" id="id"><br>
Employee Name : <input type="text" name="name" id="name"><br>
Employee Mail : <input type="text" name="mail" id="mail"><br>
Salary : <input type="number" name="sal" id="sal"><br>
Pin Code : <input type="number" name="pin" id="pin"><br>
<input type="submit" value="submit" id="submit" style="display:none">
</form>
<button id="b1" onclick="validate()">Validate</button><br>
<strong id="data"></strong>
</body>
</html>
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>
<%@page import="java.sql.*" %>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/assignment","root","password");
java.sql.Statement st=con.createStatement();
PreparedStatement ps=con.prepareStatement("insert into a7 values(?,?,?,?,?)");
ps.setString(1,request.getParameter("id"));
ps.setString(2,request.getParameter("name"));
ps.setString(3,request.getParameter("mail"));
ps.setInt(4,Integer.parseInt(request.getParameter("sal")));
ps.setInt(5,Integer.parseInt(request.getParameter("pin")));
if(ps.executeUpdate()==1)
response.getWriter().print("Added");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
%>
</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>A7</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>
Output :-
Discussion :-
We created a jsp file where we catch the data and insert the data into the database.
Jsp is easy to write and we can write html and java both language in it which makes it very easy to
use and we write very little code compare to java.
Assignment 8 :-
Write a program in java to demonstrate the MVC
design pattern.
Algo :-
Step 1 :- Start.
Step 2 :- Create a html file.
Step 3 :- Create 3 class one is for model, one is for controller and one for view.
Step 4 :- In one class define the data model.
Step 5 :- Create getter setter.
Step 6 :- Create another class and define the functions.
Step 7 :- Create another class file to show the data.
Step 8 :- Stop.
Source Code :-
Model.java :-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
Controller.java :-
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
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("/add")
public class Controller extends HttpServlet {
@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
Model m;
try{
if(!req.getParameter("name").equals("")&&!req.getParameter("id").equals("")&&!req.getParameter(
"pass").equals("")) {
m=new
Model(req.getParameter("name"),req.getParameter("id"),req.getParameter("pass"));
try {
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/assignment","root","password");
java.sql.Statement st=con.createStatement();
PreparedStatement ps=con.prepareStatement("insert into a8 values(?,?,?)");
ps.setString(1,m.getId());
ps.setString(2,m.getName() );
ps.setString(3, m.getPassword());
ps.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} }
}catch(NullPointerException e) {
System.out.println();
res.sendRedirect("show");
}
}
}
View.java :-
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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("/show")
public class View extends HttpServlet{
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
String query="select * from a8";
Model m;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/assignment","root","password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
m=new Model
(rs.getString("name"),rs.getString("id"),rs.getString("pass")) ;
resp.getWriter().print(m.getName()+"--"+m.getId()+"<br>");
}
} catch (SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e1)
{
e1.printStackTrace();
}
}
}
Index.html :-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="add" method="POST">
Name : <input type="text" name="name"><br>
Id : <input type="text" name="id"><br>
Password : <input type="password" name="pass"><br>
<input type="submit" value="add">
</form>
<form action="add">
<input type="submit" value="Show All 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="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>A8</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>
Output :-
Discussion :-
The Model-View-Controller (MVC) is a well-known design pattern in the web development field.
Here the the model.java works as model, view.java works as view, controller.java works as a
controller. The controller controls what to do according to request. Model defines the data model
and view shows all the data.
Assignment 9 :-
Write a servlet program (DisplayServlet and
LoginServlet) to validate the user using DAO
design pattern.
Algo :-
Step 1 :- Start
Step 2 :- Create index.html.
Step 3 :- Create DisplayServlet and LoginServlet.
Step 4 :- Extend HttpServlet to LoginServlet.
Step 5 :- Create check class to validate the user.
Step 6 :- Get data from index.html and validate user.
Step 7 :- If true then redirect to DisplayServlet.
Step 8 :- Extend HttpServlet to DisplayServlet.
Step 9 :- Create show class to show the data.
Step 10 :- Show data from database.
Step 11 :- Stop.
Source Code :-
Index.html :-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="POST">
Id : <input type="text" name="id"><br>
Password : <input type="password" name="pass"><br>
<input type="submit" value="login">
</form>
</body>
</html>
LoginServlet.java :-
import java.io.IOException;
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("/login")
public class LoginServlet extends HttpServlet {
resp.sendRedirect("show");
}else {
resp.getWriter().print("Invalid");
}
}
}
Check.java :-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class check {
public static boolean check(String id,String password) {
boolean f=false;
String query="select * from a8 where id='"+id+"' and pass='"+password+"'";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/assignment","root","password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
if(!rs.getString("name").equals(null))
f=true;
}
} catch (SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e1)
{
e1.printStackTrace();
}
return f;
}
}
DisplayServlet.java :-
import java.io.IOException;
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("/show")
public class DisplayServlet extends HttpServlet {
@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
res.getWriter().print("Successfully Logged In");
res.getWriter().println(show.show());
}
}
Show.java :-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
catch(ClassNotFoundException e1)
{
e1.printStackTrace();
}
return s;
}
}
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>A9</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>
Output :-
Discussion :-
DAO stands for Data Access Object. DAO design pattern is used to separate the data persistence
logic in a separate layer. This way, the service remains completely in dark about how the low-level
operations to access the database is done. This is known as the principle of Separation of Logic.
Here LoginServlet validates the user if the result is true then it redirects to DisplayServlet so the
LoginServlet does not know how the data is shown and DisplayServlet does not know how the user
got validated.
Assignment 10 :-
Write a program of form validation using javascript
and html.
Algo :-
Step 1 :- Start.
Step 2 :- Create html page.
Step 3 :- Get the input elements using document.querySelector().
Step 4 :- Check if all fields are filled or not.
Step 5 :- If all fields are filled display submit button.
Step 6 :- Otherwise error message.
Step 7 :- Stop.
Source Code :-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script>
function validate(){
var id=document.querySelector("#id").value;
var name=document.querySelector("#name").value;
var mail=document.querySelector("#mail").value;
var sal=document.querySelector("#sal").value;
var pin=document.querySelector("#pin").value;
var data=document.querySelector("#data");
if(id=="" || name=="" || mail=="" || sal=="" || pin==""){
document.querySelector("#submit").style.display="none";
data.innerHTML="All Fields Must Be Filled";
}else{
document.querySelector("#submit").style.display="block";
data.innerHTML="Ok";
}
}
</script>
</head>
<body>
<form action="registration.jsp" method="post">
Employee Id : <input type="text" name="id" id="id"><br>
Employee Name : <input type="text" name="name" id="name"><br>
Employee Mail : <input type="text" name="mail" id="mail"><br>
Salary : <input type="number" name="sal" id="sal"><br>
Pin Code : <input type="number" name="pin" id="pin"><br>
<input type="submit" value="submit" id="submit" style="display:none">
</form>
<button id="b1" onclick="validate()">Validate</button><br>
<strong id="data"></strong>
</body>
</html>
Output :-
Discussion :-
We have created a validate function using javascript. It validates the html form and if all the field
validates then it displays the submit button. If the form does not validates then it shows a error
message.
Assignment 11 :-
Write a program by the use of JQuery if we select the
value of the checkbox, then we register the form;
otherwise, the form is not registered.
Algo :-
Step 1 :- Start.
Step 2 :- Create a html form.
Step 3 :- Add event to the checkbox.
Step 4 :- If the checkbox is checked then enable the submit button.
Step 5 :- Otherwise disable the submit Button.
Step 6 :- Stop.
Source Code :-
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#check").click(function(){
console.log($("#check").prop("checked"));
if($("#check").prop("checked")){
$("#b").prop("disabled",false);
}else{
$("#b").prop("disabled",true);
}
});
});
</script>
</head>
<body>
<form action="a11.html">
ID : <input type="text" name="id"><br>
Name : <input type="text" name="name"><br>
Address : <input type="text" name="adr"><br>
<input type="checkbox" name="box" id="check">I Agree<br>
<input type="submit" value="submit" id="b" disabled>
</form>
</body>
</html>
Output :-
Discussion :-
JQuery is a javascript library. It is easy to use and light-weight. Using JQuery we have validated a
form where if the checkbox is checked then the form is registered otherwise not.
Assignment 12:-
Write a program to show the jQuery hide effect.
Algo :-
Step 1 :- Start.
Step 2 :- Create a html file.
Step 3 :- Add click event to div.
Step 4 :- If the div is clicked select the div and call hide() function over it.
Step 5 :- Stop.
Source Code :-
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").click(function(){
$(this).hide();
});
});
</script>
<style>
#w{
display:block;
width:100px;
height:100px;
background:#e6e6e6;
}
</style>
</head>
<body>
<div id="w">Click Me</div>
</body>
</html>
Output :-
Discussion :-
We have created a html file. We have created a div and add click event to it using JQuery.
If the div is clicked the it calls hide function which hides the div.