Advance Java Lab Manual
Advance Java Lab Manual
LAB MANUAL
OF
ADVANCE JAVA PROGRAMMING
(3360701)
SEMESTER – 6
Certificate
This is to certify that
in_________
Institute vision:
To develop Skilled, Creative and Socially Sensitive Engineers to Satisfy the Needs of a
Changing Society.
Institute Mission:
Imparting Value Added Technical Education for Skill Development through
Adequate Resources, while Developing Aptitude for Lifelong Learning and
Promoting Creativity, Innovation and Entrepreneur Spirit.
Department vision:
To become a recognized leader in Gujarat by producing Technically Skilled, Creative,
Independent and Socially Inclined Diploma Computer Engineers contributing towards the
ever changing needs of society.
Department Mission:
(1) To provide quality undergraduate education in both the theory and applied computer
science and train the students to implement this knowledge to solve the problems of real
world.
(2) To develop positive attitude towards lifelong learning according to the demands of versatile
society.
(3) To support other academic and socially interactive programs conducted by the institute.
1) Design and develop Desktop, Web, and Android Application to provide Solution for
problems
2) Manage, support, and troubleshoot hardware, software, networking components,
operating system (OS), and data storage in IT Infrastructure.
Index
SR. Date C Signature
PRACTICAL
NO. O
1 1 Develop a program to Test life cycle of an Applet.
2 Develop a program to print “WELCOME TO APPLET” in center
of Applet window with BLUE color.
3 Develop an applet that draw a two circle of radius 50 pixel in
horizontal line (one black color, one red color)
4 Develop an applet that draws a circle. The dimension of the
applet should be 500 x 300 pixels. The circle should be centered
in the applet and have a radius of 100 pixels. Display your name
centered in a circle.( using drawOval() method)
5 Draw ten filled red circles in a vertical column in the center of
the applet.
6 Develop an applet that sets the background color to yellow and
draw circle of radius 50 pixels centered in the middle of the
applet. Fill the circle with red color.
7 Develop an Applet to display Your name and Your City name
using passing the parameters to the Applet.
8 2 Develop a program that contains TextField, Push Button and
Label in the frame, clicking on the button content of the
TextField will displayed on Label. If TextField is empty then
display "Please Enter Text" on Label.
9 Create an application that displays a frame with a menu bar.
When a user selects any menu or menu item, display that
selection on a text area in the center of the frame
10 2 Develop an program that contains three check boxes and 50 x 50
pixel canvas.The three checkboxes should be labeled “Red”,
“Green”,”Blue”. The selection of the check boxes determines the
color of the canvas. For example, if the user selects both “Red”
and “Blue”, the canvas should be purple.
PRAC. CO FACULTY
RB1 RB2 RB3 RB4 TOTAL DATE SIGN
NO. NO.
1 CO1
2 CO2
3 CO3
4 CO4
5 CO5
import java.applet.*;
import java.awt.*;
/*
<applet code="collage1.class" width="200" height="200">
</applet>
*/
public class collage1 extends java.applet.Applet {
msg+="init()";
}
public void start() {
msg+="start()";
}
public void stop(){
msg+="stop()";
}
public void paint(Graphics g) {
g.drawString(msg,100,100);
showStatus("Priyanshu applet");
}
}
output:-
import java.applet.*;
import java.awt.*;
Font f1;
public void init() {
f1 = new Font("Arial",Font.BOLD,18);
g.setColor(Color.blue);
g.setFont(f1);
g.drawString("Welcome to Priyanshu Applet",50,100);
showStatus("206530307032-Priyanshu Applet");
}
}
output:-
3. Develop an applet that draw a two circle of radius 50 pixel in horizontal line (one black
color, one red color)
import java.applet.*;
import java.awt.*;
Font f1;
public void init() {
f1 = new Font("Arial",Font.BOLD,18);
g.fillOval(50,100,100,100);
g.setColor(Color.black);
g.setColor(Color.red);
g.fillOval(210,100,100,100);
showStatus("206530307032-Priyanshu's Applet");
}
}
output:-
4. Develop an applet that draws a circle. The dimension of the applet should be 500 x 300
pixels. The circle should be centered in the applet and have a radius of 100 pixels. Display
your name centered in a circle.( using drawOval() method)
import java.applet.*;
import java.awt.*;
/*
<applet code = "P5.class" width="500" height="300">
</applet>
*/
setSize(50,50);
g.drawOval(50,150,200,200);
g.drawString("Priyanshu",140,240);
showStatus("206530307032--Priyanshu's applet");
}
}
output:-
5. Draw ten filled red circles in a vertical column in the center of the applet.
import java.applet.*;
import java.awt.*;
/*
<applet code = "P6.class" width="500" height="700">
</applet>
*/
setSize(50,50);
int x=50;
for(int i=0;i<10;i++){
g.setColor(Color.red);
g.fillOval(225,x,50,50);
x=x+50;
}
showStatus("206530307032--Priyanshu's applet");
}
output:-
6. Develop an applet that sets the background color to yellow and draw circle of radius 50
pixels centered in the middle of the applet. Fill the circle with red color.
import java.applet.*;
import java.awt.*;
/*<applet code="Practical6.class" height="400" width="400"></applet>*/
/*
*Set background color of an applet using
* void setBackground(Color c) method.
*/
public class Practical6 extends java.applet.Applet {
Font f1;
public void init() {
setSize(50,50);
f1 = new Font("Arial",Font.BOLD,18);
g.setColor(Color.red);
g.fillOval(50,100,100,100)
setBackground(Color.yellow);
showStatus("206530307032-Priyanshu's Applet");
}
}
output:-
7. Develop an Applet to display Your name and Your City name using passing the parameters
to the Applet.
import java.applet.*;
import java.awt.*;
/*<applet code="P7.class" height=300 width=600>
<param name="nm" value="Priyanshu Goodwani"> </param>
<param name="City" value="Gandhidham"> </param>
</applet>*/
public class P7 extends java.applet.Applet {
output:-
7(b)-Built an applet that displays a horizontal rectangle in its center. Let the rectangle fill with color from
left to right.
import java.awt.*;
/*<applet code="prac7_2.class" height="250" width="400"></applet>*/
public class prac7_2 extends java.applet.Applet {
output:-
8. Develop a program that contains TextField, Push Button and Label in the frame, clicking on the
button content of the Textield will displayed on Label. If TextField is empty then display "Please
Enter Text" on Label.
import java.awt.*;
import java.awt.event.*;
Frame f;
Label lb1;
Label lb2;
Button sub;
TextField txt;
public Practical8()
{
f = new Frame();
lb1 = new Label("Enter Name");
lb2 = new Label(" ");
txt = new TextField(10);
sub = new Button("Submit");
sub.addActionListener(this);
f.setSize(400,400);
f.show();
if(s.equals(""))
{
lb2.setText("Please Enter Text");
}
else
{
lb2.setText(s);
}
}
Output1:-
Output2:-
9. Create an application that displays a frame with a menu bar. When a user selects any menu or menu
item, display that selection on a text area in the center of the frame.
import java.awt.*;
import java.awt.event.*;
setSize(300,300);
setVisible(true);
MenuItem m1;
m1=new MenuItem("Open");
m1.addActionListener(this);
f.add(m1);
m1=new MenuItem("Close");
m1.addActionListener(this);
f.add(m1);
m1=new MenuItem("Undo");
m1.addActionListener(this);
e.add(m1);
setLayout(new FlowLayout(FlowLayout.CENTER));
add(a);
Output:-
10. Develop an program that contains three check boxes and 50 x 50 pixel canvas.The three checkboxes
should be labeled “Red”, “Green”,”Blue”. The selection of the check boxes determines the color of
the canvas. For example, if the user selects both “Red” and “Blue”, the canvas should be purple.
import java.awt.*;
import java.awt.event.*;
}
}
Output1:-
Output2:-
Output3:-
11. Develop a program that draws two sets of ever-decreasing rectangles one in outline form and one
filled alternately in black and white.
import java.awt.*;
import java.awt.event.*;
int x,y,w,h;
}
showStatus("Priyanshu's applet ");
}
}
Output:-
12. Develop a program to design a Registration Page using different sub classes of Jcomponent class and
display information in pop-up window.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
JTextField name,email;
JPasswordField pass;
JButton save;
public prac12() {
save=new JButton("Submit");
add(save);
save.addActionListener(this);
setSize(400,400);
setVisible(true);
}
Output1:-
Output2:-
13. Develop an applet that displays the position of the mouse at the upper left corner of the applet when it
is dragged or moved. Draw a 10x10 pixel rectangle filed with black at the current mouse position
import java.awt.*;
import java.awt.event.*;
//<applet code="Prac13.class" height="300" width="300"></applet>
public class Prac13 extends java.applet.Applet implements MouseMotionListener {
Label l1;
public void init() {
setLayout(null);
l1=new Label();
l1.setBounds(0,0,100,20);
add(l1);
addMouseMotionListener(this);
}
Output1:-
14. Develop an applet which draw a line between two points 1) mouse pressed and 2) mouse released
import java.awt.*;
import java.awt.event.*;
int x,y;
public practical14() {
addMouseListener(this);
setSize(600,600);
setVisible(true);
Output:-
15. Develop an applet which draw a string "Mouse Clicked" at the position of cursor when mouse is click
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
Output:-
16. Develop an applet that uses the mouse listener, which overrides only two methods which are
mousePressed and mouseReleased
import java.awt.*;
import java.awt.event.*;
public prac16() {
addMouseListener(this);
setSize(400,300);
setVisible(true);
Output:-
17. Develop an applet that contains one button. Initialize the label on the button to "start" and "stop",
when the user presses the button, which changes the label between these two values each time the
button is pressed.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
Output1:-
Output2:-
18. Develop a program that has only one button in the frame, clicking on the button cycles through the
colors: red->green->blue and so on. One color changes per click.(use getBackGround() method to get
import java.awt.*;
import java.awt.event.*;
Button b;
public prac18() {
setLayout(new FlowLayout());
add(b);
b.addActionListener(this);
setBackground(Color.red);
b.setSize(60,60);
setSize(400,300);
setVisible(true);
if(getBackground()==Color.red){
setBackground(Color.green);
}else if(getBackground()==Color.green){
setBackground(Color.blue);
else if(getBackground()==Color.blue){
setBackground(Color.red);
new prac18();
Output1:-
Output2:-
Output3:-
19. Develop a JDBC application that uses any JDBC driver to perform insert, update, delete and display
all records in/from database. (Assume suitable database)
import java.awt.*;
import java.sql.*;
try {
Class.forName(JDBC_DRIVER);
stmt = conn.createStatement();
System.out.println();
System.out.println("Creating table student...");
stmt.executeUpdate("create table student5 (rollno int, name varchar(20), sem varchar(20))");
stmt.executeUpdate("insert into student5 (rollno,name,sem)values(1,'priyanshu','six)");
stmt.executeUpdate("insert into student5 (rollno,name,sem)values(2,'sumit',' six')");
stmt.executeUpdate("insert into student5 (rollno,name,sem)values(3,'om',' three')");
System.out.println(row);
}
System.out.println();
System.out.println("----------------");
System.out.println("Updating table...");
stmt.executeUpdate("update student5 set name='priyasnhu', sem='six' where rollno=1");
System.out.println("-------------");
ResultSet r = stmt.executeQuery("select * from student5");
while (r.next()) {
String row = (r.getInt(1) + " " + r.getString(2) + " " + r.getString(3));
System.out.println(row);
}
Output1:-
20. Develop a Graphical User Interface that performs the following SQL operations: a) Insert b) Delete c)
Update. (Assume suitable database)
import java.sql.*;
import javax.swing.JOptionPane;
Connection connection;
public Student_Registration() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("ID");
jLabel2.setText("Student Name:");
jLabel3.setText("Enrollment No:");
jLabel4.setText("Address");
jButton1.setText("Search");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Insert");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton4.setText("Delete");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton5.setText("Update");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField2)
.addComponent(jTextField3)))
.addGroup(layout.createSequentialGroup()
.addGap(67, 67, 67)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 80,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 82,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 77,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 277,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(111, 111, 111))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 182,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
getAccessibleContext().setAccessibleName("ID");
pack();
}// </editor-fold>
ResultSet rs = null;
Statement stmt = connection.createStatement();
rs = stmt.executeQuery(Qry);
boolean f = false;
while (rs.next()) {
f = true;
jTextField1.setText(rs.getString(2));
jTextField3.setText("" + rs.getString(4));
jLabel1.setText(rs.getString(1));
}
if (!f) {
System.out.println("Record Not Found");
}
} catch (SQLException e) {
System.out.println(e);
}
}
try {
load();
String Qry = "insert into temp(s_name,s_enroll,addr) values('" + jTextField1.getText() + "','" +
jTextField2.getText() + "','" + jTextField3.getText() + "') ";
Statement stmt = connection.createStatement();
stmt.executeUpdate(Qry);
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
System.out.println("Record Inserted");
} catch (SQLException e) {
System.out.println(e);
}
}
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jLabel1.setText("ID");
System.out.println("Record Deleted");
} else {
System.out.println("Please Select Proper Id");
}
} catch (SQLException e) {
System.out.println(e);
}
}
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jLabel1.setText("ID");
System.out.println("Record Updated");
} else {
System.out.println("Please Select Proper Id");
}
} catch (SQLException e) {
System.out.println(e);
}
}
connection = DriverManager.getConnection(connectionUrl,"root","");
pstmt.setString(1,"sneh");
pstmt.setString(2,"14");
pstmt.setString(3,"Anjar");
pstmt.executeUpdate();
String snames[]={"a","b","c","d"};
String senrolls[]={"1","2","3","4"};
String sadrs[]={"a2","b2","c2","d2"};
for(int i=0;i<snames.length;i++)
{
pstmt.setString(1,snames[i]);
pstmt.setString(2,senrolls[i]);
pstmt.setString(3,sadrs[i]);
}
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
JOptionPane.showMessageDialog(this, "All Value Inserted");
} catch (ClassNotFoundException | SQLException e) {
System.out.println(e);
} }
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Student_Registration.class.getName()).log(java.util.logging.Le
vel.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Student_Registration.class.getName()).log(java.util.logging.Le
vel.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Student_Registration.class.getName()).log(java.util.logging.Le
vel.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Student_Registration.class.getName()).log(java.util.logging.Le
vel.SEVERE, null, ex);
}
//</editor-fold>
});
}
Output1:-
Output2:-
21. Develop a program to present a set of choice for user to select a product and display the price of
product.
package collage;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Connection connection;
public prac21() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}
});
jButton1.setText("View Price");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
)
.addComponent(jLabel4))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED
)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE,
130, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addGap(129, 129, 129)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 96,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(156, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(33, 33, 33)
.addComponent(jLabel1)
.addGap(42, 42, 42)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(37, 37, 37)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 34,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52,
Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(41, 41, 41))
);
pack();
}// </editor-fold>
} catch (SQLException e) {
System.out.println(e);
}
}
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(prac21.class.getName()).log(java.util.logging.Level.SEVE
RE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(prac21.class.getName()).log(java.util.logging.Level.SEVE
RE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(prac21.class.getName()).log(java.util.logging.Level.SEVE
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new prac21().setVisible(true);
}
});
}
Output:-
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet prac22</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello World</h1>");
out.println("</body>");
out.println("</html>");
}
}
}
Output:-
23. Develop a servlet to read values of textboxes and display its values on the page using doGet() and
doPost() methods, from an HTML code (create login form having one submit button, two textboxes
labeled as Login name and Password respectively) when user clicked on submit button.
Prac23.html:
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method="post" action="prac23">
Name:<input type="text" name="name"/><br/>
Password:<input type="password" name="upass"/><br/>
<input type="submit" value="Login" name="Sub"/>
</form>
</body>
</html>
OUTPUT 1 :
OUTPUT 2 :
24. Develop a simple servlet program which maintains a counter for the number of times it has been
accessed since its loading; initialize the counter using deployment descriptor.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
int c=0;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet prac24</title>");
out.println("</head>");
out.println("<body>");
c++;
out.println("<h1>The Vistor Count is "+c);
out.println("</body>");
out.println("</html>");
}
}
}
WEB.XML:
<servlet>
<servlet-name>prac24</servlet-name>
<servlet-class>prac24</servlet-class>
<init-param>
<param-name>Count</param-name>
<param-value>0</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>prac24</servlet-name>
<url-pattern>/prac24</url-pattern>
</servlet-mapping>
OUTPUT :
25. Create a web form which processes servlet and demonstrates use of cookies and sessions.
Prac_25.html:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
Prac_25.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet prac25</title>");
out.println("</head>");
out.println("<body>");
String n=request.getParameter("fname");
HttpSession session=request.getSession();
session.setAttribute("s_name",n);
}
}
}
Prac25_1.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet prac25_1</title>");
out.println("</head>");
out.println("<body>");
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("s_name");
out.println("<b>Session Value:<b/>"+ n +"<br/>");
Cookie[] c=request.getCookies();
for(int i=0;i<c.length;i++){
String name=c[i].getName();
String value=c[i].getValue();
out.println("<b>Cookie name:</b>"+name+"<b>,Cookievalue:</b>"+value+"<br/>");
}
out.println("</body>");
out.println("</html>");
}
}
}
OUTPUT 1 :
OUTPUT 2 :
OUTPUT 3:
26. Develop servlet to read records from database and displaying them on page.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Connection connection;
Statement stmt;
ResultSet rs;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet prac26</title>");
out.println("</head>");
out.println("<body>");
try{
Class.forName("com.mysql.jdbc.Driver");
String connectionUrl = "jdbc:mysql://localhost:3306/data";
connection = DriverManager.getConnection(connectionUrl,"root","");
rs=null;
stmt = connection.createStatement();
rs=stmt.executeQuery("select * from demo");
while(rs.next()){
out.println("<h5>Id:"+rs.getInt(1)+",Name:"+rs.getString(2)+"</h5><br/>");
}
Output:-
27. Develop a JSP to determine how many times the visitors has loaded the page.
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Visitor Counter</title>
</head>
<body>
<h1>Visitor Counter</h1>
<%-- Read the visitor count from the file --%>
<% int count = 0;
String fileName = "visitorCount.txt";
try {
File file = new File(fileName);
if (file.exists()) {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
if (line != null) {
count = Integer.parseInt(line);
}
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
count++;
try {
FileWriter writer = new FileWriter(fileName);
writer.write(String.valueOf(count));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
%>
<p>You are visitor number <%= count %> to this page.</p>
</body>
</html>
Output:-
<!DOCTYPE html>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<%
Connection connection;
Statement stmt;
ResultSet rs;
String query;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionUrl,"root","");
rs=null;
stmt = connection.createStatement();
//Insert Code
%>
<h3>Record Inserted...</h3>
<%
//Update Code
%>
<h3>Record Updated...</h3>
<%
//Delete Code
%>
<h3>Record Deleted...</h3>
<%
//showing record
while(rs.next()){
%>
<%
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
%>
</body>
</html>
Output:-