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 28 29 |
package NCCS_pre; import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class KeyEventDemo extends JFrame implements KeyListener{ JTextField t,t2; JPanel p,p1; KeyEventDemo(){ t2=new JTextField(10); t=new JTextField(10); p=new JPanel(); p1=new JPanel(); p.add(t2); p1.add(t); add(p,BorderLayout.SOUTH); add(p1,BorderLayout.NORTH); t.addKeyListener(this); setSize(400,300); setVisible(true); } public void keyPressed(KeyEvent e){ t2.setText(t.getText()); } public void keyTyped(KeyEvent e){ } public void keyReleased(KeyEvent e){ } public static void main(String[] args) { new KeyEventDemo(); } } |
Q.N. 7
Q7.jsp
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 |
<!DOCTYPE html> <html> <head> <title>Q7</title></head> <body> <form method="post" action="Q7.jsp"> FirstName : <input type="text" name="fname"/><br/> LastName: <input type="text" name="lname"/><br/> Age : <input type="text" name="age"/><br/> Address : <input type="text" name="add"/><br/> <input type="submit" value="Submit" name="submit"/> </form> </body> </html> <%@page session="true" %> <% if (request.getParameter("submit") != null) { String firstName = request.getParameter("fname"); String lastName = request.getParameter("lname"); String age = request.getParameter("age"); String add = request.getParameter("add"); %> <jsp:useBean id="bean" class="bean.Customer" scope="session"/> <jsp:setProperty name="bean" property="firstname" value="<%= firstName %>"/> <jsp:setProperty name="bean" property="lastname" value="<%= lastName %>"/> <jsp:setProperty name="bean" property="age" value="<%=age%>"/> <jsp:setProperty name="bean" property="address" value="<%=add%>"/> <% response.sendRedirect("Q7disp.jsp"); } %> |
Q7disp.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<%@page session="true" %> <jsp:useBean id="bean" class="bean.Customer" scope="session"/> <!DOCTYPE html> <html> <head> <title>JSP Page</title> </head> <body> FirstName : <jsp:getProperty name="bean" property="fname"/><br/> LastName : <jsp:getProperty name="bean" property="lname"/><br/> Age : <jsp:getProperty name="bean" property="age"/><br/> Address : <jsp:getProperty name="bean" property="add"/><br/> </body> </html> |
Q7.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 |
package bean; public class Q7 { String firstname,lastname,address,age; public String getfirstname(){ return firstname; } public String getlastname(){ return lastname; } public String getage(){ return age; } public String getAddress(){ return address; } public void setfirstname (String firstname){ this.firstname = firstname; } public void setlastname (String lastname){ this.lastname = lastname; } public void setaget(String age){ this.age = age; } public void setAddress(String address){ this.address = address; } } |
Q.N. 8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package LabSheet; import java.sql.*; public class Q8 { public static void main(String [] args) throws Exception{ Connect(); } public static Connect() throws Exception{ Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/college "; Connection con=DriverManager.getConnection(url,"root",""); Statement stmt=con.createStatement(); int res=stmt.executeUpdate(sql); if(res!=-1){ String sql=”UPDATE Teacher SET address=’Dharan’ WHERE t_id=5”; int res=stmt.executeUpdate(sql); System.out.println("Update succesfully"); }else{ System.out.println("couldn't inserted. Please check ur SQL Syntax"); } } } } |
Set A
Q.N. 2
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 |
package NCCS_pre; import java.awt.*; import java.awt.event.*; public class MouseEventDemo extends Frame implements MouseListener { int x = 0, y = 0; String strEvent = ""; MouseEventDemo(String title) { super(title); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); addMouseListener(this); setSize(300, 300); setVisible(true); } public void mouseClicked(MouseEvent e) { strEvent = "MouseClicked"; x = e.getX(); y = e.getY(); repaint(); } public void mousePressed(MouseEvent e) { strEvent = "MousePressed"; x = e.getX(); y = e.getY(); repaint(); } public void mouseReleased(MouseEvent e) { strEvent = "MouseReleased"; x = e.getX(); y = e.getY(); repaint(); } public void mouseEntered(MouseEvent e) { strEvent = "MouseEntered"; x = e.getX(); y = e.getY(); repaint(); } public void mouseExited(MouseEvent e) { strEvent = "MouseExited"; x = e.getX(); y = e.getY(); repaint(); } public void paint(Graphics g) { g.drawString(strEvent + " at " + x + "," + y, 50, 50); } public static void main(String[] args) { new MouseEventDemo("Window With Mouse Events Example"); } } |
Q.N. 3
1 2 3 4 5 6 7 8 9 10 11 |
<html> <head> <title>Prime number</title> </head> <body> <form method="post" action="Prime"> Enter a number:<input type="number" name="num1"><br/> <input type="submit" value="check"> </form> </body> </html> |
Prime.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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")); int f=1; for(int i=2;i<n1/2;i++){ if(n1%==0){ f=0; break; } } if(f==1) out.println(n1+” is prime”); else out.println(n1+” is not prime”); } } |
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 |
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 check; Label l1,l2; public void init(){ l1=new Label("Num1"); l2=new Label("Num2"); t1=new TextField(10); t2=new TextField(10); check=new Button("Check"); setLayout(new GridLayout(3,2)); add(l1); add(t1); add(l2); add(t2); add(check); setSize(120,80); setVisible(true); check.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int small; int num1=Integer.parseInt(t1.getText()); int num2=Integer.parseInt(t2.getText()); if(num1<num2) small=num1; else small=num2; showStatus(""+small); } }); } } |
Q.N. 6
Q6.html
1 2 3 4 5 6 7 8 9 10 11 12 |
<html> <head> <title>Q6</title> </head> <body> <form method="post" action="Q6"> Num1:: <input type="number" name="n1"><br/> Num2:: <input type="number" name="n2"><br/> <input type="submit" value="submit"> </form> </body> </html> |
Q6.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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 { response.setContentType("text/html"); PrintWriter out = response.getWriter(); int num1,num2,add,sub,mul; num1=Integer.parseInt(req.getParameter(“n1”)); num2=Integer.parseInt(req.getParameter(“n2”)); add=num1+num2; sub=num1-num2; mul=num1*num2; out.println(“Sum is “+add); out.println(“Sum is “+sub); out.println(“Sum is “+mul); } } |
Web.xml
1 2 3 4 5 6 7 8 |
<servlet> <servlet-name>Q6</servlet-name> <servlet-class>Servlet25.Q6</servlet-class> </servlet> <servlet-mapping> <servlet-name>Q6</servlet-name> <url-pattern>/Q6</url-pattern> </servlet-mapping> |
Q.N. 7
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 |
<!DOCTYPE html> <html> <head> <title>Q7</title> </head> <body> <form method="post" action="Q7.jsp"> Name : <input type="text" name="name"/><br/> Address : <input type="text" name="add"/><br/> Age : <input type="text" name="age"/><br/> Program : <input type="text" name="pro"/><br/> <input type="submit" value="Submit" name="submit"/> </form> </body> </html> <%@page session="true" %> <% if (request.getParameter("submit") != null) { String name = request.getParameter("name"); String add = request.getParameter("add"); String age = request.getParameter("age"); String program = request.getParameter("pro"); %> <jsp:useBean id="bean" class="bean.Customer" scope="session"/> <jsp:setProperty name="bean" property="name" value="<%= name %>"/> <jsp:setProperty name="bean" property="address" value="<%=add%>"/> <jsp:setProperty name="bean" property="age" value="<%=age%>"/> <jsp:setProperty name="bean" property="program" value="<%= pro %>"/> <% response.sendRedirect("Q7disp.jsp"); } %> |
Q7disp.jsp
1 2 3 4 5 6 7 8 9 10 11 12 |
<%@page session="true" %> <jsp:useBean id="bean" class="bean.Customer" scope="session"/> <!DOCTYPE html> <html> <head> <title>JSP Page</title> </head> <body> Name : <jsp:getProperty name="bean" property="name"/><br/> Address : <jsp:getProperty name="bean" property="add"/><br/> Age : <jsp:getProperty name="bean" property="age"/><br/> Program : <jsp:getProperty name="bean" property="program"/><br/> </body> </html> |
Q7.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 |
package bean; public class Q7 { String name,address,age,program; public String getname(){ return name; } public String getAddress(){ return address; } public String getage(){ return age; } public String getprogram(){ return program; } public void setname (String name){ this.name = name; } public void setAddress(String address){ this.address = address; } public void setaget(String age){ this.age = age; } public void setprogram (String program){ this.program= program; } } |
Q.N. 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 |
package LabSheet; import java.sql.*; public class Q8 { public static void main(String [] args) throws Exception{ Connect(); } public static Connect() throws Exception{ Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/hospital "; Connection con=DriverManager.getConnection(url,"root",""); String sql="INSERT INTO patient VALUES(1,’Ram’,’kathmandu’,’Male’); if(con!=null){ Statement stmt=con.createStatement(); int res=stmt.executeUpdate(sql); String sql=”UPDATE patitent SET address=’Pokhara’ WHERE id=1”; int res=stmt.executeUpdate(sql); System.out.println("Update succesfully"); Stmt.close(); }else{ System.out.println("couldn't inserted. Please check ur SQL Syntax"); } } } } |
KIST
Group B
2) Write a swing program to add two numbers given by user as input.
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 javax.swing.*; import javax.swing.event.*; import java.awt.event.*; public class T2016_2 extends JFrame implements ActionListener{ JTextField t1,t2; JLabel sum; JButton b; public T2016_2(){ t1=new JTextField(); t2=new JTextField(); sum=new JLabel(""); b=new JButton("Add"); setLayout(new GridLayout(4,1)); add(t1); add(t2); add(b); add(sum); setSize(200,400); setVisible(true); b.addActionListener (this); } public void actionPerformed(ActionEvent e){ int n1=Integer.parseInt(t1.getText()); int n2=Integer.parseInt(t2.getText()); int s=n1+n2; sum.setText("Sum is: "+s); } public static void main(String[] args) { new T2016_2(); } } |
3) Write a program to display record from user_table that contains (id, username, password and role) inside a database kist_db.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.sql.*; public class Db{ public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/ kist_db "; String uname = "root"; String pwd = ""; try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, uname, pwd); String sql = "select * from employee"; Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql); while(rs.next()) { System.out.println(rs.getString("id")); System.out.println(rs.getString("username")); System.out.println(rs.getString("password")); System.out.println(rs.getString("role")); } }catch(Exception ex) { System.out.println(ex); } } } |
4) Write a jsp to display “Hello from jsp” 10 times.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<html> <head> <title> </title> </head> <body> <% String i=" Hello from jsp"; For( i=1; i<=10; i++){ %> <%i = %> <% } %> </body> </html> |
5) Write a servlet to find the factorial of a positive values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import javax.servlet.http.*; import java.io.*; public class Ques3_2018 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html"); int num = Integer.parseInt(request.getParameter("number")); int fact = 1; while(num > 0) { for(int i = 1; i <= num; i++) { fact = fact * i; } } try { PrintWriter pw = response.getWriter(); pw.println("<html><body>"); pw.println("<h1>Factorial of "+num+ " is "+fact+"</h1>"); pw.println("</html></body>"); }catch(Exception ex) { System.out.println(ex); } } } |
6) Create an applet that contain three text field and two buttons (add and subtract). Perform add and subtract.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class Ap extends Applet{ int a, b; public void start () { string b= getparameter("b"); string a= getparameter("a"); try{ if(a!= null && b!=null){ a= Integer.parseInt("a"); b= Integer.parseInt("b"); int sub=a-b; int sum=a+b; }catch(Exception e){ System.out.println(e); System.out.println("sum" +sum); System.out.println("sub" +sub); } } <applet code="add.Applet"> <para name="a" value="50"> <para name="b" value="60"> </applet> |
Group ‘c’
7)What layout manager? Explain border layout and grid bag layout.
- The Layout Managers are used to arrange components in a particular manner. Layout Manager is an interface that is implemented by all the classes of layout managers.
- Grid bag layout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle.
Example:
- Grid bag layout
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 java.awt.*; import javax.swing.*;z public class MyGridLayout{ Jframe f; MyGridLayout(){ 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)); f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new MyGridLayout(); } } |
- Border layout
The Border Layout is used to arrange the components in five regions: north, south, east, west and center. Each region (area) may contain one component only.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.awt.*; import javax.swing.*; public class Border { JFrame f; Border(){ f=new JFrame(); JButton b1=new JButton("NORTH");; JButton b2=new JButton("SOUTH");; JButton b3=new JButton("EAST");; JButton b4=new JButton("WEST");; JButton b5=new JButton("CENTER"); f.add(b1,BorderLayout.NORTH); f.add(b2,BorderLayout.SOUTH); f.add(b3,BorderLayout.EAST); f.add(b4,BorderLayout.WEST); f.add(b5,BorderLayout.CENTER); f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new Border(); } } |
8) What do you understand by event delegation model? How swing support look and feel ?
- 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.
The Delegation Event Model has the following key participants namely:
- Source– The source is an object on which event occurs. Source is responsible for providing information of the occurred event to it’s handler. Java provide as with classes for source object.
- Listener– It is also known as event handler. Listener is responsible for generating response to an event. From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received, the listener process the event an then returns.
“Look” refers to the appearance of GUI widgets and “feel” refers to the way the widgets behave.
Sun’s JRE provides the following L&Fs:
- CrossPlatformLookAndFeel:this is the “Java L&F” also known as “Metal” that looks the same on all platforms. It is part of the Java API (javax.swing.plaf.metal) and is the default.
- SystemLookAndFeel:here, the application uses the L&F that is default to the system it is running on. The System L&F is determined at runtime, where the application asks the system to return the name of the appropriate L&F.
For Linux and Solaris, the System L&Fs are “GTK+” if GTK+ 2.2 or later is installed, “Motif” otherwise. For Windows, the System L&F is “Windows”. - Synth:the basis for creating your own look and feel with an XML file.
- Multiplexing:a way to have the UI methods delegate to a number of different look and feel implementations at the same time.
For example:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.UIManager;import javax.swing.JFrame;class Awt implements ActionListener {JFrame f;JButton addbut, subbut, mulbut, divbut, b5;JTextField t1, t2, t3;JLabel l, l1;Awt(){f = new JFrame("Cross Platform Look and Feel");t1 = new JTextField(" ");t2 = new JTextField(" ");t3 = new JTextField(" ");addbut = new JButton("Add");subbut = new JButton("Sub");mulbut = new JButton("Mul");divbut = new JButton("Div");l = new JLabel();l1 = new JLabel();}public void awt1(){f.setLayout(new GridLayout(3, 2));f.setVisible(true);f.add(t1);f.add(t2);f.add(t3);f.add(addbut);f.add(subbut);f.add(mulbut);f.add(divbut);f.add(l);f.add(l1);addbut.addActionListener(this);subbut.addActionListener(this);mulbut.addActionListener(this);divbut.addActionListener(this);f.pack();}public void actionPerformed(ActionEvent e){String s = new String(e.getActionCommand());l.setText(s);if ((s).equals("Add")) {int a = Integer.parseInt(t1.getText());int b = Integer.parseInt(t2.getText());Integer c = a + b;t3.setText(c.toString());}else if ((s).equals("Sub")) {int a = Integer.parseInt(t1.getText());int b = Integer.parseInt(t2.getText());Integer c = a - b;t3.setText(c.toString());}else if ((s).equals("Mul")) {int a = Integer.parseInt(t1.getText());int b = Integer.parseInt(t2.getText());Integer c = a * b;t3.setText(c.toString());}}public static void main(String args[]){try {UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());}catch (Exception e) {System.out.println("Look and Feel not set");}Awt a = new Awt();a.awt1();}}
SET-A
Group B
- Write a swing program in which user can select one of the option and display that selected option.
12345678910111213141516171819202122232425262728import java.awt.*;import java.awt.event.*;import javax.swing.*;/*<applet code="JAppletDemo.class" width=200 height=200></applet>*/public class JAppletDemo extends JApplet{public void init(){setLayout(new FlowLayout());JButton b1=new JButton("Alpha");JButton b2=new JButton("Beta");JLabel label=new JLabel("Press a button");b1.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {label.setText("You have pressed Alpha");}});b2.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {label.setText("You have pressed Beta");}});add(b1);add(b2);add(label);}}
3) Write a program to set cookie.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import javax.servlet.http.*; import java.io.*; public class Ques extends HttpServlet{ public void doGet(HttpServletRequest request,HttpServletResponse response){ response.setContentType("text/html"); try{ PrintWriter pw = response.getWriter(); Cookie cookie1 = new Cookie("FirstName", "abc"); Cookie cookie2 = new Cookie("LastName", "bcd"); cookie1.setMaxAge(24*60*60); cookie2.setMaxAge(24*60*60); response.addCookie(cookie1); response.addCookie(cookie2); pw.println("Hello user cookie has been set to your computer"); pw.close(); }catch(Exception e){ System.out.println(ex); } } } |
4) Create jsp page to display all the odd numbers between 10 and 50.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<html> <head> <title></title> </head> <body> <% for(int i=10; i<=50; i++){ %> if(i%2!=0){ (%i = %) } <% } %> </body> </html> |
5) Create applet having <para> tag.
1 2 3 |
<applet code ="abc.applet" width="100px" height="100px"> <para name="a" value="10"> <para name="b" value="20"> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Ap extends Applet{ int a, b; public void start () { string b= getparameter("b"); string a= getparameter("a"); try{ if(a!= null && b!=null){ a= Integer.parseInt("a"); b= Integer.parseInt("b"); int sub=a-b; int sum=a+b; }catch(Exception e){ System.out.println(e); System.out.println("sum" +sum); System.out.println("sub" +sub); } } |
Group C
7) Describe any two layout.
1) Flow layout: The Flow Layout is used to arrange the components in a line, one after another (in a -flow). Flow Layout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel.
2) Box layout:The Box Layout is used to arrange the components either vertically or horizontally. For this purpose, Box Layout provides four constants.
8) Difference between JSP and servlet. Explain the use of web.xml with an example.
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 |
Thames
Qn.1) Write a program to illustrate how to use session state in servlet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<web-app> <servlet> <servlet-name>Servlet1</servlet-name> <servlet-class>MyServlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet1</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> <servlet> <servlet-name>Servlet2</servlet-name> <servlet-class>MyServlet2</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet2</servlet-name> <url-pattern>/welcome</url-pattern> </servlet-mapping> </web-app> |
Qn2) Write a program where user can seleclt one of the option and display the selected option.
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 |
package mynotepad1; import java.awt.Color; import java.awt.*; import java.awt.Menu; import java.awt.MenuBar; import java.awt.TextArea; public class Mynotepad1 extends Frame { TextArea ta; Mynotepad1(){ MenuBar mBar= new MenuBar(); setMenuBar(mBar); Menu files= new Menu("Files"); Menu date= new Menu ("Dates"); Menu exit= new Menu("Exit"); MenuItem mNew= new MenuItem("New"); files.add(mNew); MenuItem mOpen= new MenuItem("Open"); files.add(mOpen); MenuItem mSave= new MenuItem("Save"); files.add(mSave); files.addSeparator(); CheckboxMenuItem chMenuToolbox= new CheckboxMenuItem("Toolbox"); files.add(chMenuToolbox); ta= new TextArea(10,40); ta.setBackground(Color.gray); add(ta); mBar.add(files); mBar.add(date); mBar.add(exit); setSize(500,600); setVisible(true); } public static void main(String[] args) { new Mynotepad1(); } } |
Qn3) Repeated from past qn of 2016
Qn. 4) What is adapter class? Explain the advantages and disadvantages of adapter class over listener interfaces with suitable examples.
Adapter class is a simple java class that implements an interface with only EMPTY implementation Instead of implementing interface if we extends Adapter class ,we provide implementation only for require method. An adapter class provides the default implementation of all methods in an event listener interface. If you inherit the adapter class, you will not be forced to provide the implementation of all the methods of listener interfaces. So it saves code. You can define a new class by extending one of the adapter classes and implement only those events relevant to you.
Advantages:
• Assists unrelated classes to work together.
• Provides a way to use classes in multiple ways.
• Increases the transparency of classes.
• Its provides a way to include related patterns in a class.
Disadvantages:
• All requests are forwarded, so there is a slight increase in the overhead.
• Sometimes many adaptations are required along an adapter chain to reach the type which is required.
• No new functionality can be added in adapter class.
Examples
The following examples contain the following Adapter classes:
• ContainerAdapter class.
• KeyAdapter class.
• FocusAdapter class.
• WindowAdapter class.
• MouseAdapter class.
• ComponentAdapter class.
• MouseMotionAdapter class.
Java MouseAdapter Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.awt.*; import java.awt.event.*; public class MouseAdapterExample extends MouseAdapter{ Frame f; MouseAdapterExample(){ f=new Frame("Mouse Adapter"); f.addMouseListener(this); f.setSize(300,300); f.setLayout(null); f.setVisible(true); } public void mouseClicked(MouseEvent e) { Graphics g=f.getGraphics(); g.setColor(Color.BLUE); g.fillOval(e.getX(),e.getY(),30,30); } public static void main(String[] args) { new MouseAdapterExample(); } } |
Group C
1) Differentiate between jsp and servlet.explain the use of web.xml file with an example.
- Writing code for servlet is harder than JSP as it is html in java. 1)JSP is easy to code as it is java in html.
- Servlet plays a controller role in MVC approach. 2)JSP is the view in MVC approach for showing output.
- Servlet is faster than JSP. 3) JSP is slower than Servlet because the first step in JSP lifecycle is the translation of JSP to java code and then compile.
- Servlet can accept all protocol requests. 4) JSP only accept http requests.
- In Servlet, we can override the service() method. 5) In JSP, we cannot override its service() method.
- In Servlet by default session management is not enabled, user have to enable it explicitly. 6)In JSP session management is automatically enabled
- Servlet is a java code.
- JSP is a html based code.
Web.xml file is the configuration file of web applications in java.
It instructs the servlet container which classes to load, what parameters to set in the context,
and how to intercept requests coming from browsers.
2) Differentiate between applet and swing. explain the border layout manager.
- Swing is light weight component while applet is not.
- Applet have no main method, but swing have.
- Swing have have look and feel while Applet Does not provide this facility.
- Swing uses for stand lone Applications while Applet need HTML code for Run the Applet.
- Swing have its own Layout while Applet uses Awt Layout.
The border layout is used to arrange the component in five regions:
north,south,east,west¢er. eacch region may contain one component only.border layout creates a border layout but no gap between components. It is the default layout of frame or window.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.awt.*; import javax.swing.*; public class Border { JFrame f; Border(){ f=new JFrame(); JButton b1=new JButton("NORTH");; JButton b2=new JButton("SOUTH");; JButton b3=new JButton("EAST");; JButton b4=new JButton("WEST");; JButton b5=new JButton("CENTER");; f.add(b1,BorderLayout.NORTH); f.add(b2,BorderLayout.SOUTH); f.add(b3,BorderLayout.EAST); f.add(b4,BorderLayout.WEST); f.add(b5,BorderLayout.CENTER); f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new Border(); } } |
NCIT
SET A
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 |
<!DOCTYPE html> <html> <head> <meta charset=”ISO-8859-1”> <title>Odd and Even</title> </head> <body> <form method=”post” action=”Ques3.jsp”> <h1>Enter the number:</h1><input type=”number” name=”num”> <input type=”submit” value=”calculate”> </form> </body> </html> <%@page language=”java” contentType=”text/html; charset=ISO-8859-1”%> <!DOCTYPE html> <% int n=Integer.parseInt(request.getParameter(“num”); if(n%2==0){ out.println(“The number is even”); } else { out.println(“The number is odd”); } %> |
- Keyboard event handling by applet
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import java.awt.*;import java.awt.event.*;import java.applet.*;/*<applet code="Key" width=300 height=400></applet>*/public class Key extends Applet implements KeyListener{int X=20,Y=30;String msg="KeyEvents--->";public void init(){addKeyListener(this);requestFocus();setBackground(Color.green);setForeground(Color.blue);}public void keyPressed(KeyEvent k){showStatus("KeyDown");int key=k.getKeyCode();switch(key){case KeyEvent.VK_UP:showStatus("Move to Up");break;case KeyEvent.VK_DOWN:showStatus("Move to Down");break;case KeyEvent.VK_LEFT:showStatus("Move to Left");break;case KeyEvent.VK_RIGHT:showStatus("Move to Right");break;}repaint();}public void keyReleased(KeyEvent k){showStatus("Key Up");}public void keyTyped(KeyEvent k){msg+=k.getKeyChar();repaint();}public void paint(Graphics g){g.drawString(msg,X,Y);}}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();}}
5.
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.*; import java.sql.DriverManager; public class Five{ Connection con; Statement stmt; String sql, url; Five( ){ Class.forName(“com.mysql.jdbc.Driver”); url=”jdbc:mysql://localhost:3306/contact”; con=DriverManager.getConnection(“url”,”root”,””); stmt=con.createStatement( ); sql=”INSERT INTO Student(id, name, address, gender, program) VALUES (1,’Dikchya’, ’Sorakhutee’,’ Female’,’BIM’); int result=stmt.executeUpdate(sql); if(result!=-1){ System.out.println(“Successfully inserted”); } else { System.out.println(“Failed to insert”); } } public static void main(String[] args){ new Five( ); } } |
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 28 29 30 31 32 33 34 35 36 |
import java.awt.*; import java.awt.event.*; public class MenuDemo { public MenuDemo() { Frame f = new Frame("DashBoard"); f.setSize(400, 400); MenuBar menubar = new MenuBar(); Menu fileMenu = new Menu("File",true); Menu editMenu = new Menu("Edit"); Menu helpMenu = new Menu("Help"); menubar.add(fileMenu); menubar.add(editMenu); menubar.add(helpMenu); f.setMenuBar(menubar); MenuItem newfile = new MenuItem("New"); MenuItem openfile = new MenuItem("Open"); MenuItem newsave = new MenuItem("Save"); MenuItem newsaveas = new MenuItem("SaveAs"); MenuItem newexit = new MenuItem("Exit"); CheckboxMenuItem c1 = new CheckboxMenuItem("Check 1", true); CheckboxMenuItem c2 = new CheckboxMenuItem("Check 2"); fileMenu.add(newfile); fileMenu.add(openfile); fileMenu.add(newsave); fileMenu.add(newsaveas); fileMenu.add(newexit); fileMenu.add(c1); fileMenu.add(c2); newsaveas.setEnabled(false); f.setLocationRelativeTo(null); f.setVisible(true); } public static void main(String[] args) { new MenuDemo(); } } |
7.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import javax.swing.*; public class ListExample { ListExample(){ JFrame f= new JFrame(); DefaultListModel<String> l1 = new DefaultListModel<>(); l1.addElement("Item1"); l1.addElement("Item2"); l1.addElement("Item3"); l1.addElement("Item4"); JList<String> list = new JList<>(l1); list.setBounds(100,100, 75,75); f.add(list); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } public static void main(String args[]) { new ListExample(); }} |
-
1234567891011121314151617181920212223242526272829<!<!DOCTYPE html><html><head><title>Form </title></head><body><form action=”Form” method=”Get”>UserName:<input type=”text” name=”user”/>Password:<input type=”password” name=”pass”/><input type=”submit” name=”submit”/></form></body></html>import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class Form extends HttpServlet{public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception{HttpSession session=request.getSession( );session.setAttribute(“user”,request.getParameter(“user”);session.setAttribute(“pass”,request.getParameter(“pass”);PrintWriter out=response.getWriter( );out.println(“<! DOCTYPE html ><html><head><title>Form</title></head><body><h1>Username:”+session.getAttribute(“user”)+”<br/>Password:”+session.getAttribute(“pass”)+”</h1></body></html>”);session.invalidate( );}}
Set B
2.
Table.jsp
1 2 3 4 5 6 7 8 9 10 |
<html> <body> <h2>Enter Any 2 Numbers !!</h2> <form action="Table2.jsp" method="post"> First No: <input type="text" name="fno"><br> Second No: <input type="text" name="sno"><br> <input type="submit" value="Show Tables"> </form> </body> </html> |
Table2.jsp
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 |
<html> <body> <% int num1=Integer.parseInt(request.getParameter("fno")); int num2=Integer.parseInt(request.getParameter("sno")); int range=0;%> <table cellpadding=0 cellspacing=0 align='center' bgcolor='yellow' width=70% > <% try { for (int j = 1; j <= 10; j++) { %><tr><th>|</th><% for (range = num1; range <= num2; range++) { %><td align='center'><% out.println(range); %></td><td align='center'><%out.println("*"); %></td><td align='center'><%out.println(j); %></td><td align='center'><%out.println(" = "); %></td><td align='center'><%out.println(range * j); %><th>|</th><% } %></tr><% } } catch(Exception e) { out.println("Error"); } %> </table> </body> </html> |
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 26 27 28 29 30 31 |
<html> <body> <% int num1=Integer.parseInt(request.getParameter("fno")); int num2=Integer.parseInt(request.getParameter("sno")); int range=0;%> <table cellpadding=0 cellspacing=0 align='center' bgcolor='yellow' width=70% > <% try { for (int j = 1; j <= 10; j++) { %><tr><th>|</th><% for (range = num1; range <= num2; range++) { %><td align='center'><% out.println(range); %></td><td align='center'><%out.println("*"); %></td><td align='center'><%out.println(j); %></td><td align='center'><%out.println(" = "); %></td><td align='center'><%out.println(range * j); %><th>|</th><% } %></tr><% } } catch(Exception e) { out.println("Error"); } %> </table> </body> </html> |
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 |
import java.sql.*; import java.sql.DriverManager; public class Four{ Connection con; Statement stmt; String sql, url; Four( ){ try{ Class.forName(“com.mysql.jdbc.Driver”); url=”jdbc:mysql://localhost:3306/contact”; con=DriverManager.getConnection(“url”,”root”,””); stmt=con.createStatement( ); sql=”DELETE FROM Student WHERE Student_name=’Dikchya’); int result=stmt.executeUpdate(sql); if(result!=-1){ System.out.println(“Database has been deleted”); } else { System.out.println(“Failed to delete the database”); } } catch(Exception e){ e.printStackTrace( ); } } public static void main(String[] args){ new Four( ); } } |
5.
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 |
import java.awt.*; import java.awt.event.*; import javax.swing.*; // class extends JFrame class BorderLayoutDemo extends JFrame { BoderLayoutDemo() { JPanel pa = new JPanel(); pa.setLayout(new BorderLayout()); pa.add(new JButton("WelCome"), BorderLayout.NORTH); pa.add(new JButton("Geeks"), BorderLayout.SOUTH); pa.add(new JButton("Layout"), BorderLayout.EAST); pa.add(new JButton("Border"), BorderLayout.WEST); pa.add(new JButton("GeeksforGeeks"), BorderLayout.CENTER); add(pa); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300, 300); setVisible(true); } } public static void main(String[] args) { new BoderLayoutDemo(); } } import javax.swing.*; import java.awt.*; public class GridLayoutDemo extends JFrame { GridLayoutDemo() { JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(4, 2)); FlowLayout layout = new FlowLayout(); JPanel p2 = new JPanel(); p2.setLayout(layout); JLabel one, two, three, four; JTextField tname, tsalary, tcode, tdesig; JButton buttonSave, buttonExit; one = new JLabel("NAME"); tname = new JTextField(20); two = new JLabel("CODE"); tcode = new JTextField(20); three = new JLabel("DESIGNATION"); tdesig = new JTextField(20); four = new JLabel("SALARY"); tsalary = new JTextField(20); buttonSave = new JButton("SAVE"); buttonExit = new JButton("EXIT"); p1.add(one); p1.add(tname); p1.add(two); p1.add(tcode); p1.add(three); p1.add(tdesig); p1.add(four); p1.add(tsalary); p2.add(buttonSave); p2.add(buttonExit); add(p1, "North"); add(p2, "South"); setVisible(true); this.setSize(400, 180); } public static void main(String args[]) { new GridLayoutDemo(); } } |
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 28 29 30 31 32 33 34 35 36 37 |
import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; public class JTableExamples { // frame JFrame f; // Table JTable j; // Constructor JTableExamples() { // Frame initiallization f = new JFrame(); // Frame Title f.setTitle("JTable Example"); // Data to be displayed in the JTable String[][] data = { { "Kundan Kumar Jha", "4031", "CSE" }, { "Anand Jha", "6014", "IT" } }; // Column Names String[] columnNames = { "Name", "Roll Number", "Department" }; // Initializing the JTable j = new JTable(data, columnNames); j.setBounds(30, 40, 200, 300); // adding it to JScrollPane JScrollPane sp = new JScrollPane(j); f.add(sp); // Frame Size f.setSize(500, 200); f.setVisible(true); } public static void main(String[] args) { new JTableExamples(); } } |
7.
INDEX.JSP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <form method=”post” action=”servlet”> Name:<input type="text" name="name" value="" /> Num1:<input type="text" name="num1" value="" /> Num2:<input type="text" name="num2" value="" /> <br> <input type="submit" value="button" /> </form> </body> </html> |
Servlet:
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 |
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "HelloServelet", urlPatterns = {"/HelloServelet"}) public class HelloServelet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String name = request.getParameter("name"); int a = request.getParameter("num1"); int b = request.getParameter("num2"); int pro = 0; int x,y; x = Integer.parseInt(a); y = Integer.parseInt(b); pro = x * y; out.println("Hi!" + name + "The product is" + pro); out.close(); } } |