AJP - Lab Manual 220020107091
AJP - Lab Manual 220020107091
EXPERIMENT NO: 1
THEORY:
URLs and URLConnections provide a relatively high-level mechanism for accessing resources on
the Internet. Sometimes your programs require lower-level network communication, for example,
when you want to write a client-server application.
In client-server applications, the server provides some service, such as processing database queries
or sending out current stock prices. The client uses the service provided by the server, to an
investor. The communication that occurs between the client and the server must be reliable. That
is, no data can be dropped and it must arrive on the client side in the same order in which the
server sent it.
TCP provides a reliable, point-to-point communication channel that client-server applications on
the Internet use to communicate with each other. To communicate over TCP, a client program
and a server program establish a connection to one another. Each program binds a socket to its
end of the connection. To communicate, the client and the server each reads from and writes to
the socket bound to the connection.
If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new
socket bound to the same local port and also has its remote endpoint set to the address and port of
the client. It needs a new socket so that it can continue to listen to the original socket for
connection requests while tending to the needs of the connected client.
1
Advance java Programming (3160707) 220020107091
On the client side, if the connection is accepted, a socket is successfully created and the client
can use the socket to communicate with the server.
The client and server can now communicate by writing to or reading from their sockets.
Client Server Application using Socket
import java.io.*;
import java.net.*;
public class Client2 {
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost", 888);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
String str, str1;
while (!(str = kb.readLine()).equals("exit")) {
dos.writeBytes(str + "\n");
str1 = br.readLine();
System.out.println(str1);
}
dos.close();
br.close();
kb.close();
s.close();
}
}
import java.io.*;
import java.net.*;
class Server2 {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(888);
Socket s = ss.accept();
System.out.println("Connection established");
PrintStream ps = new PrintStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String str, str1;
while ((str = br.readLine()) != null) {
2
Advance java Programming (3160707) 220020107091
System.out.println(str);
str1 = kb.readLine();
ps.println(str1);
}
}
ps.close();
br.close();
kb.close();
ss.close();
s.close();
System.exit(0);
}
}
What is DatagramPacket and DatagramSocket:
Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.Java DatagramSocket class represents a connection-less socket for sending and
receiving datagram packets.A datagram is basically an information but there is no guarantee of
its content, arrival or arrival time.Commonly used Constructors of DatagramSocket class.
DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the
available Port Number on the localhost machine. DatagramSocket(int port) throws
SocketEeption: it creates a datagram socket and binds it with the given Port Number.
DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a
datagram socket and binds it with the specified port number and host address. Java
DatagramPacket : is a message that can be sent or received. If you send multiple packet, it may
arrive in any order. Additionally, packet delivery is not guaranteed.
Commonly used Constructors of DatagramPacket class
DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used
to receive the packets.
DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a
datagram packet. This constructor is used to send the packets.
Example of Sending DatagramPacket by DatagramSocket
DSender.java
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000); ds.send(dp);
ds.close();
}
}
DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
3
Advance java Programming (3160707) 220020107091
EXERCISE:
1. Develop the Chat Application using TCP & UDP (Two-way communication with messages).
4
Advance java Programming (3160707) 220020107091
2. Write a client-server program using TCP or UDP where the client sends 10 numbers and
server responds with the numbers in sorted order.
5
Advance java Programming (3160707) 220020107091
3. Write a UDP Client-Server program in which the Client sends any string and Server
responds with Reverse string.
EVALUATION:
6
Advance java Programming (3160707) 220020107091
EXPERIMENT NO: 2
import java.net.*;
import java.io.*;
7
Advance java Programming (3160707) 220020107091
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING
import java.net.*;
class MyURL
{
public static void main(String args[ ]) throws Exception
{
URL obj = new URL("http://ait.com/index.html");
System.out.println("Protocol: "+ obj.getProtocol());
System.out.println("Host: "+ obj.getHost());
System.out.println("File: "+ obj.getFile());
System.out.println("Port: "+ obj.getPort());
System.out.println("Path: "+ obj.getPath());
System.out.println("External form: "+ obj.toExternalForm());
}
}
8
Advance java Programming (3160707) 220020107091
InetAddress class
InetAddress class has no visible constructors. To create an InetAddress object, you have to use
one of the available factory methods. Factory methods are merely a convention whereby static
methods in a class return an instance of that class. This is done in lieu of overloading a
constructor with various parameter lists when having unique method names makes the results
much clearer. In the case of InetAddress, the three methods getLocalHost(), getByName(),
and getAllByName() can be used to create instances of InetAddress. These methods are shown
here:
static InetAddress getLocalHost( ) throws UnknownHostException.
static InetAddress getByName(String hostName) throws UnknownHostException.
static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException
The getLocalHost( ) method simply returns the InetAddress object that represents the
local host. The getByName( ) method returns an InetAddress for a host name passed to
it. If these methods are unable to resolve the host name, they throw an
UnknownHostException.
On the Internet, it is common for a single name to be used to represent several machines. In
the world of web servers, this is one way to provide some degree of scaling. The
getAllByName( ) factory method returns an array of InetAddresses that represent all of the
addresses that a particular name resolves to. It will also throw an UnknownHostException if
it can't resolve the name to at least one address.
import java.io.*;
import java.net.*;
class Address
{
public static void main(String args[ ]) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter a website name: ");
String site = br.readLine();
try{
InetAddress ip = InetAddress.getByName(site);
System.out.println("The IP Address is: "+ ip);
9
Advance java Programming (3160707) 220020107091
}catch(UnknownHostException ue)
{
System.out.println("Website not found");
}
}
}
EXERCISE:
10
Advance java Programming (3160707) 220020107091
11
Advance java Programming (3160707) 220020107091
3. Write a program to display the expiration date and last modified date for the following URL :
http://www.java2s.com/Tutorial/Java/0380 JSTL/SetupEnvironmentforJSTL.html
EVALUATION:
Involvement Understanding / Timely Completion Total
Problem solving (3) (10)
(4)
(3)
12
Advance java Programming (3160707) 220020107091
EXPERIMENT NO: 3
THEORY:
JDBC is Java application programming interface that allows the Java programmers to
access database management system from Java code. It was developed by JavaSoft, a
subsidiary of Sun Microsystems. Definition
Java Database Connectivity in short called as JDBC. It is a java API which enables the java
programs to execute SQL statements. It is an application programming interface that defines
how a java programmer can access the database in tabular format from Java code using a set of
standard interfaces and classes written in the Java programming language.
JDBC has been developed under the Java Community Process that allows multiple
implementations to exist and be used by the same application. JDBC provides methods for
querying and updating the data in Relational Database Management system such as SQL,
Oracle etc. The primary function of the JDBC API is to provide a means for the developer to
issue SQL statements and process the results in a consistent, database-independent manner.
JDBC provides rich, object-oriented access to databases by defining classes and interfaces that
represent objects such as:
1. Database connections
2. SQL statements
3. Result Set
4. Database metadata
5. Prepared statements
6. Binary Large Objects (BLOBs)
7. Character Large Objects (CLOBs)
8. Callable statements
9. Database drivers
10. Driver manager
Processing SQL Statements with JDBC
In general, to process any SQL statement with JDBC, you follow these steps:
1. Establishing a connection.
2. Create a statement.
3. Execute the query.
4. Process the ResultSet object.
5. Close the connection.
Statement interface
The Statement interface provides methods to execute queries with the
database. The statement interface is a factory of ResultSet i.e. it provides factory
method to get the object of ResultSet.
13
Advance java Programming (3160707) 220020107091
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","ora
cle"); Statement stmt=con.createStatement();
where id=102"); int result=stmt.executeUpdate("delete from employee where
id=101");
System.out.println(result+" records affected");
con.close();
}}
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor
points to before the first row.
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle
"); Statement
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_U
PDATA BLE);
ResultSet rs=stmt.executeQuery("select * from employee");
rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}}
Let's first create a table in the mysql database, but before creating table, we need to
create database first. 1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
Ex:
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
14
Advance java Programming (3160707) 220020107091
}
}
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query. String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by calling
the setter methods of PreparedStatement.
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Java CallableStatement Interface
CallableStatement interface is used to call the stored procedures and functions. We can have
business logic on the database by the use of stored procedures and functions that will make
the performance better because these are precompiled.Suppose you need the get the age of
the employee based on the date of birth, you may create a function that receives date as the
input and returns age of the employee as the output.
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");
stmt.setInt(1,1011);
stmt.setString(2,"Amit");
stmt.execute();
System.out.println("success");
}
}
16
Advance java Programming (3160707) 220020107091
EXERCISE:
1. Write a program to insert,update,delete and print first five topper student from student
records in database using prepared statement.
17
Advance java Programming (3160707) 220020107091
2. Write a program to insert,update,delete and print record for employee having salary >
20000 from Employee table in database using statement interface.
18
Advance java Programming (3160707) 220020107091
3. Write Java application program to change the basic = basic + 500 of all the employees whose
age is greater than 40 from employee table then display how many record updated using
callable statement.
19
Advance java Programming (3160707) 220020107091
20
Advance java Programming (3160707) 220020107091
EVALUATION:
21
Advance java Programming (3160707) 220020107091
EXPERIMENT NO: 4
THEORY:
Servlet technology is used to create a web application (resides at server side and generates
a dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side
programming language.
Servlet API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet
api.The javax.servlet package contains many interfaces and classes that are used by the servlet
or web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.Let's see what are the interfaces of javax.servlet package.
out.print("</body></html>");
}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}
}
Methods of HttpServlet class
There are many methods in HttpServlet class. They are as follows:
1. public void service(ServletRequest req,ServletResponse res) dispatches the request
to the protected service method by converting the request and response object into http
type.
2. protected void service(HttpServletRequest req, HttpServletResponse res)
receives the request from the service method, and dispatches the request to the
doXXX() method depending on the incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles
the GET request. It is invoked by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse res)
handles the POST request. It is invoked by the web container.
5. protected void doHead(HttpServletRequest req, HttpServletResponse res)
handles the HEAD request. It is invoked by the web container.
6. protected void doOptions(HttpServletRequest req, HttpServletResponse
res) handles the OPTIONS request. It is invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles
the PUT request. It is invoked by the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse res)
handles the TRACE request. It is invoked by the web container.
9. protected void doDelete(HttpServletRequest req, HttpServletResponse res)
handles the DELETE request. It is invoked by the web container.
10. protected long getLastModified(HttpServletRequest req) returns the time when
HttpServletRequest was last modified since midnight January 1, 1970 GMT.
HttpServlet {
private String message;
public void init() throws ServletException {
message = "Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
23
Advance java Programming (3160707) 220020107091
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
RequestDispatcher in Servlet
The RequestDispatcher interface provides the facility of dispatching the request to another
resource it may be html, servlet or jsp. This interface can also be used to include the
content of another resource also. It is one of the way of servlet collaboration.There are two
methods defined in the Request
Dispatcher interface.
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
24
Advance java Programming (3160707) 220020107091
Login.java
import java.io.*;
import javax.servlet.*;
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher
rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher
rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
}
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
25
Advance java Programming (3160707) 220020107091
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
SendRedirect in servlet
The sendRedirect() method of HttpServletResponse interface can be used to redirect
response to another resource, it may be servlet, jsp or html file. It accepts relative as well as
absolute URL. It works at client side because it uses the url bar of the browser to make another
request. So, it can work inside and outside the server.
Ex:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
response.sendRedirect("http://www.google.com");
pw.close();
}}
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>sendRedirect example</title>
</head>
<body>
<form action="MySearcher">
<input type="text" name="name">
<input type="submit" value="Google Search">
</form>
</body>
</html>
mport java.io.IOException;
import javax.servlet.ServletException;
26
Advance java Programming (3160707) 220020107091
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
public class MySearcher extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name=request.getParameter("name");
response.sendRedirect("https://www.google.co.in/#q="+name);
}
}
EXERCISE:
1. Design a form to input details of an employee and submit the data to a servlet. Write code
for servlet that will save the entered details as a new record in database table Employee with
fields (EmpId, EName,Email, Age).
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Employee Form</title>
</head>
<body>
<h2>Enter Employee Details</h2>
<form action="employee" method="POST">
<label for="empId">Employee ID:</label><br>
<input type="text" id="empId" name="empId" required><br><br>
<label for="ename">Employee Name:</label><br>
<input type="text" id="ename" name="ename" required><br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required><br><br>
<label for="age">Age:</label><br>
<input type="number" id="age" name="age" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
EmployeeServlet.java
package demo;
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
27
Advance java Programming (3160707) 220020107091
import java.sql.*;
public class EmployeeServlet extends HttpServlet {
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/student1"; // Replace
with your DB URL
private static final String JDBC_USERNAME = "root"; // Replace with your DB username
private static final String JDBC_PASSWORD = "root"; // Replace with your DB password
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String empId = request.getParameter("empId");
String ename = request.getParameter("ename");
String email = request.getParameter("email");
int age;
try {
age = Integer.parseInt(request.getParameter("age"));
} catch (NumberFormatException e) {
out.println("<h3>Error: Invalid age format.</h3>");
return;
}
Connection conn = null;
PreparedStatement stmt = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME,
JDBC_PASSWORD);
String sql = "INSERT INTO Employee (EmpId, EName, Email, Age) VALUES (?, ?,
?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setString(1, empId);
stmt.setString(2, ename);
stmt.setString(3, email);
stmt.setInt(4, age);
int rowsInserted = stmt.executeUpdate();
if (rowsInserted > 0) {
out.println("<h3>Employee details added successfully!</h3>");
} else {
out.println("<h3>Error: Could not insert employee details.</h3>");
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
28
Advance java Programming (3160707) 220020107091
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
response.getWriter().println("<h3>This servlet handles POST requests to add employee
details.</h3>");
}
}
web.xml
29
Advance java Programming (3160707) 220020107091
Output:
2. Write a servlet RegistrationServlet to get the values from registration.html html page
and display the contents. Write the web.xml file.
Registration.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Form</title>
</head>
<body>
<h2>Registration Form</h2>
<form action="RegistrationServlet" method="POST">
<label for="Name">Name:</label><br>
<input type="text" id="Name" name="name" required><br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"
required><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>
30
Advance java Programming (3160707) 220020107091
RegistrationServlet.java
package demo1;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
public class RegistrationServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String email = request.getParameter("email");
String password = request.getParameter("password");
out.println("<html><body>");
out.println("<h2>Registration Successful</h2>");
out.println("<p><strong>Name:</strong> " + name + "</p>");
out.println("<p><strong>Email:</strong> " + email + "</p>");
out.println("<p><strong>Password:</strong> " + password + "</p>");
out.println("</body></html>");
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<servlet-name>RegistrationServlet</servlet-name>
<servlet-class>demo1.RegistrationServlet</servlet-class>
<welcome-file-list>
<welcome-file>registration.html</welcome-file>
</welcome-file-list>
</web-app>
31
Advance java Programming (3160707) 220020107091
Output:
MyServlet.java
package demo;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
public class MyServlet extends HttpServlet {
public void init() throws ServletException {
ServletConfig config = getServletConfig();
String username = config.getInitParameter("username");
String password = config.getInitParameter("password");
System.out.println("Username (from ServletConfig): " + username);
System.out.println("Password (from ServletConfig): " + password);
ServletContext context = getServletContext();
context.setAttribute("appName", "My Web App"); // Set an application-wide attribute
}
@Override
32
Advance java Programming (3160707) 220020107091
33
Advance java Programming (3160707) 220020107091
</servlet>
<!-- Map the servlet to the URL -->
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/showConfigAndContext</url-pattern>
</servlet-mapping>
Output:
4. Write a Login servlet. Take input username and password from html file login.html and
authenticate the user. Write the web.xml.
Login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<h2>Login Form</h2>
<form action="LoginServlet" method="post">
34
Advance java Programming (3160707) 220020107091
<label for="username">Username:</label><br>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
LoginServlet.java
package demo;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
@Override
response.setContentType("text/html");
out.println("<html><body>");
out.println("<h2>Login Successful!</h2>");
out.println("</body></html>");
35
Advance java Programming (3160707) 220020107091
} else {
out.println("<html><body>");
out.println("<h2>Login Failed!</h2>");
out.println("</body></html>");
Web.xml
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>demo.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
36
Advance java Programming (3160707) 220020107091
Output:
5. Write a web application using servlet to compute an area of a circle. Get the radius from
the client. Write necessary web.xml file.
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculate Area of Circle</title>
</head>
<body>
<h2>Calculate Area of Circle</h2>
<form action="CircleAreaServlet" method="POST">
<label for="radius">Enter the radius of the circle:</label>
<input type="text" id="radius" name="radius" required>
<button type="submit">Calculate Area</button>
</form>
37
Advance java Programming (3160707) 220020107091
</body>
</html>
CircleAreaServlet.java
package demo;
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class CircleAreaServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
String radiusStr = request.getParameter("radius");
double radius = Double.parseDouble(radiusStr); // Parse the radius
double area = Math.PI * Math.pow(radius, 2);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Circle Area Calculation</title></head>");
out.println("<body>");
out.println("<h2>Area of the Circle</h2>");
out.println("<p>Radius: " + radius + "</p>");
out.println("<p>Area: " + area + "</p>");
out.println("</body>");
out.println("</html>");
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<servlet>
38
Advance java Programming (3160707) 220020107091
<servlet-name>CircleAreaServlet</servlet-name>
<servlet-class>demo.CircleAreaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CircleAreaServlet</servlet-name>
<url-pattern>/CircleAreaServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index1.html</welcome-file>
</welcome-file-list>
</web-app>
Output:
EVALUATION:
39
Advance java Programming (3160707) 220020107091
EXPERIMENT NO: 5
THEORY:
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet. Http protocol is a stateless so we need to maintain state using session
tracking techniques. Each time user equests to the server, server treats the request as the new
request. So we need to maintain the state of an user to recognize to particular user. HTTP is
stateless that means each request is considered as the new request. It is shown in the figure given
below:
Session Tracking Techniques
There are four techniques used in Session tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Cookies in Servlet : A cookie is a small piece of information that is persisted between the
multiple client requests. A cookie has a name, a single value, and optional attributes such as a
comment, path and domain qualifiers, a maximum age, and a version number.
How Cookie works
By default, each request is considered as a new request. In cookies technique, we add cookie
with response from the servlet. So cookie is stored in the cache of the browser. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the user
as the old user.
Example :
40
Advance java Programming (3160707) 220020107091
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
41
Advance java Programming (3160707) 220020107091
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Servlet Filter
A filter is an object that is invoked at the preprocessing and postprocessing of a
request. It is mainly used to perform filtering tasks such as conversion, logging,
compression, encryption and decryption, input validation etc.
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we
remove the entry of filter from the web.xml file, filter will be removed
automatically and we don't need to change the servlet. So maintenance cost will
be less.
42
Advance java Programming (3160707) 220020107091
Usage of Filter
Advantage of Filter
1. Filter is pluggable.
2. One filter don't have dependency onto another resource.
3. Less Maintenance
EX:
index.html
1. <a href="servlet1">click here</a>
MyFilter.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
public class MyFilter implements Filter{
public void init(FilterConfig arg0) throws ServletException {}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
PrintWriter out=resp.getWriter();
out.print("filter is invoked before");
chain.doFilter(req, resp);//sends request to next resource
out.print("filter is invoked after");
}
public void destroy() {}
}
HelloServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<br>welcome to servlet<br>");
43
Advance java Programming (3160707) 220020107091
}}
web.xml
For defining the filter, filter element of web-app must
be defined just like servlet. <web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
</web-app>
EXERCISE:
1. Write Servlet program to create cookie for employee data. Also write code to
display contents of cookie on page.
EmployeeData.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Employee Data Entry</title>
</head>
<body>
<h2>Enter Employee Data</h2>
<form action="EmployeeDataServlet" method="POST">
<label for="employeeID">Employee ID:</label>
<input type="text" id="employeeID" name="employeeID" required><br><br>
<label for="employeeName">Employee Name:</label>
<input type="text" id="employeeName" name="employeeName" required><br><br>
<label for="employeeRole">Employee Role:</label>
<input type="text" id="employeeRole" name="employeeRole" required><br><br>
<button type="submit">Save Employee Data</button>
44
Advance java Programming (3160707) 220020107091
</form>
</body>
</html>
EmployeeDataServlet.java
package demo;
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class EmployeeDataServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String employeeID = request.getParameter("employeeID");
String employeeName = request.getParameter("employeeName");
String employeeRole = request.getParameter("employeeRole");
Cookie idCookie = new Cookie("employeeID", employeeID);
Cookie nameCookie = new Cookie("employeeName", employeeName);
Cookie roleCookie = new Cookie("employeeRole", employeeRole);
idCookie.setMaxAge(80 * 80); // 1 hour
nameCookie.setMaxAge(80 * 80);
roleCookie.setMaxAge(80 * 80);
response.addCookie(idCookie);
response.addCookie(nameCookie);
response.addCookie(roleCookie);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Employee Data Saved</title></head>");
out.println("<body>");
out.println("<h2>Employee Data Saved Successfully!</h2>");
out.println("<p>Employee ID: " + employeeID + "</p>");
out.println("<p>Employee Name: " + employeeName + "</p>");
out.println("<p>Employee Role: " + employeeRole + "</p>");
out.println("<a href='ShowEmployeeDataServlet'>Click here to see your saved employee
data</a>");
out.println("</body>");
out.println("</html>");
}
}
ShowEmployeeDataServlet.java
package demo;
import java.io.*;
45
Advance java Programming (3160707) 220020107091
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class ShowEmployeeDataServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
Cookie[] cookies = request.getCookies();
String employeeID = null;
String employeeName = null;
String employeeRole = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("employeeID".equals(cookie.getName())) {
employeeID = cookie.getValue();
} else if ("employeeName".equals(cookie.getName())) {
employeeName = cookie.getValue();
} else if ("employeeRole".equals(cookie.getName())) {
employeeRole = cookie.getValue();
}
}
}
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Employee Data</title></head>");
out.println("<body>");
out.println("<h2>Employee Data from Cookies</h2>");
if (employeeID != null && employeeName != null && employeeRole != null) {
out.println("<p>Employee ID: " + employeeID + "</p>");
out.println("<p>Employee Name: " + employeeName + "</p>");
out.println("<p>Employee Role: " + employeeRole + "</p>");
} else {
out.println("<p>No employee data found in cookies.</p>");
}
out.println("<a href='index.html'>Go Back to Enter Employee Data</a>");
out.println("</body>");
out.println("</html>");
}
}
Web.xml
</servlet>
<servlet-mapping>
<servlet-name>EmployeeDataServlet</servlet-name>
<url-pattern>/EmployeeDataServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ShowEmployeeDataServlet</servlet-name>
<servlet-class>demo.ShowEmployeeDataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowEmployeeDataServlet</servlet-name>
<url-pattern>/ShowEmployeeDataServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>EmployeeData.html</welcome-file>
</welcome-file-list>
</web-app>
Output:
47
Advance java Programming (3160707) 220020107091
2. Write Servlet program to demonstrate use of session with three methods of session tracking.
Hp.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome Page</title>
</head>
<body>
<h1>Welcome to My Web Application</h1>
<p>This page demonstrates session tracking using servlets.</p>
<p>
<a href="/Ajava/SessionTrackingServlet">Start Session Tracking</a>
</p>
<p>If you click the link, a session will be created or reused, and you'll see the status.</p>
</body>
</html>
SessionTrackingServlet.java
package demo;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
public class SessionTrackingServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true); // true means create a new session if it
doesn't exist
boolean isNewSession = session.isNew();
String sessionData = (String) session.getAttribute("sessionData");
out.println("<html><body>");
out.println("<h3>Session Tracking Demonstration</h3>");
if (isNewSession) {
out.println("<p><b>New session has been created!</b></p>");
} else {
out.println("<p><b>Session already exists.</b></p>");
}
out.println("<p>Session Data: " + (sessionData != null ? sessionData : "No session data
available") + "</p>");
if (sessionData == null) {
session.setAttribute("sessionData", "Session Initialized");
}
48
Advance java Programming (3160707) 220020107091
Output:
EVALUATION:
Involvement Understanding / Timely Completion Total
Problem solving (3) (10)
(4) (3)
49
Advance java Programming (3160707) 220020107091
EXPERIMENT NO: 6
1) request
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
50
Advance java Programming (3160707) 220020107091
web.xml file
<web-app>
51
Advance java Programming (3160707) 220020107091
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<context-param>
<param-name>dname</param-name>
<paramValue>sun.jdbc.odbc.JdbcOdbcDriver</param-
value> </context-param>
</web-app>
welcome.jsp
<% out.print("Welcome "+request.getParameter("uname"));
String
driver=application.getInitParameter("dname");
out.print("driver name is="+driver);
%>
5) Session
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>
second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
52
Advance java Programming (3160707) 220020107091
%>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
pageContext.setAttribute("user",name,Context.SESSION_SCOPE);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>
second.jsp
<html>
<body>
<%
String name = (String) pageContext.getAttribute ("user",Context.SESSION_SCOPE);
out.print("Hello "+name);
%>
</body>
</html>
JSP directives
The jsp directives are messages that tells the web container how to translate a JSP page into
the corresponding servlet.
1. page directive
2. include directive
3. taglib directive
Import
<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body> </html>
contentType
<html> <body>
<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>
</body> </html>
Jsp Include Directive
<html> <body>
<%@ include file="header.html" %>
Today is: <%=
java.util.Calendar.getInstance().getTime() %>
</body> </html>
JSP Taglib directive
<html> <body>
<%@ taglib uri="http://www.google.com/tags" prefix="mytag"
%> <mytag:currentDate/>
</body> </html>
1) jsp:forward
index.jsp
<html>
54
Advance java Programming (3160707) 220020107091
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" />
</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today
is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
2) jsp:include
File: index.jsp
File: printdate.jsp
<% out.print("Today
is:"+java.util.Calendar.getInstance().getTime()); %> 3)
jsp:useBean
Calculator.java (a simple Bean class)
package com.javatpoint;
public class Calculator{
public int cube(int n){return n*n*n;}
}
index.jsp file
<jsp:useBean id="obj"
class="com.javatpoint.Calculator"/>
<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>
Example of bean development in JSP
index.html
package org.sssit;
public class User {
private String name,password,email;
//setters and getters
}
EXERCISE:
1. Write small web application which takes marks of three subject and pass to servlet. Servlet
forward to model class having method getClass() and getPercentage(). Display class and
percentage in .jsp page
Hw.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Marks Entry</title>
</head>
<body>
<div class="container">
<h2>Student Marks Entry Form</h2>
<form action="MarksServlet" method="post">
<div class="form-group">
<label for="marks1">Marks in Subject 1:</label>
<input type="number" id="marks1" name="marks1" min="0" max="100" required>
<div class="note">Enter marks between 0 and 100</div>
</div>
56
Advance java Programming (3160707) 220020107091
<div class="form-group">
<label for="marks2">Marks in Subject 2:</label>
<input type="number" id="marks2" name="marks2" min="0" max="100" required>
<div class="note">Enter marks between 0 and 100</div>
</div>
<div class="form-group">
<label for="marks3">Marks in Subject 3:</label>
<input type="number" id="marks3" name="marks3" min="0" max="100" required>
<div class="note">Enter marks between 0 and 100</div>
</div>
<input type="submit" value="Calculate Result">
</form>
</div>
</body>
</html>
Student.java
package demo;
public class Student {
private int marks1;
private int marks2;
private int marks3;
public Student(int marks1, int marks2, int marks3) {
this.marks1 = marks1;
this.marks2 = marks2;
this.marks3 = marks3;
}
public int getMarks1() {
return marks1;
}
public int getMarks2() {
return marks2;
}
public int getMarks3() {
return marks3;
}
public double getPercentage() {
57
Advance java Programming (3160707) 220020107091
MarksServlet.java
package demo;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
public class MarksServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
try {
int marks1 = Integer.parseInt(request.getParameter("marks1"));
int marks2 = Integer.parseInt(request.getParameter("marks2"));
int marks3 = Integer.parseInt(request.getParameter("marks3"));
if (marks1 < 0 || marks1 > 100 || marks2 < 0 || marks2 > 100 || marks3 < 0 || marks3 > 100)
{
throw new IllegalArgumentException("Marks must be between 0 and 100");
}
Student student = new Student(marks1, marks2, marks3);
request.setAttribute("student", student);
58
Advance java Programming (3160707) 220020107091
Result.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Student Result</title>
<style>
table {
border-collapse: collapse;
width: 50%;
margin: 20px 0;
}
th, td {
border: 1px solid #ddd;
59
Advance java Programming (3160707) 220020107091
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
.pass {
color: green;
}
.fail {
color: red;
}
</style>
</head>
<body>
<h2>Student Marks and Result</h2>
<table>
<tr>
<th>Marks in Subject 1</th>
<td>${student.marks1}</td>
</tr>
<tr>
<th>Marks in Subject 2</th>
<td>${student.marks2}</td>
</tr>
<tr>
<th>Marks in Subject 3</th>
<td>${student.marks3}</td>
</tr>
<tr>
<th>Percentage</th>
<td>${student.percentage}%</td>
</tr>
<tr>
<th>Class</th>
<td class="${student.classGrade eq 'F' ? 'fail' : 'pass'}">${student.classGrade}</td>
60
Advance java Programming (3160707) 220020107091
</tr>
</table>
<a href="hw.html">Back to Home</a>
</body>
</html>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<servlet>
<servlet-name>MarksServlet</servlet-name>
<servlet-class>demo.MarksServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MarksServlet</servlet-name>
<url-pattern>/MarksServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>hw.html</welcome-file>
</welcome-file-list>
</web-app>
Output:
61
Advance java Programming (3160707) 220020107091
2. Write a servlet that redirect requests alternatively to JSP s named Odd and Even.
RedirectServlet.java
package demo;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.IOException;
public class RedirectServlet extends HttpServlet {
private int requestCount = 0; // To keep track of the request count
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
requestCount++;
if (requestCount % 2 == 0) {
response.sendRedirect("Even.jsp");
} else {
response.sendRedirect("Odd.jsp");
62
Advance java Programming (3160707) 220020107091
}
}
}
Odd.jsp
Even.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Even JSP</title>
</head>
<body>
<h1>You have been redirected to Even.jsp</h1>
</body>
</html>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
63
Advance java Programming (3160707) 220020107091
<servlet>
<servlet-name>RedirectServlet</servlet-name>
<servlet-class>demo.RedirectServlet</servlet-class>
</servlet>
<!-- Servlet Mapping -->
<servlet-mapping>
<servlet-name>RedirectServlet</servlet-name>
<url-pattern>/RedirectServlet</url-pattern>
</servlet-mapping>
</web-app>
Output:
3. Develop JSP page to display student information with subjects for particular semester
from database.
DatabaseUtils.java
package demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseUtils {
public static Connection getConnection() throws SQLException {
String url = "jdbc:mysql://localhost:3306/student1"; // Adjust database URL if needed
String username = "root"; // Adjust username if needed
String password = "root"; // Adjust password if needed
64
Advance java Programming (3160707) 220020107091
try {
// Load the JDBC driver and establish the connection
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
throw new SQLException("Database connection error", e);
}
}
}
Student1.java
package demo;
import java.util.List;
public class Student1 {
private int id;
private String name;
private List<String> subjects;
public Student1(int id, String name, List<String> subjects) {
this.id = id;
this.name = name;
this.subjects = subjects;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public List<String> getSubjects() {
return subjects;
}
}
65
Advance java Programming (3160707) 220020107091
StudentInfoServlet.java
package demo;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class StudentInfoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String semester = request.getParameter("semester");
if (semester == null || semester.isEmpty()) {
response.sendRedirect("studentInfo.jsp");
return;
}
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rsStudents = null;
try {
conn = DatabaseUtils.getConnection();
String sqlStudents = "SELECT id, name FROM students WHERE semester = ?";
stmt = conn.prepareStatement(sqlStudents);
stmt.setString(1, semester);
rsStudents = stmt.executeQuery();
List<Student1> studentList = new ArrayList<>();
while (rsStudents.next()) {
int studentId = rsStudents.getInt("id");
String studentName = rsStudents.getString("name");
String sqlSubjects = "SELECT name FROM subjects WHERE student_id = ?";
66
Advance java Programming (3160707) 220020107091
}
}
studentInfo.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Information Portal</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f5f5f5;
}
.container {
max-width: 800px;
margin: 0 auto;
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
h2 {
color: #2c3e50;
text-align: center;
margin-bottom: 30px;
}
68
Advance java Programming (3160707) 220020107091
.student-form {
margin-bottom: 30px;
text-align: center;
}
.student-form label {
font-weight: bold;
margin-right: 10px;
}
.student-form input[type="text"] {
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
width: 100px;
}
.student-form input[type="submit"] {
padding: 8px 20px;
background-color: #3498db;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin-left: 10px;
}
.student-form input[type="submit"]:hover {
background-color: #2980b9;
}
</style>
</head>
<body>
<div class="container">
<h2>Student Information Portal</h2>
69
Advance java Programming (3160707) 220020107091
displayStudents.jsp
<%@page import="demo.Student1"%>
<%@page import="java.util.List"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Information Results</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f5f5f5;
}
.container {
max-width: 1000px;
margin: 0 auto;
background-color: white;
70
Advance java Programming (3160707) 220020107091
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
h2 {
color: #2c3e50;
text-align: center;
margin-bottom: 20px;
padding-bottom: 10px;
border-bottom: 2px solid #3498db;
}
.back-link {
display: block;
margin-bottom: 20px;
text-decoration: none;
color: #3498db;
}
.back-link:hover {
text-decoration: underline;
}
.semester-info {
text-align: center;
font-size: 18px;
margin-bottom: 30px;
padding: 10px;
background-color: #f9f9f9;
border-radius: 5px;
}
.student-card {
background-color: white;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
margin-bottom: 20px;
overflow: hidden;
}
.student-header {
background-color: #3498db;
color: white;
71
Advance java Programming (3160707) 220020107091
</tbody>
</table>
</div>
</div>
<%
}
} else {
%>
<div class="no-data">
No students found for semester ${semester}.
</div>
<%
}
%>
</div>
</body>
</html>
Error.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Error</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f5f5f5;
}
.container {
max-width: 800px;
margin: 0 auto;
background-color: white;
74
Advance java Programming (3160707) 220020107091
padding: 20px;
border-radius: 8px;
}
h2 {
color: #e74c3c;
}
.error-message {
background-color: #fadbd8;
padding: 15px;
border-radius: 5px;
margin: 20px 0;
text-align: left;
}
.back-link {
display: inline-block;
margin-top: 20px;
padding: 10px 20px;
background-color: #3498db;
color: white;
}
.back-link:hover {
background-color: #2980b9;
}
</style>
</head>
<body>
<div class="container">
<h2>Error Occurred</h2>
<div class="error-message">
${errorMessage}
</div>
75
Advance java Programming (3160707) 220020107091
Output:
76
Advance java Programming (3160707) 220020107091
4. Write a java bean named “student” having roll no and name having getter & setter
methods. Write a JSP page to set the roll number and name for a student object and then
print them by reading fromobject.
studentForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Student Information</title>
</head>
<body>
<h2>Enter Student Information</h2>
<form action="displayStudent.jsp" method="post">
Roll No: <input type="number" name="rollNo" required><br><br>
Name: <input type="text" name="name" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
77
Advance java Programming (3160707) 220020107091
</html>
displayStudent.jsp
Student3.jsp
package demo;
public class Student3 implements java.io.Serializable {
private int rollNo;
private String name;
public Student3() {}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
78
Advance java Programming (3160707) 220020107091
}
public void setName(String name) {
this.name = name;
}
}
Output:
5. Write a student bean class with property student_name, enrollment_no, address and cpi.
Write jsp page to set and display all property.
StudentDetails.java
package demo;
public class StudentDetails implements java.io.Serializable {
private String student_name;
private String enrollment_no;
private String address;
private double cpi;
public StudentDetails() {}
public String getStudent_name() {
return student_name;
}
public void setStudent_name(String student_name) {
this.student_name = student_name;
}
public String getEnrollment_no() {
return enrollment_no;
}
public void setEnrollment_no(String enrollment_no) {
79
Advance java Programming (3160707) 220020107091
this.enrollment_no = enrollment_no;
}
public String getAddress() {
}
}studentFrom1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Student Information Form</title>
</head>
<body>
<h2>Enter Student Information</h2>
<form action="displayStudent1.jsp" method="post">
Student Name: <input type="text" name="student_name" required><br><br>
Enrollment No: <input type="text" name="enrollment_no" required><br><br>
Address: <input type="text" name="address" required><br><br>
CPI: <input type="number" name="cpi" step="0.01" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
displayStudent1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<%@ page import="demo.StudentDetails" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Student Details</title>
</head>
<body>
<jsp:useBean id="student" class="demo.StudentDetails" scope="request" />
<jsp:setProperty name="student" property="student_name" param="student_name" />
80
Advance java Programming (3160707) 220020107091
Output:
EVALUATION:
Involvement Understanding / Timely Completion Total
Problem solving (3) (10)
(4)
(3)
81
Advance java Programming (3160707) 220020107091
EXPERIMENT NO: 7
TITLE: JSTL and JSP database connection.
THEORY:
The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development.
Advantage of JSTL
Fast Development JSTL provides many tags that simplify the JSP.
Code Reusability We can use the JSTL tags on various pages.
No need to use scriptlet tag It avoids the use of scriptlet tag.
Ex:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Core Tag Example</title>
</head>
<body>
<c:set var="Income" scope="session" value="${4000*4}"/>
<c:out value="${Income}"/>
</body>
</html>
Ex:
</body>
</html>
fmt:timeZone It specifies a parsing action nested in its body or the time zone for any
time formatting.
fmt:formatNumber It is used to format the numerical value with specific format or
precision.
fmt:parseDate It parses the string representation of a time and date.
fmt:bundle It is used for creating the ResourceBundle objects which will be used by their
tag body.
fmt:setTimeZone It stores the time zone inside a time zone configuration variable.
fmt:setBundle It loads the resource bundle and stores it in a bundle configuration variable
or the named scoped variable.
fmt:message It display an internationalized message.
fmt:formatDate It formats the time and/or date using the supplied pattern
and styles. Ex:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<html>
<head>
<title>fmt:formatNumber Tag</title>
</head>
<body>
<h3>Formatting of Number:</h3>
<c:set var="Amount" value="9850.14115" />
<p> Formatted Number-1:
<fmt:formatNumber value="${Amount}" type="currency" /></p>
<p>Formatted Number-2:
<fmt:formatNumber type="number" groupingUsed="true"
value="${Amount}" /></p> 16. <p>Formatted Number-3:
<fmt:formatNumber type="number" maxIntegerDigits="3"
value="${Amount}" /></p> 18. <p>Formatted Number-4:
<fmt:formatNumber type="number" maxFractionDigits="6"
value="${Amount}" /></p> 20. <p>Formatted Number-5:
<fmt:formatNumber type="percent" maxIntegerDigits="4"
value="${Amount}" /></p> 22. <p>Formatted Number-6:
<fmt:formatNumber type="number" pattern="###.###$"
value="${Amount}" /></p> 24. </body>
</html>
JSTL XML tags
JSTL XML tags List
XML Tags Descriptions
x:out Similar to <%= ... > tag, but for XPath expressions.
x:parse It is used for parse the XML data specified either in the tag body or
an attribute.
x:set It is used to sets a variable to the value of an XPath expression.
x:choose It is a conditional tag that establish a context for mutually exclusive conditional
84
Advance java Programming (3160707) 220020107091
operations.
x:when It is a subtag of that will include its body if the condition evaluated be 'true'.
x:otherwise It is subtag of that follows tags and runs only if all the prior conditions evaluated
be 'false'.
x:if It is used for evaluating the test XPath expression and if it is true, it will processes its
body content.
x:transform It is used in a XML document for providing the XSL(Extensible Stylesheet
Language) transformation.
x:param It is used along with the transform tag for setting the parameter in the
XSLT style sheet. Ex:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<html>
<head>
<title>x:choose Tag</title>
</head>
<body>
<h3>Books Information:</h3>
<c:set var="xmltext">
<books>
<book>
<name>Three mistakes of my life</name>
<author>Chetan Bhagat</author>
<price>200</price>
</book>
<book>
<name>Tomorrow land</name>
<author>Brad Bird</author>
<price>2000</price>
</book>
</books>
</c:set>
<x:parse xml="${xmltext}" var="output"/>
<x:choose>
<x:when select="$output//book/author = 'Chetan bhagat'">
Book is written by Chetan bhagat
</x:when>
<x:when select="$output//book/author = 'Brad Bird'">
Book is written by Brad Bird
</x:when>
<x:otherwise>
The author is unknown...
</x:otherwise>
</x:choose>
</body>
</html>
85
Advance java Programming (3160707) 220020107091
86
Advance java Programming (3160707) 220020107091
</c:forEach>
</table>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1"> 5. <title>JSP CRUD Example</title>
</head>
<body>
<h1>JSP CRUD Example</h1>
<a href="adduserform.jsp">Add User</a>
<a href="viewusers.jsp">View Users</a>
</body>
</html>
adduserform.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1"> 5. <title>Add User Form</title>
</head>
<body>
<jsp:include page="userform.html"></jsp:include>
</body>
</html>
userform.html
87
Advance java Programming (3160707) 220020107091
<option>India</option>
<option>Pakistan</option>
<option>Afghanistan</option>
<option>Berma</option>
<option>Other</option>
</select>
</td></tr>
<tr><td colspan="2"><input type="submit" value="Add
User"/></td></tr> 22. </table>
</form>
adduser.jsp
<%@page import="com.javatpoint.dao.UserDao"%>
<jsp:useBean id="u"
class="com.javatpoint.bean.User"></jsp:useBean> 3.
<jsp:setProperty property="*" name="u"/>
<%
int i=UserDao.save(u);
if(i>0){
response.sendRedirect("adduser-success.jsp");
}else{
response.sendRedirect("adduser-error.jsp");
}
%>
User.java
package com.javatpoint.bean;
public class User {
private int id;
private String name,password,email,sex,country;
//generate getters and setters
}
UserDao.java
package com.javatpoint.dao;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import com.javatpoint.bean.User;
public class UserDao {
public static Connection getConnection(){
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
"","");
88
Advance java Programming (3160707) 220020107091
}catch(Exception e){System.out.println(e);}
return con;
}
public static int save(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"insert into register(name,password,email,sex,country)
values(?,?,?,?,?)");
ps.setString(1,u.getName());
ps.setString(2,u.getPassword());
ps.setString(3,u.getEmail());
ps.setString(4,u.getSex());
ps.setString(5,u.getCountry());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int update(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"update register set name=?,password=?,email=?,sex=?,country=?
where id=?"); 36. ps.setString(1,u.getName());
ps.setString(2,u.getPassword());
ps.setString(3,u.getEmail());
ps.setString(4,u.getSex());
ps.setString(5,u.getCountry());
ps.setInt(6,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int delete(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("delete from register where
id=?");
ps.setInt(1,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static List<User> getAllRecords(){
List<User> list=new ArrayList<User>();
try{
89
Advance java Programming (3160707) 220020107091
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from
register");
ResultSet rs=ps.executeQuery();
while(rs.next()){
User u=new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
u.setPassword(rs.getString("password"));
u.setEmail(rs.getString("email"));
u.setSex(rs.getString("sex"));
u.setCountry(rs.getString("country"));
list.add(u);
}
}catch(Exception e){System.out.println(e);}
return list;
}
public static User getRecordById(int id){
User u=null;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from register where
id=?");
ps.setInt(1,id);
ResultSet rs=ps.executeQuery();
while(rs.next()){
u=new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
u.setPassword(rs.getString("password"));
u.setEmail(rs.getString("email"));
u.setSex(rs.getString("sex"));
u.setCountry(rs.getString("country"));
}
}catch(Exception e){System.out.println(e);}
return u;
}
}
adduser-success.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1"> 5. <title>Add User Success</title>
</head>
<body>
<p>Record successfully saved!</p>
90
Advance java Programming (3160707) 220020107091
<jsp:include page="userform.html"></jsp:include>
</body>
</html>
adduser-error.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1"> 5. <title>Add User Error</title>
</head>
<body>
<p>Sorry, an error occurred!</p>
<jsp:include page="userform.html"></jsp:include>
</body>
</html>
viewusers.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1"> 5. <title>View Users</title>
</head>
<body>
<%@page
import="com.javatpoint.dao.UserDao,com.javatpoint.bean.*,java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Users List</h1>
<%
List<User> list=UserDao.getAllRecords();
request.setAttribute("list",list);
%>
<table border="1" width="90%">
<tr><th>Id</th><th>Name</th><th>Password</th><th>Email</th>
<th>Sex</th><th>Country</th><th>Edit</th><th>Delete</th></tr>
<c:forEach items="${list}" var="u">
<tr><td>${u.getId()}</td><td>${u.getName()}</td><td>${u.getPassw
ord()}</td>
<td>${u.getEmail()}</td><td>${u.getSex()}</td><td>${u.getCountry()
}</td> <td><a href="editform.jsp?id=${u.getId()}">Edit</a></td>
<td><a href="deleteuser.jsp?id=${u.getId()}">Delete</a></td></tr>
</c:forEach>
</table>
<br/><a href="adduserform.jsp">Add New User</a>
</body>
</html>
91
Advance java Programming (3160707) 220020107091
editform.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1"> 5. <title>Edit Form</title>
</head>
<body>
<%@page
import="com.javatpoint.dao.UserDao,com.javatpoint.bean.User"%>
<%
String id=request.getParameter("id");
User u=UserDao.getRecordById(Integer.parseInt(id));
%>
<h1>Edit Form</h1>
<form action="edituser.jsp" method="post">
<input type="hidden" name="id" value="<%=u.getId() %>"/>
<table>
<tr><td>Name:</td><td>
<input type="text" name="name" value="<%=
u.getName()%>"/></td></tr> 19. <tr><td>Password:</td><td>
<input type="password" name="password" value="<%=
u.getPassword()%>"/></td></tr> 21. <tr><td>Email:</td><td>
<input type="email" name="email" value="<%=
u.getEmail()%>"/></td></tr> 23. <tr><td>Sex:</td><td>
<input type="radio" name="sex" value="male"/>Male
<input type="radio" name="sex" value="female"/>Female </td></tr>
<tr><td>Country:</td><td>
<select name="country">
<option>India</option>
<option>Pakistan</option>
<option>Afghanistan</option>
<option>Berma</option>
<option>Other</option>
</select>
</td></tr>
<tr><td colspan="2"><input type="submit" value="Edit User"/></td></tr>
</table>
</form>
</body>
</html>
edituser.jsp
<%@page import="com.javatpoint.dao.UserDao"%>
<jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
<%
92
Advance java Programming (3160707) 220020107091
int i=UserDao.update(u);
response.sendRedirect("viewusers.jsp");
%>
deleteuser.jsp
<%@page import="com.javatpoint.dao.UserDao"%>
<jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
<%
UserDao.delete(u);
response.sendRedirect("viewusers.jsp");
%>
EXERCISE:
1. Write a JSP program using JSTL SQL taglib to display student details in tabular form by
iterating through the database table student.
display_data.jsp
<%@ page import="java.sql.*" %>
<%!
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
%>
<%
try {
out.println("Connecting to database...<br>");
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/student1", "root", "root");
out.println("Connection successful!<br>");
String query = "SELECT * FROM student_info";
pst = con.prepareStatement(query);
rs = pst.executeQuery();
%>
<html>
<head>
<title>Student Information</title>
</head>
<body>
<h2>Student Information Table</h2>
<table border="1">
<tr>
<th>Roll No</th>
<th>Name</th>
<th>Branch</th>
<th>Subject1</th>
93
Advance java Programming (3160707) 220020107091
<th>Subject2</th>
<th>Subject3</th>
<th>Semester</th>
</tr>
<% while (rs.next()) { %>
<tr>
<td><%= rs.getInt("RollNo") %></td>
<td><%= rs.getString("Name") %></td>
<td><%= rs.getString("Branch") %></td>
<td><%= rs.getString("Subject1") %></td>
<td><%= rs.getString("Subject2") %></td>
<td><%= rs.getString("Subject3") %></td>
<td><%= rs.getInt("Semester") %></td>
</tr>
<% } %>
</table>
</body>
</html>
<%
} catch (Exception e) {
out.println("Error: " + e.getMessage());
e.printStackTrace();
} finally {
if (rs != null) rs.close();
if (pst != null) pst.close();
if (con != null) con.close();
}
%>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee">
<web-app>
<servlet>
<servlet-name>JSPDisplay</servlet-name>
<jsp-file>/display_data.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>JSPDisplay</servlet-name>
<url-pattern>/display</url-pattern>
</servlet-mapping>
</web-app>
94
Advance java Programming (3160707) 220020107091
Output:
2. Write a login.jsp page to get the login information from user and authenticate user
with the database with JSTL SQL tags.
Login.jsp
</form>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username != null && password != null) {
<sql:setDataSource>
String jdbcURL = "jdbc:mysql://localhost:3306/userDB";
String jdbcUsername = "root";
String jdbcPassword = "root";
String query = "SELECT * FROM users WHERE username = ? AND password = ?";
<sql:setDataSource var="dataSource" driver="com.mysql.cj.jdbc.Driver"
url="${jdbcURL}" user="${jdbcUsername}" password="${jdbcPassword}" />
<!-- Query to validate the user credentials -->
<sql:query var="user" dataSource="${dataSource}">
SELECT * FROM users WHERE username = ? AND password = ?
</sql:query>
<%-- If we found the user, show the welcome message --%>
<c:if test="${not empty user.rows}">
<p>Login Successful! Welcome, ${user.rows[0].username}.</p>
</c:if>
<%-- If the user is not found, show an error message --%>
<c:if test="${empty user.rows}">
<p>Invalid username or password. Please try again.</p>
</c:if>
}
%>
</body>
</html>
96
Advance java Programming (3160707) 220020107091
Output:
EVALUATION:
Involvement Understanding / Timely Completion Total
Problem solving (3) (10)
(4)
(3)
97
Advance java Programming (3160707) 220020107091
EXPERIMENT NO: 8
TITLE: Introduction to JSF
The JSF API provides components (inputText, commandButton etc) and helps to manage
their states. It also provides server-side validation, data conversion, defining page
navigation, provides extensibility, supports for internationalization, accessibility etc.
The JSF Tag libraries are used to add components on the web pages and connect
components with objects on the server. It also contains tag handlers that implements the
component tag.
With the help of these features and tools, you can easily and effortlessly create server-side user
interface.
98
Advance java Programming (3160707) 220020107091
be "submit", "reset", or
"image"
An HTML <img>
h:graphicImage It displays an image. An image
element
99
Advance java Programming (3160707) 220020107091
It displays a formatted
h:outputFormat Plain text Plain text
message.
It displays a nested
An HTML <label>
h:outputLabel component as a label for Plain text
element
a specified input field.
An HTML <table>
h:panelGrid It displays a table. element with <tr> and A table
<td> elements
It groups a set of
A HTML <div> or
h:panelGroup components under one A row in a table
<span> element
parent.
100
Advance java Programming (3160707) 220020107091
JSF provides inbuilt components to create web pages. Here, we are creating a user registration for with the help of
JSF components. Follow the following steps to create the form.
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
@ManagedBean
@RequestScoped
public class User{
String name;
String email;
String password;
String gender;
String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
103
Advance java Programming (3160707) 220020107091
After submitting form, JSF renders response.xhtml file as a result web page.
EVALUATION:
Involvement Understanding / Timely Completion Total
Problem solving (3) (10)
(4)
(3)
104
Advance java Programming (3160707) 220020107091
EXPERIMENT NO: 9
105
Advance java Programming (3160707) 220020107091
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class UserDao {
public static int register(User u){
int i=0;
StandardServiceRegistry ssr = new
StandardServiceRegistryBuilder().configure("hibernate.cfg.xml"). build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory = meta.getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
i=(Integer)session.save(u);
t.commit();
session.close();
return i; } }
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">create</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property
name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property
name="connection.driver_class">oracle.jdbc.driver.OracleDriver</propert>
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
EVALUATION:
Involvement Understanding / Timely Completion Total
Problem solving (3) (10)
(4)
(3)
106
Advance java Programming (3160707) 220020107091
EXPERIMENT NO: 10
Spring AOP Overview : Most of the enterprise applications have some common crosscutting
concerns that is applicable for different types of Objects and modules. Some of the common
crosscutting concerns are logging, transaction management, data validation etc. In Object
Oriented Programming, modularity of application is achieved by Classes whereas in Aspect
Oriented Programming application modularity is achieved by Aspects and they are
configured to cut across different classes. Spring AOP takes out the direct dependency of
crosscutting tasks from classes that we can’t achieve through normal object oriented
programming model. For example, we can have a separate class for logging but again the
functional classes will have to call these methods to achieve logging across the application.
Aspect Oriented Programming Core Concept
Before we dive into implementation of Spring AOP implementation, we should understand the
core concepts of AOP.
Aspect: An aspect is a class that implements enterprise application concerns that cut across
multiple classes, such as transaction management. Aspects can be a normal class configured
through Spring XML configuration or we can use Spring AspectJ integration to define a class
as Aspect using @Aspect annotation. Join Point: A join point is the specific point in the
application such as method execution, exception handling, changing object variable values
etc. In Spring AOP a join points is always the execution of a method. Advice: Advices are
actions taken for a particular join point. In terms of programming, they are methods that gets
executed when a certain join point with matching pointcut is reached in the application. You
can think of Advices as Struts2 interceptors or Servlet Filters.
1. Pointcut: Pointcut are expressions that is matched with join points to determine whether
advice needs to be executed or not. Pointcut uses different kinds of expressions that
are matched with the join points and Spring framework uses the AspectJ pointcut
expression language.
2. Target Object: They are the object on which advices are applied. Spring AOP is
implemented using runtime proxies so this object is always a proxied object. What is
means is that a subclass is created at runtime where the target method is overridden
and advices are included based on their configuration.
3. AOP proxy: Spring AOP implementation uses JDK dynamic proxy to create the
Proxy classes with target classes and advice invocations, these are called AOP
proxy classes. We can also use CGLIB proxy by adding it as the dependency in the
Spring AOP project.
107
Advance java Programming (3160707) 220020107091
4. Weaving: It is the process of linking aspects with other objects to create the advised
proxy objects. This can be done at compile time, load time or at runtime. Spring
AOP performs weaving at the runtime.
EVALUATION:
Involvement Understanding / Timely Completion Total
Problem solving (3) (10)
(4)
(3)
108