1avdheshjava PDF
1avdheshjava PDF
VISHWAVIDYALAYA
Department of Computer Science Engineering
(Session: 2021-22)
PRACTICAL FILE
INDEX
Batch: III Roll no: 21100BTCSE09993 Name: Siddharth Jain
S.no. Date of Code of Title Remarks
performing Experiment
Description :-
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.
SwingSample.java
package LabAdvJava;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
/**
*/
public SwingSample() {
String
Doctors[]={"Neurologist","Cardiologist","Dermatologist","Rheumatologist","Orthopedic","Optometri
st"};
String insti[]={"SVIIT","SVITS","SVITT","SVIM"};
cbx2.setBounds(100, 100,90,20);
String musicinstru[]={"Piano","Mandolin","Guitars","Percussions"};
cbx3.setBounds(100, 100,90,20);
String PL[]={"Java","Python","R","C++"};
cbx4.setBounds(100, 100,90,20);
pnl1.setLayout(null);
pnl2.setLayout(null);
pnl3.setLayout(null);
pnl4.setLayout(null);
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);
//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.setLayout(null);
jf.setVisible(true);
} }
Output Screenshot
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.*;
/**
*/
Experiment02()
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);
tf.setText("SVVV INDORE");
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">
</head>
<body>
<h2>Exp03:- Write a Program to develop Java Servlet and use request and
response</h2> <br>
<form action="addition">
<input type="submit">
</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;
/**
*/
@Override
int x = Integer.parseInt(req.getParameter("num1"));
int y = Integer.parseInt(req.getParameter("num2"));
System.out.println(Z);
resp.addHeader("Content-Type", "text/html" );
PrintWriter pw = resp.getWriter();
pw.write("</body</html>");
}}
Outputs:-
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>
<!--
-->
<html>
<head>
<title>12th LAB</title>
<meta charset="UTF-8">
</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>
</form>
</body>
</html>
12.jsp
<%--
Document : 12
--%>
<%@page import="java.io.PrintWriter"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<%
out.println("Welcome"+"\t"+str); %>
</body>
</html>
Outputs:-
Demo.java
package jdbc;
import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*/
try {
Class.forName("com.mysql.jdbc.Driver");
+ "value(101,'Vikas',23,'55554')";
int x = stm.executeUpdate(query);
System.out.println(x);
stm.close();
cnn.close();
System.err.println(ex.getMessage());
}}
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>
</head>
<body>
<table>
<tr><td>Country:</td><td>
<option>India</option>
<option>USA</option>
<option>UK</option>
</select>
</td></tr>
</table>
</form>
<br/>
</body>
</html>
EMP.java
return id;
this.id = id;
return name;
this.name = name;
return password;
this.password = password;
return email;
this.email = email;
return country;
this.country = country;
}}
EMPDao.java
import java.util.*;
import java.sql.*;
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;
int status=0;
try{
Connection con=EmpDao.getConnection();
+ "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;
int status=0;
try{
Connection con=EmpDao.getConnection();
PreparedStatement ps=con.prepareStatement(
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;
int status=0;
try{
Connection con=EmpDao.getConnection();
ps.setInt(1,id);
con.close();
}catch(Exception e){e.printStackTrace();}
return status;
try{
Connection con=EmpDao.getConnection();
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;
try{
Connection con=EmpDao.getConnection();
ResultSet rs=ps.executeQuery();
while(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));
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;
@Override
response.setContentType("text/html");
String name=request.getParameter("name");
String password=request.getParameter("password");
String email=request.getParameter("email");
String country=request.getParameter("country");
e.setName(name);
e.setPassword(password);
e.setEmail(email);
e.setCountry(country);
int status=EmpDao.save(e);
if(status<=0){
}else{
out.print("<p>Successfull!!</p>");
request.getRequestDispatcher("index.html").include(request, response);
}}
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")
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("<table>");
out.print("<tr><td>Country:</td><td>");
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("</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;
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");
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.close();
}}
DeleteServlet.java
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")
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;
/**
*/
@WebServlet("/ViewServlet")
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<h1>Employees List</h1>");
List<Emp> list=EmpDao.getAllEmployees();
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();
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"%>
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<p>Hello! This is the default welcome page for a Spring Web MVC project.</p>
<tt>web.xml</tt>.</p>
</html>
Dispatcher-Servlet.xml
<?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"/>
<!--
-->
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</beans>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>
<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
<%--
--%>
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>
<!--
/**
*/
-->
<!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(){
});
$("#show").click(function(){
$("p").show();
});
});
</script>
</head>
<body>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>
Output
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.
o SMTP
o POP
o IMAP
o MIME
1. Get the session object that stores all the information of host like host name, username, password etc.
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;
String msg = "Hello this is Testing mail for Advance Java Lab Experiment
09 which is submitted to Neha Agarwal mam";
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");
@Override
try
{ props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");
message.setFrom(new InternetAddress(username));
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
message.setSubject("Experiment09");
mimeBodyPart.setContent(msg, "text/html");
multipart.addBodyPart(mimeBodyPart);
message.setContent(multipart);
Transport.send(message);
}}}
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 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.
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.
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.
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.
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.