0% found this document useful (0 votes)
55 views49 pages

1avdheshjava PDF

This practical file summarizes 10 experiments conducted as part of an Advanced Java Programming course. Each experiment demonstrates a different Java concept and includes the objective, description of code, screenshots and output. The concepts covered include event handling, servlets, request and response, JDBC operations, Spring, JQuery, Java Mail and JMS Queue. The file contains the index, details of each experiment and is submitted by a student as part of their coursework.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views49 pages

1avdheshjava PDF

This practical file summarizes 10 experiments conducted as part of an Advanced Java Programming course. Each experiment demonstrates a different Java concept and includes the objective, description of code, screenshots and output. The concepts covered include event handling, servlets, request and response, JDBC operations, Spring, JQuery, Java Mail and JMS Queue. The file contains the index, details of each experiment and is submitted by a student as part of their coursework.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

SHRI VAISHNAV VIDHYAPEETH

VISHWAVIDYALAYA
Department of Computer Science Engineering
(Session: 2021-22)

PRACTICAL FILE

Subject Name: Advanced Java Programming

Subject Code: BTCS-409 [P]

Submitted to: Mrs.Neha Agarwal

Submitted by: AVDHESH PRATAP SINGH

Enrollment no: 20100BTIT07697

AVDHESH PRATAP SINGH (20100BTIT07697) 1


SHRI VAISHNAV VIDHYAPEETH VISHWAVIDYALAYA
SHRI VAISHAV INSTITUTE OF SCIENCE AND TECHNOLOGY, BAROLI, INDORE-
453331

Department: Computer Science Engineering

INDEX
Batch: III Roll no: 21100BTCSE09993 Name: Siddharth Jain
S.no. Date of Code of Title Remarks
performing Experiment

How to set up multiple panels, compound borders,


1 07/02/2022.
combo boxes.

2 14/02/2022 Write a Program to implement Event handling.

Write a Program to develop Java Servlet and use


3 28/02/2022
request and response.

. Write a Program which allows the user to enter data


4 07/03/2022
in a jsp form and display in webpage.

5 21/03/2022 Show basic JDBC operation.

Create Servlet file which contains following function:


1) Connect 2) Create Database 3) Create table 4)
6 28/03/2022 Insert records into respective table 5) Update records
of particular table of database 6) Delete records from
table 7) Delete table and also Database.

7 07/04/2022 Write a program to demonstrate Spring.

8 14/04/2022 Write a program to demonstrate Jquery.

9 21/04/2022 Write a program to demonstrate Java Mail


functionalities.

10 28/04/2022 Write a brief description of JMS Queue.

AVDHESH PRATAP SINGH (20100BTIT07697) 2


Experiment:-01

 Objective: -How to set up multiple panels, compound borders, combo


boxes.

 Description :-

Multiple Panels :- A Jpanel is a subclass of Jcomponent class and it is an invisible


component in Java. The FlowLayout is a default layout for a JPanel. We can add most of the
components like buttons, text fields, labels, tables, lists, trees, etc. to a JPanel. We can also
add multiple sub-panels to the main panel using the add() method of Container class.

Compound Borders:-Every Jcomponent can have one or more borders. Borders are
incredibly useful objects that, while not themselves components, know how to draw the edges
of Swing components. Borders are useful not only for drawing lines and fancy edges, but also
for providing titles and empty space around components.

Combo Boxes:- JComboBox is a part of Java Swing package. JComboBox


inherits JComponent class . JComboBox shows a popup menu that shows a list
and the user can select a option from that specified list . JComboBox can be
editable or read- only depending on the choice of the programmer .

SwingSample.java

package LabAdvJava;

import java.awt.*;

import javax.swing.*;

import javax.swing.border.Border;

import javax.swing.border.CompoundBorder;

/**

* @author Siddharth Jain

*/

AVDHESH PRATAP SINGH (20100BTIT07697) 3


public class SwingSample {

public SwingSample() {

JFrame jf = new JFrame();

Border blueBorder = BorderFactory.createLineBorder(Color.BLUE, 3);

Border blackBorder = BorderFactory.createLineBorder(Color.BLACK,3);

Border border4 = new CompoundBorder(blackBorder, blueBorder);

String
Doctors[]={"Neurologist","Cardiologist","Dermatologist","Rheumatologist","Orthopedic","Optometri
st"};

JComboBox cbx1 = new JComboBox(Doctors);

cbx1.setBounds(100, 100, 180, 40);

String insti[]={"SVIIT","SVITS","SVITT","SVIM"};

JComboBox cbx2 = new JComboBox(insti);

cbx2.setBounds(100, 100,90,20);

String musicinstru[]={"Piano","Mandolin","Guitars","Percussions"};

JComboBox cbx3 = new JComboBox(musicinstru);

cbx3.setBounds(100, 100,90,20);

String PL[]={"Java","Python","R","C++"};

JComboBox cbx4 = new JComboBox(PL);

cbx4.setBounds(100, 100,90,20);

JPanel pnl1 = new JPanel();

JPanel pnl2= new JPanel();

JPanel pnl3 = new JPanel();

AVDHESH PRATAP SINGH (20100BTIT07697) 4


JPanel pnl4 = new JPanel();

pnl1.setLayout(null);

pnl2.setLayout(null);

pnl3.setLayout(null);

pnl4.setLayout(null);

JLabel lbl1=new JLabel("Panel 1");

JLabel lbl2=new JLabel("Panel 2");

JLabel lbl3=new JLabel("Panel 3");

JLabel lbl4=new JLabel("Panel 4");

lbl1.setBounds(120,50,200,50);

lbl2.setBounds(120,50,200,50);

lbl3.setBounds(120,50,200,50);

lbl4.setBounds(120,50,200,50);

pnl1.add(lbl1);

pnl2.add(lbl2);

pnl3.add(lbl3);

pnl4.add(lbl4);

pnl1.add(cbx1);

pnl2.add(cbx2);

pnl3.add(cbx3);

pnl4.add(cbx4);

pnl1 .setBackground(Color.lightGray);

AVDHESH PRATAP SINGH (20100BTIT07697) 5


pnl1 .setBounds(10,10,300,200);

//Panel 2

pnl2.setBackground(Color.YELLOW);

pnl2.setBounds(320,10,300,200);

//Panel 3

pnl3.setBackground(Color.ORANGE);

pnl3.setBounds(10,220,300,200);

//Panel 4

pnl4.setBackground(Color.blue);

pnl4.setBounds(320,220,300,200);

pnl1.setBorder(border4);

pnl2.setBorder(border4);

pnl3.setBorder(border4);

pnl4.setBorder(border4);

jf.add(pnl1);

jf.add(pnl2);

jf.add(pnl3);

jf.add(pnl4);

jf.setSize(600,600);

jf.setTitle("How to set up multiple panels, compound borders, combo boxes.");

jf.setLayout(null);

jf.setVisible(true);

public static void main(String[] args) {

SwingSample smp = new SwingSample();

} }

AVDHESH PRATAP SINGH (20100BTIT07697) 6


CodeScreenshots:-

Output Screenshot

AVDHESH PRATAP SINGH (20100BTIT07697) 7


Experiment:-02

Objective:- Write a Program to implement Event handling


Description :-An event can be defined as changing the state of an object or
behavior by performing actions. Actions can be a button click, cursor
movement, keypress through keyboard or page scrolling, etc. Event handling
usually involves three types of objects.

Objects that are used to hold and report information about the event.
Objects that are typically the source of events.Objects, called listeners, are
used to handle events

A source is an object that generates an event. This occurs when the internal
state of that object changes in some way. Sources may generate more than
one type of event. Some general Event Sources are: Button,
CheckBox,List,MenusItem,Window,TextItems Etc

Experiment02.java

package LabAdvJava;

import java.awt.*;

import java.awt.event.*;

/**

* @author Siddharth Jain

*/

class Experiment02 implements ActionListener{

TextField tf = new TextField();

Experiment02()

Frame fms = new Frame("Exp02 Event Handling");

AVDHESH PRATAP SINGH (20100BTIT07697) 8


tf.setBounds(60,50,170,20);

Button btn = new Button("Action Button");

btn.setBounds(90,140,120,40);

btn.addActionListener(this);

fms.add(btn);

fms.add(tf);

fms.setSize(250,250);

fms.setLayout(null);

fms.setVisible(true);

public void actionPerformed(ActionEvent e){

tf.setText("SVVV INDORE");

public static void main(String args[]){

Experiment02 ex = new Experiment02();

AVDHESH PRATAP SINGH (20100BTIT07697) 9


Experiment:-03

Objective:- Write a Program to develop Java Servlet and use request and response

Description :- Servlets are Java classes which service HTTP requests and implement the
javax.servlet.Servlet interface. Web application developers typically write servlets that
extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface
and is specially designed to handle HTTP requests.Java servlets are server-side programs
(running inside a web server) that handle clients' requests and return a customized or dynamic
response for each request. The dynamic response could be based on user's input (e.g., search,
online shopping, online transaction) with data retrieved from databases or other applications,
or time-sensitive data (such as news and stock prices).
Java servlets typically run on the HTTP protocol. HTTP is an asymmetrical request-response
protocol. The client sends a request message to the server, and the server returns a response
message

Index.html

<html>

<head>

<title>Exp03</title>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>

<h2>Exp03:- Write a Program to develop Java Servlet and use request and
response</h2> <br>

<form action="addition">

Enter 1st number :<input type="text" name="num1"><br>

Enter 2nd number :<input type="text" name="num2"><br>

<input type="submit">

AVDHESH PRATAP SINGH (20100BTIT07697) 10


</form>

</body>

</html>

Demo1.java

package Lab11;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**

* @author Siddharth Jain

*/

@WebServlet(name = "Addition" ,urlPatterns = {"/addition"})

public class Demo1 extends HttpServlet

@Override

protected void service(HttpServletRequest req, HttpServletResponse resp) throws


ServletException, IOException {

int x = Integer.parseInt(req.getParameter("num1"));

int y = Integer.parseInt(req.getParameter("num2"));

AVDHESH PRATAP SINGH (20100BTIT07697) 11


int Z = x+y;

System.out.println(Z);

resp.addHeader("Content-Type", "text/html" );

PrintWriter pw = resp.getWriter();

pw.write("<html> <body bgcolor='coral'>");

pw.write("<h3> Result is </h3>"+Z);

pw.write("</body</html>");

}}

AVDHESH PRATAP SINGH (20100BTIT07697) 12


CodeScreenshots

Outputs:-

AVDHESH PRATAP SINGH (20100BTIT07697) 13


Experiment:-04

 Objective:- Write a Program which allows the user to enter data in a jsp form and
display in webpage

Description:- JSP technology is used to create web application just like Servlet
technology. It can be thought of as an extension to Servlet because it provides more
functionality than servlet such as expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than
Servlet because we can separate designing and development. It provides some additional
features such as Expression Language, Custom Tags, etc.

Index.html
<!DOCTYPE html>

<!--

To change this license header, choose License Headers in Project Properties.

To change this template file, choose Tools | Templates

and open the template in the editor.

Author : Siddharth Jain

-->

<html>

<head>

<title>12th LAB</title>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>

<h2><b>Exp04:-Write a Program which allows the user to enter data in a jsp form and
display in webpage </b> </h2> <br>

AVDHESH PRATAP SINGH (20100BTIT07697) 14


<form action="12.jsp">

<input type="text" name="uname"> <br>

<input type="Submit" name="Send Info"> <br>

</form>

</body>

</html>

12.jsp
<%--

Document : 12

Created on : 21 Nov, 2021, 9:39:06 PM

Author : Siddharth Jain

--%>

<%@page import="java.io.PrintWriter"%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title </title>

</head>

<body>

<%

String str = request.getParameter("uname");

out.println("Welcome"+"\t"+str); %>

</body>

</html>

AVDHESH PRATAP SINGH (20100BTIT07697) 15


Screenshot of code

Outputs:-

AVDHESH PRATAP SINGH (20100BTIT07697) 16


Experiment:-05

 Objective:- Show basic JDBC operation


Description :-JDBC stands for Java Database Connectivity. JDBC is a Java API to
connect and execute the query with the database. It is a part of JavaSE (Java Standard
Edition). JDBC API uses JDBC drivers to connect with the database.
JDBC API to access tabular data stored in any relational database. By the help of JDBC API,
we can save, update, delete and fetch data from the database

Demo.java
package jdbc;

import java.beans.Statement;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

/**

* @author Siddharth Jain

*/

public class Demo {

public static void main(String[] args) throws SQLException {

try {

Class.forName("com.mysql.jdbc.Driver");

String url = "jdbc:mysql://localhost:3306/DEMO";

AVDHESH PRATAP SINGH (20100BTIT07697) 17


Connection cnn = DriverManager.getConnection(url,"sidd","sidd@R123");

java.sql.Statement stm = cnn.createStatement();

String query = "insert into student "

+ "value(101,'Vikas',23,'55554')";

int x = stm.executeUpdate(query);

System.out.println(x);

stm.close();

cnn.close();

} catch (ClassNotFoundException ex)

System.err.println("Driver Not Found !");

} catch (SQLException ex)

System.err.println(ex.getMessage());

}}

AVDHESH PRATAP SINGH (20100BTIT07697) 18


Experiment:-06
Objective:- Create Servlet file which contains following function: 1) Connect 2) Create
Database 3) Create table 4) Insert records into respective table 5) Update records of particular
table of database 6) Delete records from table 7) Delete table and also Database

Description :- A CRUD (Create, Read, Update and Delete) application is the most
important application for any project development. In Servlet, we can easily create CRUD
application.

Index.html
<!DOCTYPE html>

<html>

<head>

<title>Insert title here</title>

</head>

<body>

<h1>Add New Employee</h1>

<form action="SaveServlet" method="post">

<table>

<tr><td>Name:</td><td><input type="text" name="name"/></td></tr>

<tr><td>Password:</td><td><input type="password" name="password"/></td></tr>

<tr><td>Email:</td><td><input type="email" name="email"/></td></tr>

<tr><td>Country:</td><td>

<select name="country" style="width:150px">

<option>India</option>

<option>USA</option>

<option>UK</option>

AVDHESH PRATAP SINGH (20100BTIT07697) 19


<option>Other</option>

</select>

</td></tr>

<tr><td colspan="2"><input type="submit" value="Save Employee"/></td></tr>

</table>

</form>

<br/>

<a href="ViewServlet">view employees</a>

</body>

</html>

EMP.java

public class Emp {

private int id;

private String name,password,email,country;

public int getId() {

return id;

public void setId(int id) {

this.id = id;

public String getName() {

return name;

AVDHESH PRATAP SINGH (20100BTIT07697) 20


public void setName(String name) {

this.name = name;

public String getPassword() {

return password;

public void setPassword(String password) {

this.password = password;

public String getEmail() {

return email;

public void setEmail(String email) {

this.email = email;

public String getCountry() {

return country;

public void setCountry(String country) {

this.country = country;

}}

EMPDao.java
import java.util.*;

import java.sql.*;

public class EmpDao {

AVDHESH PRATAP SINGH (20100BTIT07697) 21


public static Connection getConnection(){

Connection con=null;

try{

Class.forName("com.mysql.cj.jdbc.Driver");

Connection cnn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/DEMO","sidd","sidd@R123");

}catch(Exception e){System.out.println(e);}

return con;

public static int save(Emp e){

int status=0;

try{

Connection con=EmpDao.getConnection();

PreparedStatement ps = con.prepareStatement("insert into "

+ "Employee(name,password,email,country) "

+ "value(?,?,?,?)");

ps.setString(1,e.getName());

ps.setString(2,e.getPassword());

ps.setString(3,e.getEmail());

ps.setString(4,e.getCountry());

status=ps.executeUpdate();

con.close();

}catch(Exception ex){ex.printStackTrace();}

return status;

AVDHESH PRATAP SINGH (20100BTIT07697) 22


}

public static int update(Emp e){

int status=0;

try{

Connection con=EmpDao.getConnection();

PreparedStatement ps=con.prepareStatement(

"update Employee set name=?,password=?,email=?,country=? where


id=?");

ps.setString(1,e.getName());

ps.setString(2,e.getPassword());

ps.setString(3,e.getEmail());

ps.setString(4,e.getCountry());

ps.setInt(5,e.getId());

status=ps.executeUpdate();

con.close();

}catch(Exception ex){ex.printStackTrace();}

return status;

public static int delete(int id){

int status=0;

try{

Connection con=EmpDao.getConnection();

PreparedStatement ps=con.prepareStatement("delete from Employee where id=?");

ps.setInt(1,id);

AVDHESH PRATAP SINGH (20100BTIT07697) 23


status=ps.executeUpdate();

con.close();

}catch(Exception e){e.printStackTrace();}

return status;

public static Emp getEmployeeById(int id){

Emp e=new Emp();

try{

Connection con=EmpDao.getConnection();

PreparedStatement ps=con.prepareStatement("select * from Employee where


id=?");

ps.setInt(1,id);

ResultSet rs=ps.executeQuery();

if(rs.next()){

e.setId(rs.getInt(1));

e.setName(rs.getString(2));

e.setPassword(rs.getString(3));

e.setEmail(rs.getString(4));

e.setCountry(rs.getString(5));

con.close();

}catch(Exception ex){ex.printStackTrace();}

return e;

public static List<Emp> getAllEmployees(){

AVDHESH PRATAP SINGH (20100BTIT07697) 24


List<Emp> list=new ArrayList<Emp>();

try{

Connection con=EmpDao.getConnection();

PreparedStatement ps=con.prepareStatement("select * from Employee");

ResultSet rs=ps.executeQuery();

while(rs.next()){

Emp e=new Emp();

e.setId(rs.getInt(1));

e.setName(rs.getString(2));

e.setPassword(rs.getString(3));

e.setEmail(rs.getString(4));

e.setCountry(rs.getString(5));

list.add(e);

con.close();

}catch(Exception e){e.printStackTrace();}

return list;

} }

SaveServlet.java
import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

AVDHESH PRATAP SINGH (20100BTIT07697) 25


@WebServlet(name = "SaveServlet",urlPatterns = {"/SaveServlet"})

public class SaveServlet extends HttpServlet {

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");

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

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

String password=request.getParameter("password");

String email=request.getParameter("email");

String country=request.getParameter("country");

Emp e=new Emp();

e.setName(name);

e.setPassword(password);

e.setEmail(email);

e.setCountry(country);

int status=EmpDao.save(e);

if(status<=0){

out.println("Sorry! unable to save record");

}else{

out.print("<p>Successfull!!</p>");

request.getRequestDispatcher("index.html").include(request, response);

}}

AVDHESH PRATAP SINGH (20100BTIT07697) 26


EditServlet.java
import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/EditServlet")

public class EditServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out=response.getWriter();

out.println("<h1>Update Employee</h1>");

String sid=request.getParameter("id");

int id=Integer.parseInt(sid);

Emp e=EmpDao.getEmployeeById(id);

out.print("<form action='EditServlet2' method='post'>");

out.print("<table>");

out.print("<tr><td></td><td><input type='hidden' name='id'


value='"+e.getId()+"'/></td></tr>");

out.print("<tr><td>Name:</td><td><input type='text' name='name'


value='"+e.getName()+"'/></td></tr>");

AVDHESH PRATAP SINGH (20100BTIT07697) 27


type='password'

out.print("<tr><td>Email:</td><td><input type='email' name='email'


value='"+e.getEmail()+"'/></td></tr>");

out.print("<tr><td>Country:</td><td>");

out.print("<select name='country' style='width:150px'>");

out.print("<option>India</option>");

out.print("<option>USA</option>");

out.print("<option>UK</option>");

out.print("<option>Other</option>");

out.print("</select>");

out.print("</td></tr>");

out.print("<tr><td colspan='2'><input type='submit' value='Edit &amp; Save


'/></td></tr>");

out.print("</table>");

out.print("</form>");

out.close();

EditServlet2.java
import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

AVDHESH PRATAP SINGH (20100BTIT07697) 28


public class EditServlet2 extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out=response.getWriter();

String sid=request.getParameter("id");

int id=Integer.parseInt(sid);

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

String password=request.getParameter("password");

String email=request.getParameter("email");

String country=request.getParameter("country");

Emp e=new Emp();

e.setId(id);

e.setName(name);

e.setPassword(password);

e.setEmail(email);

e.setCountry(country);

int status=EmpDao.update(e);

if(status>0){

response.sendRedirect("ViewServlet");

}else{

out.println("Sorry! unable to update record");

out.close();

}}

DeleteServlet.java

AVDHESH PRATAP SINGH (20100BTIT07697) 29


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("/DeleteServlet")

public class DeleteServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

String sid=request.getParameter("id");

int id=Integer.parseInt(sid);

EmpDao.delete(id);

response.sendRedirect("ViewServlet");

}}

ViewServlet.java

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**

AVDHESH PRATAP SINGH (20100BTIT07697) 30


*

* @author Siddharth Jain

*/

@WebServlet("/ViewServlet")

public class ViewServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out=response.getWriter();

out.println("<a href='index.html'>Add New Employee</a>");

out.println("<h1>Employees List</h1>");

List<Emp> list=EmpDao.getAllEmployees();

out.print("<table border='1' width='100%'");

out.print("<tr><th>Id</th><th>Name</th><th>Password</th><th>Email</th><th>C
ountry</th><th>Edit</th><th>Delete</th></tr>");

for(Emp e:list){

out.print("<tr><td>"+e.getId()+"</td><td>"+e.getName()+"</td><td>"+e.getPasswor
d()+"</td><td>"+e.getEmail()+"</td><td>"+e.getCountry()+"</td><td><a
href='EditServlet?id="+e.getId()+"'>edit</a></td><td><a
href='DeleteServlet?id="+e.getId()+"'>delete</a></td></tr>");

out.print("</table>");

out.close();

AVDHESH PRATAP SINGH (20100BTIT07697) 31


Output

AVDHESH PRATAP SINGH (20100BTIT07697) 32


Experiment:-07

 Objective:- Write a program to demonstrate Spring

Description :- A Spring MVC is a Java framework which is used to build web


applications. It follows the Model-View-Controller design pattern. It implements all the basic
features of a core spring framework like Inversion of Control, Dependency Injection.

A Spring MVC provides an elegant solution to use MVC in spring framework by the help
of DispatcherServlet. Here, DispatcherServlet is a class that receives the incoming request
and maps it to the right resource such as controllers, models, and views.

Index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Welcome to Spring Web MVC project</title>

</head>

<body>

<p>Hello! This is the default welcome page for a Spring Web MVC project.</p>

<p><i>To display a different welcome page for this project, modify</i>

<tt>index.jsp</tt> <i>, or create your own welcome page then change

the redirection in</i> <tt>redirect.jsp</tt> <i>to point to the new

welcome page and also update the welcome-file setting in</i>

<tt>web.xml</tt>.</p>

AVDHESH PRATAP SINGH (20100BTIT07697) 33


</body>

</html>

Dispatcher-Servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>

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

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:p="http://www.springframework.org/schema/p"

xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd

http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-
tx-4.0.xsd">

<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

<!--

Most controllers will use the ControllerClassNameHandlerMapping above, but

for the index controller we are using ParameterizableViewController, so we must

define an explicit mapping for it.

-->

<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

<property name="mappings">

<props>

<prop key="index.htm">indexController</prop>

AVDHESH PRATAP SINGH (20100BTIT07697) 34


</props>

</property>

</bean>

<bean id="viewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolver"

p:prefix="/WEB-INF/jsp/"

p:suffix=".jsp" />

<!--

The index controller.

-->

<bean name="indexController"

class="org.springframework.web.servlet.mvc.ParameterizableViewController"

p:viewName="index" />

</beans>

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

<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd">

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>/WEB-INF/applicationContext.xml</param-value>

</context-param>

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

<servlet>

<servlet-name>dispatcher</servlet-name>

AVDHESH PRATAP SINGH (20100BTIT07697) 35


<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<load-on-startup>2</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>dispatcher</servlet-name>

<url-pattern>*.htm</url-pattern>

</servlet-mapping>

<session-config>

<session-timeout>

30

</session-timeout>

</session-config>

<welcome-file-list>

<welcome-file>redirect.jsp</welcome-file>

</welcome-file-list>

</web-app>

Redirect.jsp
<%--

Views should be stored under the WEB-INF folder so that

they are not accessible except through controller process.

This JSP is here to provide a redirect to the dispatcher

servlet but should be the only JSP outside of WEB-INF.

--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<% response.sendRedirect("index.htm"); %>

AVDHESH PRATAP SINGH (20100BTIT07697) 36


Output

AVDHESH PRATAP SINGH (20100BTIT07697) 37


Experiment:-08

 Objective:- . Write a program to demonstrate Jquery

Description:- jQuery is a fast, small, and feature-rich JavaScript library. It makes things
like HTML document traversal and manipulation, event handling, animation, and Ajax much
simpler with an easy-to-use API that works across a multitude of browsers. With a
combination of versatility and extensibility, jQuery has changed the way that millions of
people write JavaScript.

EXP08.html

<!DOCTYPE html>

<!--

To change this license header, choose License Headers in Project Properties.

To change this template file, choose Tools | Templates

and open the template in the editor.

/**

* @author Siddharth Jain

*/

-->

<!DOCTYPE html>

<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script>

$(document).ready(function(){

$("#hide").click(function(){

AVDHESH PRATAP SINGH (20100BTIT07697) 38


$("p").hide();

});

$("#show").click(function(){

$("p").show();

});

});

</script>

</head>

<body>

<p>If you click on the "Hide" button, I will disappear.</p>

<button id="hide">Hide</button>

<button id="show">Show</button>

</body>

</html>

AVDHESH PRATAP SINGH (20100BTIT07697) 39


CodeScreenshot

Output

AVDHESH PRATAP SINGH (20100BTIT07697) 40


Experiment:-09

Objective:- . Write a program to demonstrate Java Mail functionalities .

Description:- The JavaMail is an API that is used to compose, write and

read electronic messages (emails).

The JavaMail API provides protocol-independent and plateform-independent framework for


sending and receiving mails.

The javax.mail and javax.mail.activation packages contains the core classes of JavaMail
API.

The JavaMail facility can be applied to many events. It can be used at the time of registering
the user (sending notification such as thanks for your interest to my site), forgot password
(sending password to the users email id), sending notifications for important updates etc. So
there can be various usage of java mail api.

Protocols used in JavaMail API


There are some protocols that are used in JavaMail API.

o SMTP

o POP

o IMAP

o MIME

o NNTP and others

Steps to send email using JavaMail API


There are following three steps to send email using JavaMail. They are as follows:

1. Get the session object that stores all the information of host like host name, username, password etc.

2. compose the message

3. send the message

AVDHESH PRATAP SINGH (20100BTIT07697) 41


EmailService.java
package Mail;

import java.util.Properties;

import javax.mail.Authenticator;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.AddressException;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

public class EmailService

public static void main(String[] args) {

AVDHESH PRATAP SINGH (20100BTIT07697) 42


{

String msg = "Hello this is Testing mail for Advance Java Lab Experiment
09 which is submitted to Neha Agarwal mam";

String username = "[email protected]";

String password = "Siddharth@900";

Properties props = System.getProperties();

String host = "smtp.gmail.com";

props.put("mail.smtp.starttls.enable", "true");

props.put("mail.smtp.host", host);

props.put("mail.smtp.user", username);

props.put("mail.smtp.password", password);

props.put("mail.smtp.port", "587");

props.put("mail.smtp.auth", "true");

Session session = Session.getInstance(props, new Authenticator()

@Override

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(username, password);

AVDHESH PRATAP SINGH (20100BTIT07697) 43


});

try

{ props.setProperty("mail.smtp.starttls.enable", "true");

props.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");

Message message = new MimeMessage(session);

message.setFrom(new InternetAddress(username));

message.setRecipients(

Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));

message.setSubject("Experiment09");

MimeBodyPart mimeBodyPart = new MimeBodyPart();

mimeBodyPart.setContent(msg, "text/html");

Multipart multipart = new MimeMultipart();

multipart.addBodyPart(mimeBodyPart);

message.setContent(multipart);

Transport.send(message);

catch (Exception me) {

System.out.println("Email Errro : " + me.getMessage());

}}}

AVDHESH PRATAP SINGH (20100BTIT07697) 44


CodeScreenshot

AVDHESH PRATAP SINGH (20100BTIT07697) 45


Experiment:-10

Objective:- . Write a brief description of JMS Queue

Messaging
Messaging is a method of communication between software components or applications. A
messaging system is a peer-to-peer facility: A messaging client can send messages to, and
receive messages from, any other client. Each client connects to a messaging agent that
provides facilities for creating, sending, receiving, and reading messages.

Messaging enables distributed communication that is loosely coupled. A component sends a


message to a destination, and the recipient can retrieve the message from the destination.
However, the sender and the receiver do not have to be available at the same time in order to
communicate. In fact, the sender does not need to know anything about the receiver; nor does
the receiver need to know anything about the sender. The sender and the receiver need to
know only which message format and which destination to use. In this respect, messaging
differs from tightly coupled technologies, such as Remote Method Invocation (RMI), which
require an application to know a remote application’s methods.

Messaging also differs from electronic mail (email), which is a method of communication
between people or between software applications and people. Messaging is used for
communication between software applications or software components.

About JMS API


The Java Message Service is a Java API that allows applications to create, send, receive, and
read messages. Designed by Sun and several partner companies, the JMS API defines a
common set of interfaces and associated semantics that allow programs written in the Java
programming language to communicate with other messaging implementations.

The JMS API minimizes the set of concepts a programmer must learn in order to use
messaging products but provides enough features to support sophisticated messaging
applications. It also strives to maximize the portability of JMS applications across JMS
providers in the same messaging domain.

The JMS API enables communication that is not only loosely coupled but also

 Asynchronous: A JMS provider can deliver messages to a client as they arrive; a client
does not have to request messages in order to receive them.
 Reliable: The JMS API can ensure that a message is delivered once and only once.
Lower levels of reliability are available for applications that can afford to miss messages
or to receive duplicate messages.

AVDHESH PRATAP SINGH (20100BTIT07697) 46


The JMS specification was first published in August 1998. The latest version is Version 1.1,
which was released in April 2002. You can download a copy of the specification from the
JMS web site: http://www.oracle.com/technetwork/java/index-jsp-142945.html.

Usage of JMS API


An enterprise application provider is likely to choose a messaging API over a tightly coupled
API, such as remote procedure call (RPC), under the following circumstances.

 The provider wants the components not to depend on information about other
components’ interfaces, so that components can be easily replaced.
 The provider wants the application to run whether or not all components are up and
running simultaneously.
 The application business model allows a component to send information to another and
to continue to operate without receiving an immediate response.

For example, components of an enterprise application for an automobile manufacturer can


use the JMS API in situations like these:

 The inventory component can send a message to the factory component when the
inventory level for a product goes below a certain level so that the factory can make
more cars.
 The factory component can send a message to the parts components so that the factory
can assemble the parts it needs.
 The parts components in turn can send messages to their own inventory and order
components to update their inventories and to order new parts from suppliers.
 Both the factory and the parts components can send messages to the accounting
component to update their budget numbers.
 The business can publish updated catalog items to its sales force.

Using messaging for these tasks allows the various components to interact with one another
efficiently, without tying up network or other resources. Figure 31-1 illustrates how this
simple example might work.

Figure 31-1 Messaging in an Enterprise Application

AVDHESH PRATAP SINGH (20100BTIT07697) 47


Manufacturing is only one example of how an enterprise can use the JMS API. Retail
applications, financial services applications, health services applications, and many others
can make use of messaging.

Working of JMS API with the Java EE Platform


When the JMS API was introduced in 1998, its most important purpose was to allow Java
applications to access existing messaging-oriented middleware (MOM) systems, such as
MQSeries from IBM. Since that time, many vendors have adopted and implemented the JMS
API, so a JMS product can now provide a complete messaging capability for an enterprise.

Beginning with the 1.3 release of the Java EE platform, the JMS API has been an integral
part of the platform, and application developers can use messaging with Java EE components.

The JMS API in the Java EE platform has the following features.

 Application clients, Enterprise JavaBeans (EJB) components, and web components can
send or synchronously receive a JMS message. Application clients can in addition
receive JMS messages asynchronously. (Applets, however, are not required to support
the JMS API.)
 Message-driven beans, which are a kind of enterprise bean, enable the asynchronous
consumption of messages. A JMS provider can optionally implement concurrent
processing of messages by message-driven beans.
 Message send and receive operations can participate in distributed transactions, which
allow JMS operations and database accesses to take place within a single transaction.

The JMS API enhances the Java EE platform by simplifying enterprise development,
allowing loosely coupled, reliable, asynchronous interactions among Java EE components
and legacy systems capable of messaging. A developer can easily add new behavior to a Java
EE application that has existing business events by adding a new message-driven bean to
operate on specific business events. The Java EE platform, moreover, enhances the JMS API
by providing support for distributed transactions and allowing for the concurrent
consumption of messages. For more information, see the Enterprise JavaBeans specification,
v3.0.

The JMS provider can be integrated with the application server using the Java EE Connector
architecture. You access the JMS provider through a resource adapter. This capability allows
vendors to create JMS providers that can be plugged in to multiple application servers, and it
allows application servers to support multiple JMS providers. For more information, see the
Java EE Connector architecture specification, v1.5.

Messaging Domains
There are two types of messaging domains in JMS.

1. Point-to-Point Messaging Domain


2. Publisher/Subscriber Messaging Domain

AVDHESH PRATAP SINGH (20100BTIT07697) 48


AVDHESH PRATAP SINGH (20100BTIT07697) 49

You might also like