You are on page 1of 57



Practical -1
Aim:Write a Program to create a GUI form using swing.

* Created on Jul 23, 2011, 2:29:58 PM
package gui1;

public class NewJFrame extends javax.swing.JFrame {
privateJPanel panel1,panel2;
privateJComboBox branch;

/** Creates new form NewJFrame */

publicNewJFrame(String t)




panel1=new JPanel();
lblFname=new JLabel("First Name:");
txtFname=new JTextField();
lblLname=new JLabel("Last Name:");
txtLname=new JTextField();
lblEnno=new JLabel("Enrollment No:");
txtEnno=new JTextField();
lblSem=new JLabel("Semester:");
txtSem=new JTextField();
lblBranch=new JLabel("Branch:");
branch=new JComboBox(new Object[] {

panel2=new JPanel();




lblEmail=new JLabel("Email:");
txtEmail=new JTextField();
lblCno=new JLabel("Contact No.:");
txtCno=new JTextField();
lblCourse=new JLabel("Course:");
ButtonGroup bg1=new ButtonGroup();
bg1.add(new JRadioButton("U.G."));
bg1.add(new JRadioButton("P.G"));
Enumeration e1=bg1.getElements();
JRadioButton rb1=(JRadioButton)e1.nextElement();
lblUni=new JLabel("University:");
ButtonGroup bg2=new ButtonGroup();
bg2.add(new JRadioButton("U.G."));
bg2.add(new JRadioButton("P.G"));
Enumeration e2=bg2.getElements();




JRadioButton rb2=(JRadioButton)e2.nextElement();

btnOk=new JButton("O.K.");
btnCancel=new JButton("Cancel");

Container cp=getContentPane();


public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
newNewJFrame("Student Details:").setVisible(true);







*. publicint flag.swing.ActionEventevt) { // TODO add your handling code here: buf. } private void jButton1ActionPerformed(java.ADVANCED JAVA TECHNOLOGY 090300107128 Practical -2 Aim:Write a Program of calculator package calculator.event. LDRP ITR 6 . /** Creates new form NewJFrame1 */ public NewJFrame1() { initComponents().awt. importjava. importjava.swing. public double var1. public class NewJFrame1 extends javax. jTextField1.*.awt. public double var2.event.awt.*. importjavax.toString()).append("1"). public double var3.setText(buf.Jframe { publicStringBufferbuf=new StringBuffer(""). public double var4.

awt. } private void jButton6ActionPerformed(java.ActionEventevt) { // TODO add your handling code here: buf.ADVANCED JAVA TECHNOLOGY 090300107128 } private void jButton2ActionPerformed(java.ActionEventevt) { // TODO add your handling code here: buf.setText(buf.awt.append("5").awt. jTextField1.append("6").setText(buf.event.toString()).append("2").setText(buf. } private void jButton4ActionPerformed(java.ActionEventevt) { // TODO add your handling code here: buf.toString()).awt.setText(buf. } private void jButton3ActionPerformed(java.event.setText(buf. jTextField1. jTextField1. } LDRP ITR 7 .event. jTextField1.toString()).event.toString()).append("4").awt.append("3"). jTextField1. } private void jButton5ActionPerformed(java.event.ActionEventevt) { // TODO add your handling code here: buf.ActionEventevt) { // TODO add your handling code here: buf.toString()).

event.setText(buf.setText(buf.ADVANCED JAVA TECHNOLOGY 090300107128 private void jButton7ActionPerformed(java.append("0").toString()). } private void jButton8ActionPerformed(java.append("8").event.ActionEventevt) { // TODO add your handling code here: buf.setText(buf.toString()). jTextField1. jTextField1.toString()).event.append("9").ActionEventevt) { // TODO add your handling code here: LDRP ITR 8 . } private void jButton16ActionPerformed(java.toString()).awt.setText("").event.awt.append("7").setText(buf.ActionEventevt) { // TODO add your handling code here: buf. jTextField1.awt.ActionEventevt) { // TODO add your handling code here: buf. } private void jButton10ActionPerformed(java.ActionEventevt) { // TODO add your handling code here: buf.awt.event.ActionEventevt) { // TODO add your handling code here: jTextField1. jTextField1. } private void jButton9ActionPerformed(java.event. } private void jButton15ActionPerformed(java.awt.awt.

buf = new StringBuffer(""). } private void jButton11ActionPerformed(java. } private void jButton12ActionPerformed(java.parseDouble(jTextField1. flag=2.setText("").awt.getText()).getText()). } private void jButton13ActionPerformed(java.parseDouble(jTextField1.parseDouble(jTextField1.getText()).getText()). jTextField1.parseDouble(jTextField1.setText(""). jTextField1.awt.event. buf=new StringBuffer("").ActionEventevt) { // TODO add your handling code here: var1 = Double. flag = 1. flag = 4.event. buf = new StringBuffer("").event. buf = new StringBuffer("").ActionEventevt) { // TODO add your handling code here: var1=Double.awt. } LDRP ITR 9 .ActionEventevt) { // TODO add your handling code here: var1 = Double. flag = 3.ADVANCED JAVA TECHNOLOGY 090300107128 var1 = Double. jTextField1.setText("").setText(""). jTextField1.

buf. jTextField1.append(var3). //buf = null. jTextField1. //buf = null.toString()).setText(buf. } else if(flag==3){ var3 = var1*var2. buf.toString()). jTextField1.append(var3). //buf = null. LDRP ITR 10 .setText("").setText(buf.ActionEventevt) { // TODO add your handling code here: var2 = Double.append(var3).append(var3). } else if(flag==2){ var3 = var1-var2.awt.event.setText(buf. if(flag==1){ var3 =var1+var2.ADVANCED JAVA TECHNOLOGY 090300107128 private void jButton14ActionPerformed(java.toString()).toString()). buf=new StringBuffer(). jTextField1. buf. } else{ var3 = var1/var2. buf.parseDouble(buf.

} /** * @paramargs the command line arguments */ public static void main(String args[]) { java. } // Variables declaration .do not modify privatejavax."). // buf = null.JButton jButton10.invokeLater(new Runnable() { public void run() { new NewJFrame1(). } private void jButton17ActionPerformed(java. } buf = new StringBuffer("").awt.setText(buf. } }).EventQueue.setText(buf.toString()).ActionEventevt) { // TODO add your handling code here: buf.JButton jButton1. LDRP ITR 11 .append(".event. jTextField1.awt.toString()).ADVANCED JAVA TECHNOLOGY 090300107128 jTextField1.swing.swing. privatejavax.setVisible(true).

privatejavax.swing. privatejavax.JButton jButton12.swing.swing.JButton jButton7.swing.swing.swing. privatejavax.JButton jButton8.JButton jButton4. privatejavax. privatejavax.JButton jButton2.swing. // End of variables declaration } LDRP ITR 12 .JTextField jTextField1.swing. privatejavax.swing.swing. privatejavax.JButton jButton13. privatejavax. privatejavax.swing.JButton jButton14. privatejavax. privatejavax. privatejavax.JButton jButton9.JLabel jLabel1.ADVANCED JAVA TECHNOLOGY 090300107128 privatejavax.JButton jButton3.JButton jButton11.swing. privatejavax.swing. privatejavax.JButton jButton15.JButton jButton5.JButton jButton6.swing.swing.JButton jButton17.swing. privatejavax.JPanel jPanel1.swing. privatejavax.JButton jButton16. privatejavax.swing.


*.ADVANCED JAVA TECHNOLOGY 090300107128 Practical -3 Aim:Write a Java Program which makes a database connection and print the metadata and name of driver.odbc.close(). importjava.getConnection(db. conn.out.println(“Driver name:”+md.sql.jdbc.out.ClassNotFoundException{ //get database connection String driverClassName="sun. System.JdbcOdbcDriver".getDatabaseProductName()). String db="jdbc:odbc:dtaSource"."".println(“Product name:”+md.getMetaData().""). //get metadata and name of driver DatabaseMetaData md=conn.forName(driverClassName). public class JDBCExample1 { public static void main(String args[]) throwsSQLException. package chapter1.getDriverName()). Connection conn=DriverManager. System. Class. } } LDRP ITR 14 .

dll) LDRP ITR 15 .ADVANCED JAVA TECHNOLOGY 090300107128 Output: Product name:ACCESS Driver name:JDBC-ODBC Bridge (odbcjt32.

LDRP ITR 16 .odbc."".Connection. Connection conn=dbConnection(). public class EmpData { public Connection dbConnection()throws Exception { Class.sql.forName("sun. PreparedStatement pre = conn. importjava. /*A class for retrieving EMP table data from the database*/ packageemp_example.sql.executeQuery().util. String db="jdbc:odbc:emp1".ResultSet. importjava.PreparedStatement.sql.prepareStatement("select * from emp"). importjava. ResultSetrs = pre. returnDriverManager.getConnection(db. importjava.""). } public Vector getEmployee()throws Exception { Vector<Vector<String>>employeeVector = new Vector<Vector<String>>().Vector.ADVANCED JAVA TECHNOLOGY 090300107128 Practical -4 Aim: Write a Program with Java GUI that displays the entire EMP table from the SAMPLE database in the JTABLE object . importjava.jdbc.sql.DriverManager.JdbcOdbcDriver").

//used for data from database private Vector<String> header.ADVANCED JAVA TECHNOLOGY 090300107128 while(rs. //name employee. importemp_example. } returnemployeeVector.add(rs. //Empid employee. //used to store data header publicEmp_frame() throws Exception{ //get data from database LDRP ITR 17 .add(rs.getString(3)). //dept employee. } } /*A frame for displaying EMP table data into JTABLE object*/ packageemp_example.add( { Vector<String> employee = new Vector<String>().Vector. importjava.getString(2)).swing. employee. public class Emp_frame extends javax.EmpData. //salary employeeVector.util.getString(4)).add(rs.JFrame { private Vector<Vector<String>> data.getString(1)).add(employee).

add("emp_Name").printStackTrace(). //Empid header.} } }). data = empdata.swing. // employee department header. //create header for the table header = new Vector<String>().JTable jTable1. // employee name header. }catch(Exception e){e. // employee salary initComponents().do not modify privatejavax. privatejavax.invokeLater(new Runnable() { public void run() { try { newEmp_frame().add("ID"). } // Variables declaration .setVisible(true). header.getEmployee().add("department").swing.EventQueue. } java. // End of variables declaration } LDRP ITR 18 .JScrollPane jScrollPane1.awt.add("salary").ADVANCED JAVA TECHNOLOGY 090300107128 EmpDataempdata = new EmpData().

ADVANCED JAVA TECHNOLOGY 090300107128 *Output:- LDRP ITR 19 .

txt" S-Format="TEXT/CSV" S-Label-Fields="TRUE" --> <p>User Id:&nbsp.&nbsp. <p>First Name: <input type="text" name="firstname" size="20"></p> <p>Lastname: <input type="text" name="lastname" size="20"></p> <p>Enrollment No:<input type="text" name="eno" size="20"></p> <p>Semester:<input type="text" name="sem" size="20"></p> <p>Branch:<input type="text" name="branch" size="20"></p> <p>Email Address: <input type="text" name="email" size="20"></p> <p>Contact No:<input type="text" name="cno" size="20"></p> LDRP ITR 20 .Document"> <title>New Page 1</title> </head> <body> <form method="POST" action="/sqlStatServlet/ServletUserEnquiryForm"> <!--webbot bot="SaveResults" U-File="fpweb:///_private/form_results. /*The code of the program is given below:*/ <html> <head> <meta http-equiv="Content-Language" content="en-us"> <meta http-equiv="Content-Type" content="text/html.&nbsp.0"> <meta name="ProgId" content="FrontPage.&nbsp.&nbsp.ADVANCED JAVA TECHNOLOGY 090300107128 Practical -5 Aim: Modify the program stated in 1 to include the database connectivity with it.&nbsp. The student details should be entered in the database using prepared statement. charset=windows-1252"> <meta name="GENERATOR" content="Microsoft FrontPage 4.Editor.&nbsp.

init(config). PrintWriter out = res. LDRP ITR 21 .* import javax. } /**Process the HTTP Get request*/ public void doPost(HttpServletRequestreq. res. IOException{ String connectionURL = "jdbc:mysql://localhost/zulfiqar".sql. import java. HttpServletResponse res) throws ServletException.*.getWriter().servlet. //get the variables entered in the form String fname = req. public class ServletUserEnquiryFormextends HttpServlet{ public void init(ServletConfigconfig) throws ServletException{ super.servlet.ADVANCED JAVA TECHNOLOGY 090300107128 <p>Course:<input type="text" name="course" size="20"></p> <p>University:<input type="text" name="uni" size="20"></p> <p><input type="submit" value="Submit" name="B1"></p> </form> </body> </html> ServletUserEnquiryForm. Connection connection=null.setContentType("text/html").java import java. import javax.getParameter("firstname").*.*. ResultSetrs.

getParameter("course").mysql.getParameter("uni").forName("org.setString(2.setString(3. pst. LDRP ITR 22 . pst. pst. // Get a Connection to the database connection = DriverManager.?.getParameter("lastname"). try { // Load the database driver Class.ADVANCED JAVA TECHNOLOGY 090300107128 String lname = req. String uni = req.getParameter("cno"). String branch = req. pst.getParameter("eno").getParameter("branch"). pst. lastname). course).prepareStatement(sql).setString(8.getConnection (connectionURL.?.getParameter("sem"). PreparedStatementpst = connection.eno).setString(5. pst. pst. String course = req.?.?. firstname).?. branch).?. "admin"). cno). sem). eno).gjt. String email = req. "root".setString(4.?)".Driver"). String eno = req. pst.setString(1. String cno = req.setString(6.getParameter("email"). String sem = //Add the data into the database String sql = "insert into emp_details values (?.

println("Couldn't load database driver: " + e.println(" '"+fname+"'").getMessage()).getMessage()).close().println(ignored). try { if (connection != null) connection. } catch (SQLException ignored){ out.close(). } } } } LDRP ITR 23 . uni). } catch (Exception e){ out. intnumRowsChanged = pst. out.ADVANCED JAVA TECHNOLOGY 090300107128 pst.println("SQLException caught: " + e.executeUpdate().setString(7.println(e). } catch(ClassNotFoundException e){ out. } catch(SQLException e){ out. pst. } finally { // Always close the database connection.

io. Objects of the ImmediateMessage class will connect to these server objects and a single message to be displayed at the server system. System. and then displays the information received on the connection. /*The code of theImmediateMessageServer:*/ import java.*.println("Connection established"). //connect it to client socket Socket s = ss. classImmediateMessageServer { public static void main(String args[ ]) throws Exception { //Create server socket ServerSocketss = new ServerSocket(888).*.net. import java.ADVANCED JAVA TECHNOLOGY 090300107128 Practical -6 Aim: Create a pair of classes called ImmediateMessage and ImmediateMessageServer. Objects of the ImmediateMessageServer class should listen on a specified port for a connection from other systems. //to read data coming from the client BufferedReaderbr = new BufferedReader(new InputStreamReader(s.accept().out.getInputStream())). while(true) //server executes continuously { LDRP ITR 24 .

*.net. ss. //repeat as long as client does not send null string while((str = br.close().close(). import java.ADVANCED JAVA TECHNOLOGY 090300107128 String str.println(str).close().exit(0). } //close connection br. LDRP ITR 25 .io. s.getOutputStream()).str1.out. classImmediateMessage { public static void main(String args[ ]) throws Exception { //Create client socket Socket s = new Socket("localhost". System. //terminate application } //end of while } } /*A code for ImmediateMessage class*/ import java.*.readLine()) != null) //read from client { System. 888). //to send data to the server DataOutputStream dos = new DataOutputStream(s.

//send to server } //close connection."\n").close().close(). s.readLine()). While(true){ String str.close(). //repeat as long as exit is not typed at client while(!(str = kb.equals("exit")) { dos.ADVANCED JAVA TECHNOLOGY 090300107128 //to read data from the key board BufferedReader kb = new BufferedReader(new InputStreamReader(System. } } } LDRP ITR 26 . kb.

class Server2 { public static void main(String args[ ]) throws Exception { //Create server socket ServerSocketss = new ServerSocket(888). //connect it to client socket Socket s = ss.println("Connection established"). //to read data coming from the client BufferedReaderbr = new BufferedReader(new LDRP ITR 27 . System.getOutputStream()).an empty string is returned. import They receive requests requests from TemperatureClient objects in the form of datagram.*.ADVANCED JAVA TECHNOLOGY 090300107128 Practical -7 Aim: Create a pair of classes called TemperatureServer and TemperatureClient.*. //to send data to the client PrintStreamps = new PrintStream(s. Each datagram contains the name of a city that the server looks up in its table. If the requested city cannot be found. Objects of the TemperatureServerclass contain a table of current temperatures for a number of cities around the world. /*The code of theTemperatureServer:*/ import java.accept(). The current temperature for the city is returned by the TemperatureServer object to the TemperatureClient object in a datagram.

//repeat as long as client does not send null string while((str = br.close().exit(0).out.println(str1). System.println(str).in)). ss. //terminate application } //end of while LDRP ITR 28 . //send to client } //close connection ps.close(). str1 = kb. while(true) //server executes continuously { String str. ps.close().ADVANCED JAVA TECHNOLOGY 090300107128 InputStreamReader(s.close().close(). //to read data from the key board BufferedReader kb = new BufferedReader(new InputStreamReader(System. br.readLine()) != null) //read from client { System. kb.readLine().str1.getInputStream())). s.

net.getOutputStream()).ADVANCED JAVA TECHNOLOGY 090300107128 } } /*The code of the TemperatureClient:*/ import java. //to read data from the key board BufferedReader kb = new BufferedReader(new InputStreamReader(System. //repeat as long as exit is not typed at client LDRP ITR 29 .*. //to send data to the server DataOutputStream dos = new DataOutputStream(s. //to read data coming from the server BufferedReaderbr = new BufferedReader(new InputStreamReader( classTemperatureClient { public static void main(String args[ ]) throws Exception { //Create client socket Socket s = new Socket("localhost". import java.getInputStream())).str1.*. 888).io. String str.

dos.close().out.equals("exit")) { dos.close().readLine().writeBytes(str+"\n").close().close(). //receive from server System.println(str1).readLine()). //send to server str1 = br. br. kb. } } LDRP ITR 30 . } //close connection. s.ADVANCED JAVA TECHNOLOGY 090300107128 while(!(str = kb.

} LDRP ITR 31 .registry.ADVANCED JAVA TECHNOLOGY 090300107128 Practical -8 Aim: Create a simple application that demonstrates the use of RMI. /* DemoInterface.RemoteException.RemoteException. importjava.rmi. importjava.Remote. publicDemoServer(String msg) throws RemoteException { message = msg. importjava.rmi. public interface DemoInterface extends Remote { public String SayDemo() throws*/ importjava. } private String message.Registry. importjava.UnicastRemoteObject.rmi. } /*DemoServer.server. public class DemoServer implements DemoInterface { publicDemoServer() { super()*/ importjava.registry.rmi.rmi.

LocateRegistry. Registry registry = LocateRegistry. importjava.Naming.out.getRegistry(). importjava.println ("Server is connected and ready for operation.Registry.setSecurityManager(new SecurityManager()). } } } /*DemoClient. System. DemoInterface stub = (DemoInterface) UnicastRemoteObject. stub).exportObject(h.rmi.rmi.registry. } public static void main (String[] argv) { try { DemoInterface h = new DemoServer("Hello"). LDRP ITR 32*/ importjava.registry.println ("Server not connected: " + e). } catch (Exception e) { System.getSecurityManager() == null) { System.rmi. registry.").rebind ("Hello". public class DemoClient { public static void main (String[] args) { if (System.ADVANCED JAVA TECHNOLOGY 090300107128 public String SayDemo() throws RemoteException { return message. 0).

println (h. } } } LDRP ITR 33 .getRegistry(args[0]).println ("DemoClient exception: " + e). } catch (Exception e){ System. System. DemoInterface h = (DemoInterface) reg.SayDemo()).ADVANCED JAVA TECHNOLOGY 090300107128 } try { Registry reg = LocateRegistry.out.out.lookup("Hello").

getWriter().//DTD Web Application 2.http.3//EN" "http://java.ADVANCED JAVA TECHNOLOGY 090300107128 Practical -9 Aim: Create a servlet that prints today’s date. pw. import java. IOException{ PrintWriter pw = response.*.println("<html>"+"<body><h1>Today Date is</h1>").*.servlet. Inc.*. HttpServletResponse response) throws ServletException.util. pw. } } XML File for this program <?xml version="1. Date today = new Date().0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems. import java.*.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>DateDisplay</servlet-class> </servlet> <servlet-mapping> LDRP ITR 34 .com/dtd/web-app_2_3. import javax.println("<b>"+ today+"</b></body>"+ "</html>"). import public class DisplayingDateextends HttpServlet{ public void doGet(HttpServletRequest request.sun.

ADVANCED JAVA TECHNOLOGY 090300107128 <servlet-name>Hello</servlet-name> <url-pattern>/DateDisplay</url-pattern> </servlet-mapping> </web-app> *Output:- Practical -10 LDRP ITR 35 .*/ importjava.servlet. LDRP ITR 36 . charset=windows-1256" pageEncoding="windows-1256" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.http.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/ /*Create a login page*/ <%@ page language="java" contentType="text/html.HttpServletRequest.01 Transitional//EN" "http://www.w3.IOException. importjavax.ADVANCED JAVA TECHNOLOGY 090300107128 Aim: Create a servlet for a login page. importjavax.servlet.servlet.http. If the username and password are correct then it says message “welcome <usernsme> else a message “login failed”. charset=windows-1256"> <title>Login Page</title> </head> <body> <form action="LoginServlet"> Please enter your username <input type="text" name="un"/><br> Please enter your password <input type="text" name="pw"/> <input type="submit" value="submit"> </form> </body> </html> /*loginservlet.servlet.http.ServletException.http.HttpServletResponse. importjavax.HttpSession. importjavax.

jsp"). user. } } } *Output:- LDRP ITR 37 .user).IOException { try { UserBean user = new UserBean().login(user).getParameter("un")).io. user = UserDAO. //error page } catch (ThrowabletheException) { System.setAttribute("currentSessionUser". if (user.jsp").ADVANCED JAVA TECHNOLOGY 090300107128 /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request. HttpServletResponse response) throwsServletException.getParameter("pw")). response.println(theException). user. session.isValid()) { HttpSession session = request.getSession(true).setPassword(request.setUserName(request.sendRedirect("invalidLogin.sendRedirect("userLogged.out. //logged-in page } else response. java.

ADVANCED JAVA TECHNOLOGY 090300107128 Practical -11 LDRP ITR 38 .

Integer count = (Integer)session. out.println("<BODY><H1>Session Tracking Demo</H1>").*.servlet. import java. importjavax.*. LDRP ITR 39 . out. out.intValue() + 1).println("You've visited this page " + count + ((count. IOException { res. if (count == null) count = new Integer(1).getWriter().ADVANCED JAVA TECHNOLOGY 090300107128 Aim: Create a servlet that uses Cookies to store the number of times a user has visited servlet.println("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>").println("<H2>Here is your session data:</H2>").println("<P>"). public class SessionTracker extends HttpServlet { public void doGet(HttpServletRequestreq. // Increment the hit count for this page." : " times.count". HttpServletResponse res) throws ServletException. // Get the current session object.intValue() == 1) ? " time.http.putValue("tracker. The value is saved // in this client's session under the name "tracker. // Display the hit count for this page session.setContentType("text/html").getValue("tracker.count"). out. PrintWriter out = res.")). create one if necessary HttpSession session = req. importjavax.*. else count = new Integer(count.count".count).servlet.

i <names. for (int i = 0. }} *Output:- LDRP ITR 40 .length.getValue(names[i]) + "<BR>"). i++) { out.println(names[i] + ": " + session.println("</BODY></HTML>").ADVANCED JAVA TECHNOLOGY 090300107128 String[] names = session. } out.getValueNames().

util.printStackTrace(). try { String debug = config. public void init(ServletConfigconfig) throws ServletException { super.PrintWriter. /* SnoopServlet Written by Gabriel Wong < */ package test. **/ public class SnoopServlet extends HttpServlet { privateboolean debug = true. } } public void doService(HttpServletRequest request.debug = false.equals("false")) this. /** * Tests the Servlet Client and Server Environment.> http://www. IOException { LDRP ITR 41 .init(config).http. importjava. if (debug != null &&debug.ADVANCED JAVA TECHNOLOGY 090300107128 Practical -12 Aim: Create a servlet that displays some header information from your request as well as any from data. importjavax. } catch (Throwable e) { e.getInitParameter("debug"). HttpServletResponse response) throwsServletException.*.Enumeration. importjava.servlet.servlet.*. private String prefix = "/apps".io.

print("<p><b>Cookies</b><br>").getValue()). out. out.getHeaderNames(). out. //Headers out. String headerName. out.print("</table>").print(cookie.print(cookie. PrintWriter out = response. if (debug) System.print("<p><b>Request Headers</b><br>").length.getWriter(). out. if (debug) { System.out. out.getValue()). } Cookie[] cookies = request.print("<html><title>Snoop</title><form method=post action=" + prefix + request. out.print("<tr><td>").print("<table border=1 >").print("<table border=1 >"). ct<cookies. if (debug) System.out.print("<tr><th>Name</th><th>Value</th></tr>").print("<p><center><b><FONT SIZE=+2>SnoopServlet</FONT></b></center>").print("</td><td>").getName() + ": " + cookie.print("<tr><th>Name</th><th>Value</th></tr>").getName()).println("**Cookies**"). if (cookies != null) { for (intct = 0.setContentType("text/html").ADVANCED JAVA TECHNOLOGY 090300107128 try { response. out.getCookies(). out. out. Enumeration headers = request. out.println(cookie.ct++){ cookie = cookies[ct]. //Cookies out.getRequestURI() + ">").println("**Request Headers**"). LDRP ITR 42 .print("</td><tr>").out. } } out. Cookie cookie.

out.getHeader(headerName).out. headerValue = request.print("</td><td>"). if (debug) System.print("<br><input type=submit name=Submit value=Submit><br>").print(parameterName). if (debug) System. out. parameterValue = request. out.print("<p><b>Request Parameters</b><br>").print("<tr><td>"). String parameterValue. out. Enumeration parameters = request. out. out.print("</td><tr>").print(headerValue).getParameter(parameterName).print(headerName).out. } out. //Method (GET/POST) out.print("</td><td>").print("<p><b>Method</b><br>"). LDRP ITR 43 . out. //Parameters out.println("**Method**").println(headerName + ": " + headerValue). out. out.print("Method: " + request. String parameterName. while (headers. out.print("<tr><th>Name</th><th>Value</th></tr>").nextElement().out. out.getParameterNames().getMethod()).hasMoreElements()){ parameterName = (String)parameters.out. out.hasMoreElements()) { headerName = (String)headers. if (debug) System.print("<table border=1 >").print(parameterValue).print("<tr><td>").ADVANCED JAVA TECHNOLOGY 090300107128 String headerValue. while (parameters. if (debug) System.getMethod()).print("</table>").println("Method: " + request.nextElement().println("**Request Parameters**"). out.

getQueryString()). //Servlet Path LDRP ITR 44 . if (debug) System.getPathInfo()). out.ADVANCED JAVA TECHNOLOGY 090300107128 out.print("<p><b>Path Info</b><br>").out.println("**Query String**").getPathTranslated()). if (debug) System. //Request URI out.print("</table>").out.getPathTranslated()).println("**Request URI**").out.getQueryString()). if (debug) System.println(parameterName + ": " + parameterValue). if (debug) System. if (debug) System. //PathInfo out.print("</td><tr>").println("Path Info: " + request.getPathInfo()).println("Query String: " + request.out.println("Path Translated: " + request.out. if (debug) System.out. out.print("Request URI: " + request.out.println("**Path Info**"). //Query String out.print("Query String: " + request.print("Path Info: " + request. if (debug) System.print("<p><b>Request URI</b><br>").print("Path Translated: " + request.getRequestURI()).println("Request URI: " + request. //Path Translated out.out.print("<p><b>Query String</b><br>"). if (debug) System. } out.println("**Path Translated**").out.getRequestURI()). if (debug) System. out. out.print("<p><b>Path Translated</b><br>").

if (debug) System.print("</form></html>"). HttpServletResponse response) throwsServletException.println("**Servlet Path**"). } } LDRP ITR 45 .out. if (debug) System.response). IOException { doService(request. IOException { doService(request.getServletPath()).printStackTrace().ADVANCED JAVA TECHNOLOGY 090300107128 out.println("Servlet Path: " + request.print("<p><b>Servlet Path</b><br>"). } } public void doGet(HttpServletRequest request.out. out.getServletPath()).print("Servlet Path: " + request.response). } public void doPost(HttpServletRequest request. } catch (Throwable e) { e. HttpServletResponse response) throwsServletException. out.

importjavax.getOutputStream().*.nextElement().toUpperCase().equals("text/html")) { DataInputStream ds = new DataInputStream(req. importjava. HttpServletResponse res) throwsServletException. if (req.getHeaderNames(). value).hasMoreElements()) { String header = (String)e. String value = req. LDRP ITR 46 .getContentType().*.io.setHeader(header. /** * This is an example of a simple Servlet.ADVANCED JAVA TECHNOLOGY 090300107128 Practical -13 Aim: Create a servlet filter that changes all text to upper case.servlet. res. */ public class UpperCaseFilter extends HttpServlet { public void service(HttpServletRequestreq. } ServletOutputStream out = res. String s.getHeader(header).Enumeration.getInputStream()). while (e.http. IOException { Enumeration e = req.util. while ( (s = ds.servlet. importjavax.*. import java.readLine()) != null) { String u = s.

getInputStream().read()) != -1) out. while ( (b = in.close().indexOf("IMG") != -1)) out.write(b). int b. } } else { ServletInputStream in = req. } out.ADVANCED JAVA TECHNOLOGY 090300107128 if((u.println(u).println(s). else out. } public String getServletInfo() { return "A simple servlet". } } LDRP ITR 47 .indexOf("HREF") != -1) || (u.

<%@page contentType="text/html" pageEncoding="UTF-8"%> <%@page import="java..Date()%> </body> </html> *Output: Mon.jsp > <html> <head> <meta http-equiv="Content-Type" content="text/html. charset=UTF-8"> <title>R4R Tech Soft</title> </head> <body> <!h1.*" %> <!program for display the "current Date/Time on browser"> <!save as a helloR4R. 23 Sept 2011 01:29:56 +053 LDRP ITR 48 used for display heading > <h1>Hello R4R Tech Soft! Current Date/Time</h1> <!dynamic content is generated: Date/Time> <%= new java..ADVANCED JAVA TECHNOLOGY 090300107128 Practical -14 Aim: Create a JSP that prints current date and time.

ADVANCED JAVA TECHNOLOGY 090300107128 Practical -15 Aim: Create a JSP that adds and subtracts two numbers.print("Subtraction of a and b :"+result2). int result1=a+b int result2-a-b. out. int b=2. %> </body> </html> *Output:Addition of a and b:7 Subtraction of a and b:3 LDRP ITR 49 . <%@ page language="java"%> <html> <head> <title>Add number program in JSP</title> </head> <body> <% int a=5.print("Additon of a and b :"+result1). out.

i++) { if((i%2)!=0) { out.i<=10. <%@ page language="java"%> <html> <head> <title>Odd number program in JSP</title> </head> <body> <% for(int i=0.print("<br>").ADVANCED JAVA TECHNOLOGY 090300107128 Practical -16 Aim: Create a JSP that prints odd numbers that come within a range. } } %> </body> </html> *Output:Odd number:1 3 5 7 9 LDRP ITR 50 . out.print("Odd number :"+i).

<a href=\"logout. } else { %> <form action="checkLogin.println("Welcome "+myname+" .ADVANCED JAVA TECHNOLOGY 090300107128 Practical -17 Aim: Create a JSP for login module. <HTML> <HEAD> <TITLE>Login using jsp</TITLE> </HEAD> <BODY> <H1>LOGIN FORM</H1> <% String myname= (String)session.getAttribute("username"). if(myname!=null) { out.jsp\" >Logout</a>").jsp"> <table> <tr> <td> Username : </td><td><input name="username" size=15 type="text" /></td> </tr> <tr> <td> Password : </td><td><input name="password" size=15 type="text" /></td> LDRP ITR 51 .

getParameter("password"). } // Here you put the check on the username and password if (username.println("Checking login<br>"). } LDRP ITR 52 .equals("admin") && password.toLowerCase().print("Invalid paramters ").println("Welcome " + username + " <a href=\"index.getParameter("username"). out.trim().trim().toLowerCase(). username).jsp\">Back to main</a>"). session.setAttribute("username".equals("admin")) { out.ADVANCED JAVA TECHNOLOGY 090300107128 </tr> </table> <input type="submit" value="login" /> </form> <% } %> </BODY> </HTML> /* Check Username & password*/ <% String username = request. if (username == null || password == null) { out. String password = request.

jsp\">Back</a>"). if(username!=null) { out.println("Invalid username and password").jsp\">Back</a>"). } else { out.println("You are already not login <a href=\"index.removeAttribute("username"). } %> /*for logout*/ <% String username=(String)session.println(username+" loged out. } %> LDRP ITR 53 . <a href=\"index.getAttribute("username"). session.ADVANCED JAVA TECHNOLOGY 090300107128 else { out.

ADVANCED JAVA TECHNOLOGY 090300107128 *Output:- LDRP ITR 54 .

sf.DB2Driver</property> <property name="hibernate.url">jdbc:db2:SAMPLE</property> <property name="">create-drop</property> <!">db2admin</property> <property name="hibernate.connection.connection.ADVANCED JAVA TECHNOLOGY 090300107128 Practical -18 Aim: Create a simple application of hibernate for inserting contact details that demonstrates O/R mapping.db2.connection.jdbc.hbm2ddl.pool_size">10</property> <property name="show_sql">true</property> <property name="dialect">net.Mapping files --> <mapping resource="contact.driver_class"> COM.password">db2admin</property> <property name=""/> </session-factory> </hibernate-configuration> LDRP ITR 55 .connection.dialect.DB2Dialect</property> <property name="hibernate.connection. <hibernate-configuration> <session-factory> <property name="hibernate.

printStackTrace().out. Session session= sessionFactory.setFirstName((String)contactForm. } } } LDRP ITR 56 .flush().get("firstName")).configure().buildSessionFactory().buildSessionFactory(). e.close().save(contact). } catch (HibernateException e) { System. session.ADVANCED JAVA TECHNOLOGY 090300107128 /*The AddContactAction. // Actual contact insertion will happen at this step session. public class HibernateStrutsPlugIn implements PlugIn{ public void init(ActionServlet arg0.openSession().java class executes this method:/* SessionFactorysessionFactory = new Configuration(). ModuleConfig arg1) throwsServletException { try { SessionFactorysessionFactory = new Configuration(). //Create new instance of Contact and set values in it by reading them from form object Contact contact = new Contact(). session.println("Error in configuringSessionFactory"). contact.configure().