2016 Batch
Asian
2.Write a program passing parameter in applet.Write complete HTML file to include applet.
1 2 3 4 5 6 7 8 |
import java.applet.Applet; import java.awt.Graphics; public class UseParam extends Applet{ public void paint(Graphics g){ String str=getParameter("msg"); g.drawString(str,50, 50); } } |
3.Explain two key swing features.
Swing offers two key features:
Swing components are lightweight and don’t rely on peers. Swing supports a pluggable look and feel. The three PLAFs available to all users are Metal (default), Windows, and Motif.
4.Write a swing program demonstrating GridLayout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package assignment; import java.awt.*; import javax.swing.*; public class GridLayoutDemo{ public GridLayoutDemo(){ JFrame f=new JFrame(); JButton b1=new JButton("1"); JButton b2=new JButton("2"); JButton b3=new JButton("3"); JButton b4=new JButton("4"); JButton b5=new JButton("5"); JButton b6=new JButton("6"); JButton b7=new JButton("7"); JButton b8=new JButton("8"); JButton b9=new JButton("9"); f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); f.add(b6);f.add(b7);f.add(b8);f.add(b9); f.setLayout(new GridLayout(3,3,10,2)); f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { try { // UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); // UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception e) { System.out.println("Look and Feel not set"); } new GridLayoutDemo(); } } |
Long Answer Questions:
7.Write a program to insert data using JDBC in MYSql database called contact_db.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package database; import java.sql.*; public class InsertData { public static void main(String args[]) throws Exception { String url = "jdbc:mysql://localhost:3307/contact_db"; String uname = "root"; String pwd = ""; Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, uname, pwd); Statement stmt = con.createStatement(); stmt.executeUpdate("insert into user values(15,'Sush',23,'Sundarijal')"); System.out.println("records affected"); con.close(); } } |
8.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
package swing-demo; import javax.swing.*; import java.awt.*; import java.awt.event.*; class Sushmita implements ActionListener { JFrame frame = new JFrame("Registration Form"); Container con = frame.getContentPane(); JLabel headLbl, nameLabel, addressLabel, genderLabel, hobbyLabel; JTextField nameTextFeild, addressTextField; JComboBox cb; JRadioButton r1, r2; ButtonGroup gender = new ButtonGroup(); JComboBox music, sport; JButton submit, reset; JTextArea display; Sushmita() { frame.setBounds(150, 90, 740, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); con.setBackground(Color.YELLOW); con.setLayout(null); Font f = new Font("Times New Roman", Font.BOLD, 30); headLbl = new JLabel("Registration Form"); headLbl.setBounds(250, 5, 400, 35); headLbl.setFont(f); con.add(headLbl); nameLabel = new JLabel("Name"); nameLabel.setBounds(50, 50, 60, 30); con.add(nameLabel); genderLabel = new JLabel("Gender"); genderLabel.setBounds(50, 100, 60, 30); con.add(genderLabel); addressLabel = new JLabel("Address"); addressLabel.setBounds(50, 150, 60, 30); con.add(addressLabel); nameTextFeild = new JTextField(); nameTextFeild.setBounds(130, 53, 180, 20); con.add(nameTextFeild); r1 = new JRadioButton("Male"); r1.setBounds(130, 103, 80, 20); r1.setBackground(Color.YELLOW); con.add(r1); r2 = new JRadioButton("Female"); r2.setBounds(250, 103, 80, 20); r2.setBackground(Color.YELLOW); con.add(r2); gender.add(r1); gender.add(r2); addressTextField = new JTextField(); addressTextField.setBounds(130, 150, 180, 20); con.add(addressTextField); hobbyLabel = new JLabel("Hobby"); hobbyLabel.setBounds(50, 200, 60, 30); con.add(hobbyLabel); String hobbies[] = { "music", "sports" }; cb = new JComboBox<>(hobbies); cb.setBounds(110, 200, 90, 20); con.add(cb); submit = new JButton("SUBMIT"); submit.setBounds(100, 350, 80, 25); con.add(submit); reset = new JButton("RESET"); reset.setBounds(200, 350, 80, 25); con.add(reset); Font ff = new Font("Times New Roman", Font.BOLD, 15); display = new JTextArea(); display.setBounds(400, 50, 300, 350); con.add(display); display.setFont(ff); display.setBackground(Color.GRAY); display.setEditable(false); submit.addActionListener(this); reset.addActionListener(this); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { String ch = e.getActionCommand(); if (ch == "SUBMIT") { String name = nameTextFeild.getText(); String gen = "male"; if (r2.isSelected()) { gen = "female"; } String address = addressTextField.getText(); String hobby = cb.getSelectedItem().toString(); display.setText( "\n\nName: " + name + "\nGender: " + gen + "\nAddress: " + address + "\nHobby: " + hobby); } else { nameTextFeild.setText(null); addressTextField.setText(null); display.setText(null); gender.clearSelection(); } } } public class Registration { public static void main(String[] args) { Sushmita sp = new Sushmita(); } } |
NCC
Group-B
Qno.2.
Source Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.sql.*; public class question_2 { Public static void main(String[] args) { String sql=”select * from student_db”; String url=”jdbc:mysql://localhost:3306/college_db”; String user=”root”; Statement st=null; Connection con=null; try { Class.forName(“com.mysql.jdbc.Driver”); conn=DriverManager.getConnection(url,user,””); if(conn!=null) { st=conn.createStatement(); ResultSet rs=st.executeQuery(sql); While(rs.next()) { System.out.println(“ID:”+rs.getInt(“id”)); System.out.println(“Name:”+rs.getString(“name”)); System.out.println(“Roll:”+rs.getInt(“roll”)); System.out.println(“Marks:”+rs.getInt(“marks”)); } } } catch(SQLException | ClassNotFoundException e) { e.printStackTrace(); } } } |
Qno.3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import javax.swing ; public class Factorial extends JFrame public class Factorical(){ Jlabel l1 = new JLabel ("Enter number”); Jlabel l2= new JLabel (""Result"”); JTextField t1 = new JTextField(); JTextField t2 = new JTextField(); JButton b1 = new JButton ("Find Factorial"); getsize (500, 600); set visible (true); set layout (new Grid Layout (3, 2); bl.add Action listener (new Action listener() { public void action performed (Action Event e) { int num, fact= 1; num Integer.parse Int (t1.getText()); for (i=1;i<=num ; i++) { fact=fact* i; } t2.settext (String.valueof ("fact"); } }); } } |
Qno.4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.ncc.swingdemo.jdbc.basic; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class InsertDemo { public static void main(String[] args) { String sql="INSERT INTO employee_tbl(id,emp_name, emp_salary)VALUES (1,'NCC',20000)"; Connection con = null; Statement st = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/company_db", "root", ""); st = con.createStatement(); st.executeUpdate(sql); System.out.println("Data Inserted"); } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); } } } |
Qno.5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.ncc.ServletDemo.basic; import javax.servlet.*; public class Qno_5 extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String name=req.getParameter("n"); String a=request.getParameter("a"); int age=0; if(a!=null) { age=Integer.parseInt(a); } response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("Name is:"+name); out.println("Age is:"+age); }} |
Group C
Qno.6.
Ans: Delegation model is the modern approach of handling the event that defines standard and consistent mechanism to create the event and control the event.
Source Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
package demo; import java.applet*; import java.awt.*; public class MouseEvents extends Applet implements MouseListener, MouseMotionListener { String msg = ""; // coordinates of mouse int mouseX = 0; int mouseY = 0; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouseDragged(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); msg = "*"; showStatus("Dragging mouse at " + mouseX + "," + mouseY); repaint(); } public void mouseMoved(MouseEvent e) { showStatus("Moving mouse at: " + e.getX() + "," + e.getY()); } public void mouseClicked(MouseEvent e) { mouseX = 0; mouseY = 10; msg = "mouse clicked"; repaint(); } public void mousePressed(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); msg = "Down"; repaint(); } public void mouseReleased(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); msg = "Up"; repaint(); } public void mouseEntered(MouseEvent e) { mouseX = 0; mouseY = 10; msg = "mouse entered"; repaint(); } public void mouseExited(MouseEvent e) { mouseX = 0; mouseY = 10; msg = "mouse exited"; repaint(); } // Display msg in applet window at current X,Y location. public void paint(Graphics g) { g.drawString(msg, mouseX, mouseY); } } |
Qno.7.
Ans: Servlet is the java program that generates dynamic web pages and extends the functionality of server.
The lifecycle methods of servlet are:
- init()
The init() methods run once in a servlet that initialize the servlet object and variables. - service()
The service() methods deals with dynamic request of client and generate the dynamic web pages. - destroy()
The destroy method() is used before deleting the servlet from memory.
Deployment Descriptor
Web container uses XML based file to read the information about servlet and name the file as web.xml which is known as deployment descriptor.
//Structure of Deployment Descriptor
1 2 3 4 5 6 7 8 9 10 |
<web-app> <servlet> <servlet_name>Demo</servlet_name> <servlet_class>com.ServletDemo</servlet_class> </servlet> <servlet_mapping> <servlet_name> Demo</servlet_name> <url_pattern>/demo</url_pattern> </servlet_mapping> </web_app> |
St. Xaviers
Group B
- Create a HTML document that contain the header information of page and include this HTML as a header file in JSP.
// index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<html> <head> <title>Header Information</title> <style> p{ color: red; } </style> </head> <body> <p>This text is red</p> </body> </html> |
//header.jsp
<% @include file=”index.html” %>
- What is key event? How is it handled in java? Explain with suitable java source code.
On entering the character the Key event is generated. There are three types of key events which are represented by the integer constants. These key events are following
- KEY_PRESSED
- KEY_RELASED
- KEY_TYPED
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.awt.*; import java.awt.event.*; public class KeyListenerExample extends Frame implements KeyListener{ Label l; TextArea area; KeyListenerExample(){ l=new Label(); l.setBounds(20,50,100,20); area=new TextArea(); area.setBounds(20,80,300, 300); area.addKeyListener(this); add(l);add(area); setSize(400,400); setLayout(null); setVisible(true); } public void keyPressed(KeyEvent e) { l.setText("Key Pressed"); } public void keyReleased(KeyEvent e) { l.setText("Key Released"); } public void keyTyped(KeyEvent e) { l.setText("Key Typed"); } public static void main(String[] args) { new KeyListenerExample(); } } |
- How can you maintain session in servlet? Explain with example.
In such case, container creates a session id for each user. The container uses this id to identify the particular user. An object of HttpSession can be used to perform two tasks:
-
- bind objects
- view and manipulate information about a session, such as the session identifier, creation time, and last accessed time.
//index.html
1 2 3 4 |
<form action="servlet1"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form> |
//FirstServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); HttpSession session=request.getSession(); session.setAttribute("uname",n); out.print("<a href="servlet2">visit</a>"); out.close(); }catch(Exception e){System.out.println(e);} } } |
//SecondServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session=request.getSession(false); String n=(String)session.getAttribute("uname"); out.print("Hello "+n); out.close(); }catch(Exception e){System.out.println(e);} } } |
- Write a servlet program to find the prime number between 20 and 100.
123456789101112131415161718192021import java.io.*;import javax.servlet.*;import javax.servlet.http.*;class test extends HttpServlet{public void doGet (HttpServletResponse res, HttpServletRequest req) throws IOException{printWriter out = res.getWriter();int i, count, num = 20;while (num<= 100){i=2;count=0;while(i<=num/2){if(num%i ==0){count++;break;}i++;if(count == 0){out.println(num);}num++;}} - Write a swing program to insert data in table using prepared statement. (You can assume your own database, table, and number of field.
123456789101112131415import java.sql.*;class InsertPrepared{public static void main(String args[]){try{Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");stmt.setInt(1,101);//1 specifies the first parameter in the querystmt.setString(2,"Ratan");int i=stmt.executeUpdate();System.out.println(i+" records inserted");con.close();}catch(Exception e){ System.out.println(e);}}}
Group C
- How exception can be handled in JSP and forward to the “error.jsp”? Explain with suitable JSP script.
There are two ways of handling exceptions in JSP. They are:
-
- By errorPage and isErrorPage attributes of page directive.
- By <error-page> element in web.xml file.
//A.jsp
<% @page errorPage = “error.jsp” %>
< %
String num1 = request.getParameter(“first”);
String num2 = request.getParameter(“second”);
// extracting numbers from request
int x = Integer.parseInt(num1);
int y = Integer.parseInt(num2);
int z = x / y; // dividing the numbers
out.print(“division of numbers is: ” + z); // result
% >
//error.jsp
<% @page isErrorPage = “true” %>
<h1> Exception caught</ h1>
The exception is : <%= exception %>
- What are the advantages of JSP over servlet? Explain the use of web.xml with example.
There are many advantages of JSP over servlet. They are as follows:
- Extension to Servlet
JSP technology is the extension to servlet technology. We can use all the features of servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in JSP that makes JSP development easy.
- Easy to maintain
JSP can be easily managed because we can easily separate our business logic with presentation logic. In servlet technology, we mix our business logic with the presentation logic.
- Fast Development: No need to recompile and redeploy
If JSP page is modified, we don’t need to recompile and redeploy the project. The servlet code needs to be updated and recompiled if we have to change the look and feel of the application.
- Less code than Servlet
In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code. Moreover, we can use EL, implicit objects etc.
web.xml defines mappings between URL paths and the servlets that handle requests with those paths. The web server uses this configuration to identify the servlet to handle a given request and call the class method that corresponds to the request method. For example: the doGet() method for HTTP GET requests.
<servlet-mapping>
<servlet-name>redteam</servlet-name>
<url-pattern>/red/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>blueteam</servlet-name>
<url-pattern>/blue/*</url-pattern>
</servlet-mapping>
Morgan
XML Schema overcame all the limitations of DTD and had now become the standard for validating XML documents. The good thing about XML Schema is that it is closely associated with Object Oriented data models.
- What is web server?
Web server is a computer where the web content is stored. Basically web server is used to host the web sites but there exists other web servers also such as gaming, storage, FTP, email etc. Web server respond to the client request in either of the following two ways:
Sending the file to the client associated with the requested URL.
-
- Generating response by invoking a script and communicating with database
Group B
2. Write a swing program to compute sum, difference and product of two numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
import javax.swing.*; import java.awt.event.*; public class SwingDemo extends JFrame implements ActionListener{ JLabel l1,l2,l3; JTextField t1,t2,t3 ; JButton b1,b2,b3; SwingDemo(){ l1=new JLabel(“first number”); l2=new JLabel(“second number”); l3=new JLabel(“Result”); t1= new JTextField(10); t2 = new JTextField(10); t3=new JTextField(10); b1=new JButton(“Sum ”); b2=new JButton(“Difference”); b3=new JButton(“Product”); setLayout(new FlowLayout(FlowLayout.LEFT)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(200,200); setVisible(true); add(l1); add(t1); add(l2); add(t2); add(b1); add(b2); add(b3); b1.add ActionListener(this); b2.add ActionListener(this); b3.add ActionListener(this); } public void actionPerformed(ActionEvent e){ int a=Integer.ParseInt(t1.getText()); int b=Integer.ParseInt(t2.getText()); if(e.getsource()==b1){ int c=a+b; } if(e.getsource()==b2){ int c=a-b; } if(e.getsource()==b3){ int c=a*b; } t3.setText(string.valueof(c)); } public static void main(String[] args) { new SwingDemo(); } |
3.write an applet to check whether given word by user is of length 5 or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.awt.*; import java.applet.*; public class WordLength extends Applet { String word, temp; int n; public void start () { word = getParameter("input"); n = word.length (); if(n==5) temp = "The word is of length 5"; else temp = "The word is not of length 5"; } public void paint (Graphics g){ g.drawString (temp,20, 20); } } |
The HTML file for above applet is:
1 2 3 4 5 6 |
<html> <body> <applet code ="WordLength.class" width = "400" height = "500"> <param name = "input" value =" This is Applet"> </applet> </html> |
4.write a JSP program to compute sum of two numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<html> <head> <title>Form Processing</title> </head> <body> <font size = 3> <br> <center> Processing HTML Form <hr color = red size = 3> <% out.println(“Hello World”); int x = 10; int y = 20; int z = x+y; out.println(“sum = “+z); %> </center> </font> </body> </html> |
5. Write a program to set cookie in servlet.
Cookie.html file
1 2 3 4 5 6 7 |
<html> <body> <form action = Servlet” method = “POST”> Name:<input type=“text” name “uname”/><br> <input type =“submit” value=“go”/></form> </body> </html> |
Cookie.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Import java.io.*; Import javax.servlet.*; Import javax.servlet.http.*; public class SetServlet extends HttpServlet { Public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Response.setContentType(“text/html”); PrintWriter out = response.getWriter(); String n = request.getParameter(“uname”); Out.print(“Welcome”+n); Cookie ck = new Cookie(“name”,n); ck.setMaxAge(60*60*60*24); response.addCookie(ck); out.print(“form action = ‘ReadServlet’ method = “POST”>”); Out.print(“<input type = submit value = ‘go’>”); </form> out.close(); } } |
ReadServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.io.*; import javax.servlet.http.*;. public class ReadServlet extends HttpServlet { public void doPost(HttpServletRequest request , HttpServletResponse response) throws IOException, ServletException { response.setContentType(“text/html”); PrintWriter out = response.getWriter(); Cookie[] ck = request.getCookies(); If(ck!=null) out.print(“Hello”+ck[0].getValue()); out.close(); } } |
6. Write a program to read the employee(eid,name,address,salary) from file and display.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.sql.*; public class ConnectDB { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/Company"; public static void main(String[] args) { Connection conn = null; try{ Class.forName ("com.mysql.jdbc.Driver"); System.out.println ("Connecting to database...."); conn = DriverManager.getConnection(DB_URL,"root","mysql"); System.out.println("Creating statement..."); Statement stmt = conn.createStatement (); String sql = "select * from employee"; ResultSet rs = stmt.executeQuery (sql); while(rs.next()){ int eid = rs.getInt("eid"); float Salary = rs.getfloat("salary"); String name = rs.getString("name"); String address = rs.getString("address"); System.out.println("ID"+id); System.out.println("salary:"+salary); System.out.println("Name:"+name); System.out.println("Address:"+address); rs.close(); stmt.close(); conn.close(); } }catch(Exception e){ System.out.println("Connection failed"+e); } System.out.println("Good bye"); } |
Comprehensive Questions:
- Differentiate between FlowLayout and BorderLayout. Make user form with two textfield and two buttons.
FlowLayout: Flow layout manager is a default layout for applet and panel. A flow layout arranges components in a left to right, much like lines of text in a paragraph. Components are laid out from the upper left corner, left to right and top to down. When no more components fit on a line, the next one appears on next line.
BorderLayout: The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region may contain one component only. It is the default of frame or window. The four sides are referenced to as north, south, east and west. The middle area is called the center. North, south, east and west are narrow fixed width regions whereas center is large region.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import javax.swing.*; import java.awt.*; class SwingDemo { public static void main(String[] args) { JFrame f = new JFrame(); JTextField t1, t2; JLabel l1, l2; JButton b1, b2; l1 = new JLabel("First Name"); l2 = new JLabel("Last Name"); t1 = new JTextField(20); t2 = new JTextField(20); b1 = new JButton("Save"); b2 = new JButton("Close"); f.setLayout(new FlowLayout()); f.add(l1); f.add(t1); f.add(l2); f.add(t2); f.add(b1); f.add(b2); f.setSize(300,400); f.setVisible(true); } } |
- Write a servlet program to compute factorial of a given positive number.
Factorial.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<html> <head> <title> Factorial Example</title> </head> <body> <form method = “get” action = “FactorialServlet”> <table> <tr> <td>Enter value to find its factorial </td> <td><Input type = “text” name =”text1”/> </tr> <tr> <td></td> <td><Input type = “submit” value =”ok”/> </tr> </table> </form> </body> </html> |
FactorialServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.io.*; import java.servlet.*; public class FactorialServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType (“text/html”); PrintWriter out = response.getWriter (); int num = Integer.parseInt(request.getParameter(“text1”)); out.println (this.fact(num)); } long fact(long a) { If(a<=1) retrun 1; else return a*fact(a-1)); } } |
Hetauda
Short Answers
- Write a program which creates a menu (File->open, save, close) in frame.
12345678910111213141516171819202122import java.awt.*;public class MenuDemo extends Frame {MenuBar mnubar=new MenuBar();Menu mnu=new Menu("File");MenuItem mnuopen=new MenuItem("Open");MenuItem mnusave=new MenuItem("Save");MenuItem mnuexit=new MenuItem("Exit");public MenuDemo(){this.setMenuBar(mnubar);mnubar.add(mnu);mnu.add(mnuopen);mnu.add(mnusave);mnu.add(mnuexit);this.setSize(200,200);this.setVisible(true);}public static void main(String argp[]){new MenuDemo();}} - Explain the delegation event model with example.
- Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import java.awt.event.*; import javax.swing.*; public class Demo extends JFrame implements ActionListener{ JButton btnok=new JButton("Ok"); JButton btnclear=new JButton("Clear"); JTextField txt=new JTextField(10); JPanel pnl=new JPanel(); public Qno6() { add(pnl); pnl.add(txt); txt.setEditable(false); pnl.add(btnok); btnok.addActionListener(this); pnl.add(btnclear); btnclear.addActionListener(this); this.setSize(200,200); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("Ok")) { txt.setText("Welcome"); } else txt.setText(null); } public static void main(String arg[]) { new Demo(); } } |
- Create a frame which contains a swing table with some data.
123456789101112131415161718192021222324import java.awt.*;import javax.swing.*;public class SwingTable extends JFrame {Object row[][]= {{"ram",1},{"hari",2},{"shyam",3}};Object col[]= {"Name","roll"};JTable tbl=new JTable(row, col);JPanel pnl=new JPanel();public SwingTable(){add(pnl);pnl.add(tbl);JScrollPane js=new JScrollPane(tbl);this.add(js);this.setSize(200, 200);this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);this.setVisible(true);}public static void main(String arh[]){new SwingTable();}} - What do you understand by Request Dispatching? Explain with example.
- Request Dispatcheris an interface whose implementation defines an object which can dispatch the requestto any resources on the server. javax.servlet.RequestDispatcher interface is used to forward or include the response of a resource in a Servlet.
Example.
Index.html
1 2 3 4 5 |
<form action="servlet1" method="post"> Name:<input type="text" name="userName"/><br/> Password:<input type="password" name="userPass"/><br/> <input type="submit" value="login"/> </form> |
Login.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Login extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); String p=request.getParameter("userPass"); if(p.equals("servlet"){ RequestDispatcher rd=request.getRequestDispatcher("servlet2"); rd.forward(request, response); } else{ out.print("Sorry UserName or Password Error!"); RequestDispatcher rd=request.getRequestDispatcher("/index.html"); rd.include(request, response); } } } |
- Explain component and Container with example program.
- A componentis an object having a graphical representation that can be displayed on the screen and that can interact with the user. Examplesof components are the buttons, checkboxes, and scrollbars of a typical graphical user interface.
Example:
1 2 3 4 5 6 7 8 9 10 11 |
import java.applet.*; import java.awt.*; public class MyApplet extends Applet { Button btn; Label lbl; public void init() { add(lbl); add(btn); } } |
- A containeris a component which can contain other components inside itself
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.awt.*; public class Calculator extends Frame { private Label lblN1=new Label("N1:"); private TextField txt3=new TextField(5); private Panel pnl=new Panel(); private Button btn=new Button("Add"); public Calculator() { this.setTitle("Calculator"); this.add(pnl); pnl.add(lblN1); pnl.add(txt3); pnl.add(btn); this.setSize(200,200); this.setVisible(true); } public static void main(String arg[]) { Calculator cal=new Calculator(); } } |
- Create an Application using swing package which will search the student in the database and display the record in the respective fields. [Database schema is as- Student (Sid, sname, address)].
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475import java.awt.event.*;import java.sql.*;import javax.swing.*;public class StudentDemo extends JFrame implements ActionListener {JLabel lbl=new JLabel("SID");JLabel lblname=new JLabel("Name");JLabel lbladd=new JLabel("Address");JTextField txt=new JTextField(10);JTextField txtname=new JTextField(10);JTextField txtadd=new JTextField(10);JButton btn=new JButton("Search");JPanel pnl=new JPanel();public StudentDemo(){add(pnl);pnl.add(lbl);pnl.add(txt);pnl.add(lblname);pnl.add(txtname);pnl.add(lbladd);pnl.add(txtadd);pnl.add(btn);btn.addActionListener(this);this.setSize(200, 200);this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);this.setVisible(true);}public void actionPerformed(ActionEvent e) {Integer sid=null;try{sid=Integer.parseInt(txt.getText());}catch(NumberFormatException ex){System.out.println(ex.getMessage());}if(txt.getText()!=null){try{Class.forName("com.mysql.jdbc.Driver");Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost/student","root","");Statement stm=con.createStatement();String query="select * from student where sid='"+sid+"'";ResultSet result=stm.executeQuery(query);if(result.next()){txt.setText(result.getString(1));txtname.setText(result.getString(2));txtadd.setText(result.getString(3));}else{JOptionPane.showMessageDialog(this, "No data found");txt.setText(null);txtname.setText(null);txtadd.setText(null);}}catch(ClassNotFoundException ex){System.out,.println(ex.getMessage());}catch(SQLException ex){System.out,.println(ex.getMessage());}}}public static void main(String arg[]){new StudentDemo();}}
- Create a login form (web) and validate the user from database. Assume your own database parameters.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647<%@page import="java.sql.*"%><%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><body><form action="#" method="post">Username:<input type="text" name="user"><input type="submit" value="submit" name="submit"></form><%if(request.getMethod().equals("POST")){if(request.getParameter("user")!=null){String s=request.getParameter("user");try{Class.forName("com.mysql.jdbc.Driver");Connection con=DriverManager.getConnection("jdbc:mysql://localhost/tests", "root", "");Statement stm=con.createStatement();String query="Select username from user where username='"+s+"'";ResultSet result=stm.executeQuery(query);if(result.next()){out.println("Welcome "+s);}else{out.println("Sorry no username found for "+s);}}catch(ClassNotFoundException e){out.println("Class not found:-"+e.getMessage());}catch(SQLException e){out.println("SQL Exception:-"+e.getMessage());}}}%></body></html>
- Create a Jsp simple calculator. The result should be processed by a servlet.
Calculator.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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=ISO-8859-1"> <title>Insert title here</title> </head> <body> <form action="CalculatorDemo" method="post"> Number 1:<input type=text name="one"><br> Number 2:<input type=text name="two"><br> <input type="submit" value="Add" name="submit"> <input type="submit" value="Sub" name="submit"> <input type="submit" value="Mul" name="submit"> <input type="submit" value="Div" name="submit"> </form> </body> </html> |
CalculatorDemo.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.io.*; import javax.servlet.*; import javax.servlet.annotation.*; import javax.servlet.http.*; @WebServlet("/CalculatorDemo") public class CalculatorDemo extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) { } public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException { RequestDispatcher rd=request.getRequestDispatcher("Calculator.jsp"); rd.include(request, response); if(request.getParameter("submit")!=null) { Integer a=Integer.parseInt(request.getParameter("one")); Integer b=Integer.parseInt(request.getParameter("two")); if(request.getParameter("submit").equals("Add")) { response.getWriter().println(a+b); } else if(request.getParameter("submit").equals("Add")) { response.getWriter().println(a-b); } else if(request.getParameter("submit").equals("Add")) { response.getWriter().println(a*b); } else { response.getWriter().println((float)a/b); } } } } |
Orchid
Short Answer Questions:
2.Write a program to insert 3 records into a table “book” having columns(id,name,author,publishor and price).Assume database name yourself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.sql.*; public class InsertData{ public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/library"; String uname = "root"; String pwd = ""; try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, uname, pwd); String sql = "insert into book (id, name, author, publisher, price) values " + "(1, 'abc', 'bcd', 'efg', 200)," + "(2, 'abc', 'bcd', 'efg', 200)," + "(3, 'abc', 'bcd', 'efg', 200)"; Statement st = con.createStatement(); int rst = st.executeUpdate(sql); if(rst > 0) { System.out.println("Records inserted"); } con.close(); }catch(Exception ex) { System.out.println(ex); } } } |
3.Create a jsp that takes an integer from HTML and display its reverse.
reverse.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<html> <body> <% int num = Integer.parseInt(request.getParameter("number")); int rev = 0, rem; while(num > 0){ rem = num % 10; rev = rem + rev * 10; num = num / 10; } out.println("Reverse is: "+rev); %> </body> </html> |
—————————-
reverse.html
1 2 3 4 5 6 7 8 |
<html> <body> <form action = "reverse.jsp" method = "get"> Enter a number: <input type = "text" name = "number" /> <input type = "submit" /> </form> </body> </html> |
4.Create an applet to draw a circle and a rectangle filled with different colors.
1 2 3 4 5 6 7 8 9 10 |
import java.applet.*; import java.awt.*; public class DrawShape extends Applet { public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(10, 10, 200, 100); g.setColor(Color.blue); g.fillOval(50, 50, 100, 100); } } |
5.Create a swing program with menu bar,menu and a menu item.When menu item is clicked,display “hello” in a message dialog.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MenuBarDemo implements ActionListener { JFrame f1; JMenuBar bar; JMenu m1; JMenuItem mi1; MenuBarDemo(){ f1 = new JFrame(); f1.setSize(300, 300); f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); bar = new JMenuBar(); m1 = new JMenu("File"); bar.add(m1); mi1 = new JMenuItem("OK"); m1.add(mi1); mi1.addActionListener(this); f1.setJMenuBar(bar); f1.setVisible(true); } public static void main(String[] args) { new MenuBarDemo(); } public void actionPerformed(ActionEvent e) { if(e.getSource() == mi1) { JOptionPane.showMessageDialog(null, "Hello"); } } } |
6.Create a servlet to read cookie from client and display the name and value associated with the cookie.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import javax.servlet.http.*; import java.io.*; public class ReadCookie extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html"); Cookie[]cookie = request.getCookies(); try { PrintWriter pw = response.getWriter(); pw.println("<html><body>"); pw.println("<h1>Cookie Info</h1>"); if(cookie != null) { for(int i = 0; i < cookie.length; i++) { pw.println("Cookie name: "+cookie[i].getName()); pw.println("Cookie value: "+cookie[i].getValue()); } } pw.println("</html></body>"); }catch(Exception ex) { System.out.println(ex); } } } |
Long Answer Questions:
8.What is a java bean?Explain.Write a program to use java bean in jsp.
A Java Bean is a java class that should follow following conventions:
-It should have a no-argument constructor.
-It should be Serializable.
-It should provide methods to set and get the values of the properties, known as getter and setter methods.
java_bean.jsp
1 2 3 4 5 6 7 8 9 10 11 |
<html> <body> <% <jsp:useBean id = "abc" class = "web.Person" /> <jsp:setProperty name = "abc" property = "name" value = "Ram" /> <jsp:setProperty name = "abc" property = "salary" value = "20000" /> <p>Name: <jsp:getProperty name = "abc" property = "name" /> </p> <p>Salary: <jsp:getProperty name = "abc" property = "salary" /> </p> %> </body> </html> |
————————————
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package web; import java.io.*; public class Person implements Serializable { private String name; private double salary; public Person() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } } |
SET A
Short Answer Questions
2.Create a swing program to add two numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class CalculatorDemo implements ActionListener{ JFrame f1; JLabel l1, l2, l3; JTextField t1, t2, t3; JButton b1; CalculatorDemo(){ f1 = new JFrame(); f1.setSize(300,300); f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f1.setLayout(new GridLayout(4, 2)); l1 = new JLabel("Num1"); l2 = new JLabel("Num2"); l3 = new JLabel("Result"); t1 = new JTextField(); t2 = new JTextField(); t3 = new JTextField(); b1 = new JButton("Add"); f1.add(l1); f1.add(t1); f1.add(l2); f1.add(t2); f1.add(l3); f1.add(t3); f1.add(b1); b1.addActionListener(this); f1.setVisible(true); } public static void main(String[] args) { new CalculatorDemo(); } public void actionPerformed(ActionEvent e) { int a = Integer.parseInt(t1.getText()); int b= Integer.parseInt(t2.getText()); int c = 0; if(e.getSource() == b1) { c = a + b; } t3.setText(c+""); } } |
3.Write a program to update price of book to 1200 whose name is “Head First Java” into a table “book”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.sql.*; public class UpdateData { public static void main(String [] args) { String url = "jdbc:mysql://localhost:3306/library"; String uname = "root"; String pwd = ""; try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, uname, pwd); String sql = "UPDATE book SET price = 1200 WHERE name = 'Head First Java'"; Statement st = con.createStatement(); int rst = st.executeUpdate(sql); if(rst > 0){ System.out.println("Record Updated"); } con.close(); } catch(Exception ex) { System.out.println(ex); } } } |
4.Create an applet to draw a circle and a rectangle filled with different colors.
1 2 3 4 5 6 7 8 9 10 |
import java.applet.*; import java.awt.*; public class DrawShape extends Applet { public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(10, 10, 200, 100); g.setColor(Color.blue); g.fillOval(50, 50, 100, 100); } } |
5.Create a jsp to find the length of given string provided from HTML.
length.jsp
1 2 3 4 5 6 7 8 9 |
<html> <body> <% String str = request.getParameter("str"); int len = str.length(); out.println("Length is: "+len); %> </body> </html> |
—————————-
length.html
1 2 3 4 5 6 7 8 |
<html> <body> <form action = "length.jsp" method = "get"> Enter a Text: <input type = "text" name = "str" /> <input type = "submit" /> </form> </body> </html> |
6.Create a servlet to write cookie to user computer and store it for 24 hours.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import javax.servlet.http.*; import java.io.*; public class CookieDemo extends HttpServlet{ public void doGet(HttpServletRequest request,HttpServletResponse response){ response.setContentType("text/html"); try{ PrintWriter pw = response.getWriter(); Cookie cookie1 = new Cookie("FirstName", "abc"); cookie1.setMaxAge(24*60*60); response.addCookie(cookie1); pw.println("Hello user, cookie has been set to your computer"); pw.close(); }catch(Exception ex){ System.out.println(ex); } } } |
Long Answer Questions:
- What is a java bean?Explain.Write a program to use java bean in jsp.
A Java Bean is a java class that should follow following conventions:
-It should have a no-argument constructor.
-It should be Serializable.
-It should provide methods to set and get the values of the properties, known as getter and setter methods.
java_bean.jsp
1 2 3 4 5 6 7 8 9 10 11 |
<html> <body> <% <jsp:useBean id = "abc" class = "web.Person" /> <jsp:setProperty name = "abc" property = "name" value = "Ram" /> <jsp:setProperty name = "abc" property = "salary" value = "20000" /> <p>Name: <jsp:getProperty name = "abc" property = "name" /> </p> <p>Salary: <jsp:getProperty name = "abc" property = "salary" /> </p> %> </body> </html> |
————————————
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package web; import java.io.*; public class Person implements Serializable { private String name; private double salary; public Person() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } } |
IMS
Group B
- Make an user interface to take name and address of user?
1234567891011121314151617181920212223242526272829import java.awt.*;import java.awt.event.*;import javax.swing.*;class First extends JFrame implements ActionListener{JLabel name; JTextField jtf;JLable address; JTextField jtf2JButton btn;public First(){name = new JLable("Enter Name");jtf = new JTextField(10);address = new JLable("Enter Addres");jtf2 = new JTextField(10);btn = new JButton("Submit");add(name);add(jtf);add(address);add(jtf2);add(btn);setsize(400,400);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLayout(new FlowLayout());setVisible(true);jb.setActionListener(this);}public void actionPerformed(ActionEvent ae){First f = new First() ;}} - Make a user interface to take name and address of user?
123456789101112131415161718192021222324252627282930313233import java.awt.*;import java.awt.event.*;import javax.swing.*;class Prime extends JFrame implements ActionListener{JLabel jLb1;JTextField jtf;JButton jbt;public Prime(){jLb1 = new JLabel("Enter Numner");jtf = new JTextField(10);jbtn = new JButton("Check");add(jLb1);add(jtf);add(jbtn);setsize(200,200);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLayout(new FlowLayout());setVisible(true);jbtn.setActionListener(this);}public void actionPerformed(ActionEvent ae){int a = Integer.parseInt(jtf.getText());int m = 0;flag = 0;for (int i=1; i<=a; i++) {if (a%i==0) {System.out.println("Prime");}else{System.out.println("Not Prime");}}}} - Make an applet to display name of your college?
12345678import java.applet.Applet;import java.awt.Graphics;public class College extends Applet{public void paint (Graphics g){g.drawString ("IMS College",20,150);}}/*<applet code = "College.class" width="200" height="200"></applet>*/ - Write a jsp program to display multiplication table to 2 (from 1 To 10).
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586<html><head><title>JSP Program</title></head><body><form action="tb_disp.jsp" method="post"><table align="center"><tr><th>Multiplication Table</th></tr><tr><td>Enter no. of rows</td><td><input type="number" name="rows"></td></tr><tr><td>Enter no. of colums </td><td><input type="number" name="cols"></td></tr><tr><td><input type="submit"></td></tr></table></form></body></html><% page import = "java.util.Random"%><%page content Type = "text/html"%><html><head><title>Multiplication Table</title></head><body><%Random r = new Random();int n.row=0, cols=0, inc2;row= Integer.parse.Int(request.getParameter("row"));col= Integer.parse.Int(request.getParameter("cols"));%><table border="2" cellpadding="7" align="center"><thead><center>Multiplication Table</center></thead><tr><%String str;for(inc1=1; inc1<=row; inc1++){n=r.nextInt(0.Xfffff);str=Integer.toHexString(n);%><td align="center"><font size="5"><%Out.print(inc1);%></font></td><%}%></tr><%for(inc1=1; inc1<=col; inc1++)%><tr><%String str;for(inc2=1; inc2<=row; inc2++){n=r.nextInt(0.Xfffff);str=Integer.toHexString(n);%><td><font size="5"><%Out.print(inc1+"*"+inc2+"="+(inc1*inc2));%></font></td><%}%></tr><%}%><tr> </tr></table></body></html>
Group C
- Differentiate between JSP and Servlet?
Servlet |
JSP |
A servlet is a server-side program and written purely on Java. | JSP is an interface on top of Servlets. In another way, we can say that JSPs are extension of servlets to minimize the effort of developers to write User Interfaces using Java programming. |
Servlets run faster than JSP | JSP runs slower because it has the transition phase for converting from JSP page to a Servlet file. Once it is converted to a Servlet then it will start the compilation |
Executes inside a Web server, such as Tomcat | A JSP program is compiled into a Java servlet before execution. Once it is compiled into a servlet, it’s life cycle will be same as of servlet. But, JSP has it’s own API for the lifecycle. |
Receives HTTP requests from users and provides HTTP responses | Easier to write than servlets as it is similar to HTML. |
We can not build any custom tags | One of the key advantage is we can build custom tags using JSP API (there is a separate package available for writing the custom tags) which can be available as the re-usable components with lot of flexibility |
Servlet has the life cycle methods init(), service() and destroy() | JSP has the life cycle methods of jspInit(), _jspService() and jspDestroy() |
Written in Java, with a few additional APIs specific to this kind of processing. Since it is written in Java, it follows all the Object Oriented programming techniques. | JSPs can make use of the Javabeans inside the web pages |
- Explain layout manager?
-
- The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented by all the classes of layout managers. There are following classes that represents the layout managers:
- java.awt.BorderLayout
- java.awt.FlowLayout
- java.awt.GridLayout
- java.awt.CardLayout
- java.awt.GridBagLayout
- javax.swing.BoxLayout
- javax.swing.GroupLayout
- javax.swing.ScrollPaneLayout
- javax.swing.SpringLayout, etc.
BorderLayout
Every content pane is initialized to use a BorderLayout. (As Using Top-Level Containers explains, the content pane is the main container in all frames, applets, and dialogs.) A BorderLayoutplaces components in up to five areas: top, bottom, left, right, and center. All extra space is placed in the center area. Tool bars that are created using JToolBar must be created within a BorderLayout container, if you want to be able to drag and drop the bars away from their starting positions
CardLayout
The CardLayout class lets you implement an area that contains different components at different times. A CardLayout is often controlled by a combo box, with the state of the combo box determining which panel (group of components) the CardLayout displays. An alternative to using CardLayout is using a tabbed pane, which provides similar functionality but with a pre-defined GUI.
FlowLayout
FlowLayout is the default layout manager for every JPanel. It simply lays out components in a single row, starting a new row if its container is not sufficiently wide. Both panels in CardLayoutDemo, shown previously, use FlowLayout.
NCCS
Set B
Q.N. 2
Fact.html
1 2 3 4 5 6 7 8 9 10 11 |
<html> <head> <title>Factorial number</title> </head> <body> <form method="post" action="Fact"> Enter a number:<input type="number" name="num1"><br/> <input type="submit" value="Calculate"> </form> </body> </html> |
Fact.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package ServletLab; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Fact extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); int n1=Integer.parseInt(req.getParameter("num1")); out.println("<html>"); out.println("<head>"); out.println("</head>"); out.println("<body>"); int f=1; for(int i=1;i<=n1;i++){ f*=i; } out.println("Factorial is "+f); out.println("</body>"); out.println("</html>"); } } |
Q.N. 3
Q3.html
1 2 3 4 5 6 7 8 9 10 11 12 |
<html> <head> <title>Q3</title> </head> <body> <form method="post" action="Q3"> Name:: <input type="number" name="name"><br/> Age:: <input type="number" name="age"><br/> <input type="submit" value="submit"> </form> </body> </html> |
Q3.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package ServletLab; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Q5 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); response.setContentType("text/html"); String name = request.getParameter("name"); String age = request.getParameter("age"); session.setAttribute("name", name); session.setAttribute("age", age); PrintWriter out = response.getWriter(); out.println(“Name:: “ + session.getAttribute(name)); out.println(“Age:: “ + session.getAttribute(age)); } } |
Web.xml
1 2 3 4 5 6 7 8 |
<servlet> <servlet-name>Q3</servlet-name> <servlet-class>Servlet25.Q3</servlet-class> </servlet> <servlet-mapping> <servlet-name>Q3</servlet-name> <url-pattern>/Q3</url-pattern> </servlet-mapping> |
Q.N. 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package NCCS_pre; import java.applet.Applet; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; /* <applet code="Q4" width=300 height=300> </applet> */ public class Q4 extends Applet{ TextField t1,t2; Button add,div; Label l1,l2; public void init(){ l1=new Label("Num1"); l2=new Label("Num2"); t1=new TextField(10); t2=new TextField(10); add=new Button("Add"); div=new Button("Divide"); setLayout(new GridLayout(4,2)); add(l1); add(t1); add(l2); add(t2); add(add); add(div); setSize(120,80); setVisible(true); add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int num1=Integer.parseInt(t1.getText()); int num2=Integer.parseInt(t2.getText()); int sum=num1+num2; showStatus(""+sum); } }); div.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { double num1=Double.parseDouble(t1.getText()); double num2=Double.parseDouble(t2.getText()); double d=num1/num2; showStatus(""+d); } }); } } |
Q.N. 6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |