Ajava Imp Question With Answer
Ajava Imp Question With Answer
Ajava Imp Question With Answer
UNIT-1
1) Explain Life cycle of APPLET
Ans:
✓ Every java applet inherits a set of default behaviours from the Applet class.so when an
applet is loaded ,it undergoes a series of changes in its state.
✓ The applet states are:
1. Born or Initialization state
2. Running state
3. Idle state
4. Dead or destroyed state
1) Initialization state(Born)
✓ Applet enters the initialization state when it is first loaded.this is achieved by calling the init()
method of Applet class.The applet is born.
✓ Initialization occurs only once in the applet’s life cycle.
✓ To provide any of behaviour mentioned above,we must overrride init() method:
public void init()
{
............(Action)
............
}
2) Running state
✓ Applet enters the running state when the system calls start() method of Applet class.This
occurs automatically after applet is initialized.
✓ Unlike init() method,the start() method may be called more than once.
✓ We may override the start() method to create a thread to control the applet.
public void start( )
{
............(Action)
............
1
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
HEIGHT = Pixels
[ALIGN= Alignment]
[VSPACE = Pixels]
[HSPACE = Pixles]
[<PARAM NAME=name1 VALUE= value1 >]
[<PARAM NAME=name2 VALUE= value2 >]
..............
</APPLET>
NO Attribute Meaning
CODE=AppletfileName.class Specifies the name of the applet class to be
1 (necessary) loaded.
CODEBASE= codebase_URL Specifies URL of the directory in which the
2 (Optional) applet resides.(must used in remote applet)
WIDTH = Pixels Specify width and height of the space on the
3 HEIGHT = Pixels(necessary) HTML page that will be reserved for applet.
Name = applet_instance_name A name for the other applet on the page may
4 (Optional) refer to this applet.
[ ALIGN= Alignment] Alignment of applet on page.
5
(Optional)
[ VSPACE = Pixels ] It specifies amount of vertical blank space the
6
(Optional) browser should leave surrounding the applet.
[ HSPACE = Pixels] It specifies amount of horizontal blank space the
7
(Optional) browser should leave surrounding the applet.
[ALT = Alternate_text ] Non _java browser will display this text where
8
(Optional) the applet would normally go.
✓ We can define init() method in applet to get hold of the parametes defined in
<PARAM> tags.
✓ getParameter() method ,takes one string argument representing the name of program.
✓ Each <PARAM...> tag has a name attribue and value attribute .
Syntax:
<APPLET.......>
<PARAMname=color value=“red”>
<PARAMname=text value=“I like java!”>
</APPLET>
Example:
import java.applet.*;
import java.awt.*;
/*
<applet code=ParamTest.class width=500 height=300>
<param Name="Author" value="Balaguru swami">
</applet>
*/
4
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
5
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
import java.awt.*;
import java.applet.*;
/*<applet code=Hello.class width=400 heigth=400>
</applet>*/
public class Hello extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.pink);
g.drawString( “Hello java” ,10,100);
}
}
import java.awt.*;
import java.applet.*;
/*<applet code=Hello.class width=400 heigth=400>
</applet>*/
public class Hello extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.pink);
g.drawString( “Hello java” ,10,100);
}
}
No Methods Action
6
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
7
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
UNIT-2
1) What is Swing? Explain the need of swing.
Ans:
✓ Swing is a part of the java foundation classes.
✓ It is an extension library to AWT.
✓ Swing is a set of classes that provide more powerful and flexible components than
AWT
Need of Swing
✓ The uniform look and feel across platform is an advantage of swing
✓ Swing is light weight components.
✓ Swing is compatible for standalone/GUI applications, Applets and servlets.
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=FrameDemo1.class width=250 height=150></applet>*/
public class FrameDemo1 extends Applet
{ Frame f;
Button b1;
public void init()
{ f=new Frame("Frame Window");
b1=new Button("Show Window");
add(b1);
}
8
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
Before
After
9
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
Canvas();
Canvas(graphics configuration config);
➢ Methods:
GetAccessibleContext();
getBufferStrartegy();
paint(Graphics g);
update(Graphics g);
createBufferStrategy(int num Buffers);
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=CanvasDemo.class width=250 height=150></applet>*/
public class CanvasDemo extends Applet
{ Canvas c;
public void init()
{
c=new Canvas();
c.setBackground(Color.pink);
c.setSize(50,90);
add(c);}}
Output:
Listeners: It is an object that the listener to the event. Once the event is received by the
listener can the process of event and then returns it.
8) List layouts manager, classes in java. Explain any one with example.
Ans:
12
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
public void setMnemonic(int a): is used to set the mnemonic on the button.
public void addActionListener(ActionListener a): is used to add the action
listenerto this object.
Constructor for JButton:
JButton(Icon i)
JButton(String s)
JButton(String s,Icon i) //s and i are the string and icon used for the button.
Example:
import java.awt.*;
import javax.swing.*;
public class JButtonDemo extends JFrame
{
JButtonDemo(String title)
{
super(title);
setLayout(new GridLayout(3,2));
Icon plus= new ImageIcon("plus.png");
JButton b1=new JButton("ADD",plus);
JButton b2=new JButton("OK");
add(b1);
add(b2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
JButtonDemo t=new JButtonDemo("JButton Demo");
t.setSize(300,100);
t.setVisible(true);
}}
13
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
CheckboxGroup () method.
Checkbox is use for multiple selection RadioButton is use for single selection.
Syntax:- Syntax:-
Checkbox ch1=new checkbox(“pen”); CheckboxGroup ch=new CheckboxGroup();
Add(ch1); Checkbox ch1=new checkbox(“female”);
Ch1.setcheckboxgroup(ch1);
Ch1.setstate(false);
Add(ch1);
MouseEvent Description
Method
getClickCount() It can return number of times the mouse was clicked.
getPoint() It can return a point of object is an AWT class that can represents
the X and Y co-ordinates.
getX() It can return the X co-ordinates of the point at which the event
can occur.
getY() It can return the Y co-ordinates of the point at which the event
can occur.
EXAMPLE: -
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code= Mousedemo.class Width=500 Height=500>
</applet>*/
Public class Mousedemo extends Applet implement MouseListener
{
String message;
14
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
Method Description
Public void KeyTyped Invoked when a key has been typed
(KeyEvent e) (pressed and released).
Public void KeyPressed Invoked when a key has been pressed.
(KeyEvent e)
Public void KeyReleased Invoked when a key has been released.
(KeyEvent e)
EXAMPLE: -
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code= Keydemo.class Width=500 Height=500>
</applet>*/
Public class Keydemo extends Applet implement KeyListener
{
TextArea t1;
Public void init()
{
15
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
addKeyListener(this);
}
Public void KeyPressed(KeyEvent e)
{
showStatus(“Key is pressed”);
}
Public void KeyReleased(KeyEvent e)
{
showStatus(“Key is Released”);
}
Public void KeyTyped(KeyEvent e)
{
showStatus(“Key is Typed”);
}}
1) Component
✓ Component class is derived from object class.
✓ It is the super class for all AWT components class such as Label, TextComponent,
RadioButton, and CheckBox etc.
2) Container
✓ Container class is derived from component class.
✓ The Container is a component in AWT that can contain another component like
buttons, textfields, labels etc. The class that extends Container class is known as
container such as Frame, Dialog and Panel.
3) Windows
✓ Windows class is derived from container class.
✓ The window is the containers that have no borders and menu bars. You must use frame,
dialog or another window for creating a window.
4) Panel
16
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
17
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
{
String s = "This is a very long label";
Label l1 = new Label(s, Label. LEFT);
add (l1);
Label l2 = new Label(s, Label. CENTER);
add (l2);
Label l3 = new Label(s, Label. RIGHT);
add (l3);
}}
18) Explain border layout, flow layout, grid layout with example.
Ans:
Flow Layout (default Layout): see above Question-answer.
Grid Layout:
✓ The Grid layout class puts each component into a place on a grid that is equal in size to all
the other places.
✓ The grid is given specific dimensions when created; Components are added to the grid in
order, starting with upper-left corner to right.
✓ Components are given equal amounts of space in the container.
✓ Grid layout is widely used for arranging components in rows and columns.
18
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
✓ However unlike, Flow Layout, here underlying components are resized to fill the row-
column area. if possible.
✓ Grid Layout can reposition objects after adding or removing components. Whenever area is
resized, components are also resized.
GridLayout b1=new GridLayout (2, 3); // 4 rows and 1 column
SetLayout (b1)
Border Layout
✓ Border layout is the default layout manager for all window, dialog and frame class.
✓ In Border layout, components are added to the edges of the container, the center area is
allotted all the space that’s left over.
✓ Border layout ,provides five areas to hold component:
Four border→ north, south, east, and west
Remaining space: center
✓ When you add a component to the layout you must
Specify which area to place it in.
✓ Java event handling mechanism is represented by event classes.At the root of the java
event class hierarchy is EventObject.
✓ EventObject (Object src)-src are the object that generates event.
19
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
Method Description
WindowActivated Invoked when a window is activated.
(WindowEvent e)
WindowClosed Invoked when a window has been closed.
(WindowEvent e)
WindowClosing Invoked when a window is in the process of being
(WindowEvent e) closed.
WindowOpened (WindowEvent e) Invoked when a window has been opened.
WindowDeactivated(WindowEvent e) Invoked when a window is deactivated.
EXAMPLE:
import java.awt.*;
import java.awt.event.*;
public class windowprogram extends Frame implements WindowListener
{
TextArea t1;
Public windowprogram()
20
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
{
addWindowListener(this);
setTitle(“Windowed Program”);
setSize(400,400);
setVisible(true);
t1=new TextArea(5,50);
add(t1);
}
public void WindowClosing(WindowEvent e)
{
setVisible(false);
System.exit(0);
}
Public void WindowOpened(WindowEvent e)
{
t1.append Text(“window is opened”);
}
Public void WindowClosed(WindowEvent e)
{
t1.append Text(“window is closed”);
}
Public static void main(String[] args)
{
New windowprogram();
}}
21
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
22
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
UNIT-3
1) Which package is used to perform almost all JDBC operations?
Ans: Java.sql package is used to perform almost all JDBC operations.
2) List JDBC API components. Explain in brief.
Ans:
JDBC has four Components:
1. The JDBC API.
2. The JDBC Driver Manager.
3. The JDBC Test Suite.
4. The JDBC-ODBC Bridge.
1. JDBC API
✓ JDBC API (application programming interface) is a part of the Java platform that
have included in Java Standard Edition (Java SE) and the Java Enterprise Edition
(Java EE) in itself.
✓ The latest version of JDBC 4.0 application programming interface is divided into
two packages
java.sql
javax.sql.
✓ These packages contain all the APIs which provide programmatic access to a
relational database (like oracle, SQL server, MySQL etc.)
✓ Using it, front end java applications can execute query and fetch data.
2 JDBC Driver Managers
✓ This interface manages a list of database drivers. Matches connection requests from
the java application with the proper database driver using communication sub
protocol.
✓ The first driver that recognizes a certain sub protocol under JDBC will be used to
establish a database Connection.
✓ Internally, JDBC Driver Manager is a class in JDBC API. The objects of this class
can connect Java applications to a JDBC driver.
✓ Driver Manager is the very important part of the JDBC architecture. The main
responsibility of JDBC Driver Manager is to load all the drivers found in the system
properly.
✓ The Driver Manager also helps to select the most appropriate driver from the
previously loaded drivers when a new open database is connected.
3 JDBC Test Suite
✓ The function of JDBC driver test suite is to make ensure that the JDBC drivers will
run user's program or not.
✓ The test suite of JDBC application program interface is very useful for testing a
driver based on JDBC technology during testing period.
✓ It is used to check compatibility of JDBC driver with (J2EE)Java Platform
Enterprise Edition.
4 JDBC-ODBC Bridge
✓ The JDBC-ODBC Bridge, also known as JDBC type 1 driver is a database driver
that utilizes the ODBC driver to connect the database.
23
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
✓ This driver translates JDBC method calls into ODBC function calls. The Bridge
implements JDBC for any database for which an ODBC driver is available. The
Bridge is always implemented as the sun.jdbc.odbc
✓ Java package and it contains a native library used to access ODBC.
✓ ODBC driver is already installed or come as default driver in windows.
4) List JDBC driver .explain JDBC .NET pure java driver (Type -3).
Ans:
24
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
5) Whatis a JDBC connection? Explain steps to get database connection using java program.
Ans:
✓ A Connection is the session between java application and database.
✓ The Connection interface is a factory of Statement, PreparedStatement, and
DatabaseMetaData i.e. object of Connection can be used to get the object of
Statement and DatabaseMetaData.
✓ The Connection interface provide many methods for transaction management like
commit(),rollback() etc
Steps to get Database connection
1. Register the driver class
25
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
7) Develop a JDBC application that uses any JDBC drivers to display all records.
Ans:
Import java.sql.*;
public class selectdata
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection ("jdbc: mysql://localhost:3306/mydb","root", "");
Statement stmt=cn.createStatement ();
System.out.println (“Table data :”);
ResultSet rs=stmt.executeQuery ("select distinct * from stud");
While (rs.next ())
{
System.out.println (rs.getInt ("id") + "\t");
System.out.println (rs.getString ("name") +"\n");
}
}
Catch (Exception e)
{
System.out.println (e);
}
}
}
Output:
26
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
Table data:
1 Sita
8) Develop a JDBC application that uses any JDBC drivers to deletea record.
Ans:
import java.sql.*;
public class del { public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection ("jdbc: mysql://localhost:3306/mydb","root","");
Statement stmt=cn.createStatement();
String sql = "delete from stud “+ "where id=2";
stmt.execute(sql);
System.out.println ("Row is deleted");
}
Catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Row is deleted
1 Rita
9) Develop a JDBC application that uses any JDBC drivers to insert a record.
Ans:
import java.sql.*;
public class insert
{
public static void main (Stringargs [])
{
Try
{
Class.forName ("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection ("jdbc: mysql: //localhost:3306/mydb","root","");
Statement stmt=cn.createStatement ();
String sql = "INSERT INTO student VALUES (1, 'Rita') ";
stmt.execute (sql);
String sql = "INSERT INTO student VALUES (2, 'Ram') ";
stmt.execute (sql);
System.out.println (“Row is inserted");
ResultSet rs=stmt.executeQuery ("select DISTINCT * from stud ");
While (rs.next ())
{
27
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
28
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
Ans:
Advantages:
1. Can read any database if proper derivers are installed.
2. Creates XML structure of data from database automatically.
3. No content conversion required.
4. Query and stored procedure supported.
5. Supports modules.
Disadvantages:
1. JDBC is not good if used in large project.
2. It is not at all good in the transaction management.
3. JDBC needs database specific queries.
4. JDBC cannot maintain the database independent SQL statement.
5. When multiple connection are created and closed affects the performance.
6. Exception handling is one of the main drawbacks in JDBC.
29
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
✓ The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers
connected to multiple databases.
✓ In the three-tier model, commands are sent to a "middle tier" of services, which then
sends the commands to the data source.
✓ The data source processes the commands and sends the results back to the middle
tier, which then sends them to the user.
30
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)
✓ MIS (management information system) directors find the three-tier model very
attractive because the middle tier makes it possible to maintain control over access
and the kinds of updates that can be made to corporate data.
✓ Another advantage is that it simplifies the deployment of applications. Finally, in
many cases, the three-tier architecture can provide performance advantages.
31
Gtu paper solution AJAVA(3360701)
UNIT-4
SERVLET
1) What is Servlet? What is difference between Servlet and Applet?
Ans:
✓ Servlet is a technology which is used to create web application.
✓ Servlet technology is used to create web application which resides at server
side and generates dynamic web page.
✓ Servlet technology uses java language to create dynamic web application.
✓ Servlet are designed to work within a request/response processing model.
Servlet Applet
A java servlet executes on the A java Applet executes on the
Web Server in response to Web Browser.
requests from a Web Browser.
Servlet have no GUI. Applets are rich in GUI
Servlet is server side technology.
Applet is client side
technology.
Servlet are more powerful than Java Applets are limited to
Applet. certain operations on the
Browser.
Servlets can be used for server Applets can be used for client
side data validation. side data validation.
2) What is the difference between doGet () method and doPost () method?
Ans:
doGet() doPost()
Data is sent in header to the Data is sent in request body.
server.
Data request can send only Large amount of data can be
limited amount of data. send in Post method.
Get request is not secured Post request is secured
because data is exposed in URL. because data is not exposed in
URL.
Get request is more efficient. Post request is less efficient.
Get request can be bookmarked. Post request is not
bookmarked.
Page 1
Gtu paper solution AJAVA(3360701)
Page 2
Gtu paper solution AJAVA(3360701)
WEB.XML FILE:
<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
<init-param>
<param-name>userName</param-name>
<param-value>Shweta</param-value>
</init-param>
</servlet>
<Servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/DemoServlet</url-pattern>
</servlet-mapping>
</web-app>
SERVLET FILE:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
Page 3
Gtu paper solution AJAVA(3360701)
5) Create a web form which process servlet and demonstrates use of cookies?
Ans:
Simple example of Servlet Cookies
✓ In this example, we are storing the name of the user in the cookie object and
accessing it in another servlet.
✓ As we know well that session corresponds to the particular user. So if you
access it from too many browsers with different values, you will get the
different value.
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
Page 4
Gtu paper solution AJAVA(3360701)
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse resp
onse){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
Page 5
Gtu paper solution AJAVA(3360701)
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Page 6
Gtu paper solution AJAVA(3360701)
✓ You can pass parameters to a servlet from the web.xml file too. They are
called initialization parameters.
✓ The ServletConfig interface is implemented by the server. It can allow servlet
to get the information about the Configuration during its initialization.
✓ There are two types of init parameters available. They are both referred to as
initparameters, although defined in different elements.
Servlet init parameters (defined in <init-param> elements).
o Servlet init parameters are available to only the servlet for which the
<init-param> was configured.
o Servlet init parameters are defined within the <servlet> elements for
each specific servlet.
Context init parameters (defined in <context-param> elements).
o Context init parameters are available to only the servlet or JSP that are
the part of the current web app.
o Context init parameters are defined within the <Web-app> elements.
METHOD DESCRIPTION
String getInitParameter(String Returns a string which can
name) contains the value of the
initialization parameter and name
which can defines names of
initialization parametes.
Enumeration Returns Enumeration of string
getInitParameterNames() objects containing the names of
all initialization parameters.
Public Returns the reference of
ServletContextgetServletContext() ServletContext
Page 7
Gtu paper solution AJAVA(3360701)
Page 8
Gtu paper solution AJAVA(3360701)
Page 9
Gtu paper solution AJAVA(3360701)
Page 10
Ajava(3360701)
UNIT-5(JSP)
1) Difference between JSP and Servlet.
Ans:
JSP Servlet
JSP is a file which consists of Servlet is a java class.
HTML tag and scripting code.
Files are saved using .jsp extension Files are saved using .java
extension
It is server side scripting language Servlet is special program of JAVA
which is used to develop dynamic that is already compiled and used to
web pages. create dynamic web contents.
JSP run slower as compared to Servlet runs faster as compared to
Servlet because we need to compile JSP because servlet is already
the code written in JSP to convert it compiled.
in servlet code.
Coding is easy in JSP as compared Coding is difficult in servlet as
to Servlet. compared to Servlet.
JSP are supported to HTTP protocol Servlets are supported to HTTP,
only. FTP and SMTP protocols.
out.print("</tr>"); }
out.print("</table>");
}
catch(Exception e) {
} %>
</body>
</html>
Output:
✓ Servlet and JSP are the main technologies to develop the web applications.
✓ Servlet was considered superior to CGI. Servlet technology doesn't create
Process, rather it creates thread to handle request. The advantage of creating
thread over process is that it doesn't allocate separate memory area. Thus
many subsequent requests can be easily handled by servlet.
✓ Problem in Servlet technology Servlet needs to recompile if any designing
code is modified. It doesn't provide separation of concern. Presentation and
Business logic are mixed up.
Page 2
Ajava(3360701)
<Html>
<Head>
<title>JSP Hello World</title>
</head><body>
<%! int a=2;int b=3; %>sum of a and b= <%= a+b %>
</body></html>
Output :
sum of a and b=5
Page 3
Ajava(3360701)
Translation:
✓ JSP container checks the JSP page code and converts it to generate the servlet
source code.
✓ After JSP page is translated into servlet all the request for that JSP page are
served by its related servlet class.
Compilation of JSP Page
✓ In this Java source code for the related servlet is compiled by the JSP
container. The container converts source code into byte code.
Class loading:
✓ In this servlet class file is loaded by the class loader.
Instantiation:
✓ Object of the Generated Servlet is created.
Initialization:
✓ In this instantiated object is initialized. For this jspInit() method is invoked by
the container.
✓ jspInit( ) method declared in JSP page and it is implemented by JSP
container.This method called once in JSP life cycle to initialize it with config
params configured in deployment descriptor.
Request processing:
✓ In this stage of JSP life cycle only those objects of a JSP equivalent servlet
that initialized successfully are used by the web container to handle client
request.
✓ _jspService () method is invoked by the container for each client request by
passing request and response object.
Destroy:
✓ If a servlet container decides to destroy a servlet instance of a JSP
page,jspDestroy () method is invoked by the container.
✓ It clean up the environment .It is called only once in JSP life cycle.
Page 4
Ajava(3360701)
Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
6) Write a JSP program of user login form with static data.
Ans:
Index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<form action="wel.jsp" method="Post">
<table>
<tr> <td>User Name: </td> <td>
<input type="text" name="userName"/>
</td> </tr>
<tr> <td>Password: </td> <td>
<input type="password" name="userPass"/></td> </tr>
<tr><td><input type="submit" value="Login"/></td> </tr>
</table>
</form>
</body>
</html>
Welcome.jsp
<%@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>
<% String uname = request.getParameter("userName");
String pass = request.getParameter("userPass");
if(uname.equals("shweta") && pass.equals("123"))
{
out.println("Successfully Login");
out.println("Welcome "+uname);
}
else
{
out.println("Sorry..!!! Wrong User Name & Password");
} %>
</body>
</html>
Page 5
Ajava(3360701)
Output:
Page 6
Ajava(3360701)
JSP
✓ JSP are text document that describe how a server should handle specific
requests.
✓ JSP is run by JSP server, which interprets the JSP and performs the actions the
page describes.
✓ JSP server compiles the JSP into a servlet to enhance performance. The server
would the periodically check the JSP for changes. If JSP changes the server
will recompile it into a servlet.
✓ JSP is extension to servlet.
✓ JSP looks very similar to static HTML pages, expect they contain special tags
are used to identify and define areas that contain java functionality.
8) Explain JSP scripting elements.
Ans:
✓ The scripting elements provides the ability to insert java code inside the JSP
✓ There are mainly three types of scripting elements:
1. Scriptlet tag
2. Expression tag
3. Declaration tag
Note: Explain each tag with Example.
9) Write simple JSP program to print “HELLO”.
Ans:
<html>
<head>
<title>JSP Hello World</title>
</head>
<body>
<% out.println("Hello World<br>"); %>
</body>
</html>
Output:
Hello World
10) How to access database using JSP. Explain with example.
Ans: See Question 2.
11) Explain <scriptlet> tag with syntax.
Ans:
✓ It is used to execute java source code in JSP.
✓ A scriptlet can contain any number of JAVA language statements, variable or
method declarations, or expressions that are valid in the page scripting
language.
✓ Scriptlet evaluated at request processing time, using the values of any
declarations and expressions that are made to them.
✓ It is used to do complex code rather than simple expression scriptlet tag is
used.
Syntax of Scriptlet:
<% code fragment %>
You can write scriptlet tag in XML as follows:
<jsp: scriptlet>
Page 7
Ajava(3360701)
Code fragment
</jsp: scriptlet>
Example-Write a program to print Hello world in JSP
<html>
<head>
<title>JSP Hello World</title>
</head>
<body><% out.println("Hello World<br>"); %></body>
</html>
Output: Hello World
12) Develop a JSP program to display the grade of a student by accepting the marks of
five subjects.
Ans:
index .jsp
<html>
<head>
<title>JSP Program</title>
</head>
<body>
<form action="StudentGrade" method="Post">
<table>
<tr><td>Subject 1: </td>
<td><input type="text" name="sub1"/></td>
</tr>
<tr><td>Subject 2: </td>
<td><input type="text" name="sub2"/></td>
</tr>
<tr><td>Subject 3: </td>
<td><input type="text" name="sub3"/></td></tr>
<tr><td>Subject 4: </td>
<td><input type="text" name="sub4"/></td>
</tr>
<tr><td>Subject 5: </td>
<td><input type="text" name="sub5"/></td></tr>
<tr><td><input type="submit"
value="Submit"/></td></tr></table></form></body></html>
Grade.jsp
<html>
<head>
<title>JSP Grade</title>
</head>
<body><% int sub1 = Integer.parseInt(request.getParameter("sub1"));
int sub2 = Integer.parseInt(request.getParameter("sub2"));
int sub3 = Integer.parseInt(request.getParameter("sub3"));
int sub4 = Integer.parseInt(request.getParameter("sub4"));
Page 8
Ajava(3360701)
Page 9
Ajava(3360701)
Connection cn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/vpmp","root","");
Statement stmt = cn.createStatement();
int no = stmt.executeUpdate("insert into student
values('"+Uid+"','"+Uname +"')");
if(no>0)
{
out.println("Data inserted successfully");
} }
catch(Exception e) {
} %>
</body>
</html>
Output:
Page 10