1. QUESTION BANK
UNIT –IV
Q.1 What is JSP?What are the advantages and disadvantages of JSP?
Ans: JavaServerPages(JSP) isa server-sideprogramming technology thatenablesthecreation of dynamic,platform-
independentmethod forbuilding Web-based applications.
Advantages:
1. HTML friendly simpleand easy languageand tags
2. Supportsjava code
3. Supports standard web sitedevelopmenttools
4. Rich UIfeatures
5. Much Java knowledgeisnot required
Disadvantages:
1. As JSPpagesaretranslated into servlet and compiled,it is difficult to trace the errorsoccurred in JSPpage
2. JSP pagesrequiresdoublethe disk spaces
3. JSP requiresmore time to executewhen it is accessed forthe first time
Q.2 Write a JSP code to print the detailsenteredinthe form on the nextpage?( The detailsenteredinthe html page
are Name,Username,DOB, DOJ, Gender)
Ans: HTML Code:
<formmethod=postaction=”display.jsp”>
<pre>
Enter yourName:<inputtype=textname=t1>
Enter DOB: <inputtype=textname=t2>
Enter DOJ: <inputtype=textname=t3>
Select yourGender: <input type=radio name=r1value=”Male”> Male
<input type=radio name=r1value=”Female”> Female
<input type=submitvalue=”Clickhere”>
</pre>
</form>
JSP Code:
<%
String a,b,c,d;
A=request.getParameter(“t1”);
B= request.getParameter(“t2”);
C= request.getParameter(“t3”);
D= request.getParameter(“r1”);
Out.println(“Nameis:”+a +” n DOB is:”+ b+ “n DOJis:”+ c+”
n YourGender is:”+ d);
%>
Q.3 Explainthe architecture of JDBC
Ans: The JDBC APIsupportsbothtwo-tierand three-tierprocessing modelsfor
databaseaccess.
Figure 1: Two-tier Architecture for Data Access.
2. In thetwo-tiermodel,a Java application talksdirectly to the data source.
This requires a JDBCdriver thatcan communicatewith theparticular data
sourcebeing accessed.A user's commandsaredelivered to thedatabaseor
otherdatasource,and the resultsof thosestatementsaresentback to the
user.The datasourcemay be located on anothermachineto which theuser is
connected via a network.This is referred to as a client/serverconfiguration,
with theuser's machineas theclient, and themachinehousing thedata
sourceas the server.The networkcan be an intranet,which,forexample,
connectsemployeeswithin a corporation,orit can be the Internet.
Figure 2: Three-tier Architecture for Data Access.
In thethree-tier model,commandsaresentto a "middletier" of services,
which then sendsthecommandsto thedata source.The data source
processesthecommandsand sendstheresultsbackto the middle tier, which
then sendsthem to the user.MIS directorsfind the three-tier modelvery
attractivebecausethe middle tier makesit possibleto maintain control over
accessand the kindsof updatesthatcan bemadeto corporatedata.Another
advantageisthatit simplifies the deploymentof applications.Finally,in
many cases,thethree-tier architecturecan provideperformanceadvantages.
Q.4 Write a JDBC program to insertfive records in customertable with fieldsCustNo,FName,LName,Address,Mobno
& Email
Ans: importjava.sql.*;
importjava.io.*;
class JdbcDemo
3. {
public static void main(String args[])throwsException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:user");
Statementst= con.createStatement();
st.executeUpdate("createtablecustomer(cno integer,cfname
varchar(10),clnamevarchar(10),addressvarchar(25),mobile
varchar(10),emailvarchar(30)");
st.executeUpdate("insertinto customer
values(1,’john’,’willy’,’normal’,’123’,’ss@ss.com’)");
st.executeUpdate("insertinto customer
values(2,’john’,’willy’,’normal’,’123’,’ss@ss.com’)");
st.executeUpdate("insertinto customer
values(3,’john’,’willy’,’normal’,’123’,’ss@ss.com’)");
st.executeUpdate("insertinto customer
values(4,’john’,’willy’,’normal’,’123’,’ss@ss.com’)");
st.executeUpdate("insertinto customer
values(5,’john’,’willy’,’normal’,’123’,’ss@ss.com’)");}
catch(SQLException s) {
System.out.println(s);
}
catch(ClassNotFoundException c)
{
System.out.println(c);
}
finally()
{
if(con!=null)
{
st.close();
con.close();
}
}}
}
Q.5 Explainthe componenetsofJDBC
Ans: DriverManager: This class managesa list of databasedrivers.Matchesconnection requestsfromthejava
application withthe properdatabasedriverusing communication subprotocol.Thefirst driverthat
recognizesa certain subprotocolunderJDBCwill be used to establish a databaseConnection.
Driver: This interfacehandlesthecommunicationswith thedatabaseserver.You will interactdirectly with
Driver objectsvery rarely. Instead,you useDriverManagerobjects,which managesobjectsof thistype.It
also abstractsthe detailsassociated with working with Driver objects
Connection: This interfacewith all methodsforcontacting a database.Theconnection objectrepresents
communication context,i.e.,allcommunication with databaseisthrough connection objectonly.
Statement : You use objectscreated fromthis interfaceto submittheSQL statementsto the database.
Somederived interfacesaccept parametersin addition to executing stored procedures.
4. ResultSet: These objectshold data retrieved froma databaseafteryou executean SQL query using
Statementobjects.Itactsas an iterator to allow you to movethrough itsdata.
SQLException:This class handlesany errorsthat occurin a databaseapplication
Q.6 Write an exhaustive note on “preparedstatement”.Attach code specificationtosupport your answer
Ans: Prepared Statementwhen you plan to use theSQL statementsmany times.
The Prepared Statementinterfaceacceptsinputparametersatruntime.
The PreparedStatementinterfaceextendstheStatementinterfacewhich givesyou added functionalitywith
a coupleof advantagesovera generic Statementobject.
This statementgivesyou the flexibility of supplying argumentsdynamically
Example:
PreparedStatementpstmt=null;
try
{
String SQL = "UpdateEmployeesSETage = ? WHERE id = ?";
pstmt= conn.prepareStatement(SQL);.. .
}
catch (SQLException e) { . . . }
finally { . . . }
Q.7. Enlistthe implicitobjectsof JSP. Explianany four of themin detail
Ans: JSPImplicit Objectsarethe Java objectsthattheJSPContainermakesavailableto developersin each pageand
developercan call them directly withoutbeing explicitly declared.JSPImplicit Objectsarealso called pre-defined
variables.
JSP supports ImplicitObjects whichare listed below:
1. The request Object:
The requestobjectis an instanceof a javax.servlet.http.HttpServletRequestobject.Each timea client requestsa
pagethe JSPenginecreates a newobjectto representthatrequest.
The requestobjectprovidesmethodsto getHTTP headerinformation including formdata,cookies,HTTPmethods
etc.
2. The responseObject:
The responseobjectis an instanceof a javax.servlet.http.HttpServletResponseobject.Justastheserver createsthe
requestobject,it also createsan objectto represent theresponseto theclient.
3. The outObject:
The outimplicit objectis an instanceof a javax.servlet.jsp.JspWriter objectand isused to send contentin a
response.Theinitial JspWriterobjectis instantiated differently dependingon whetherthepageis buffered ornot.
Buffering can be easily turned off by using thebuffered='false'attributeof the pagedirective.TheJspWriter object
containsmostof the samemethodsasthejava.io.PrintWriterclass.
4. The sessionObject:
The session objectis an instanceof javax.servlet.http.HttpSessionand behavesexactly thesameway thatsession
objectsbehaveunderJava Servlets.Thesession objectis used to track client session between client requests.
5. The exceptionObject:
The exception objectis a wrappercontaining theexception thrown fromthepreviouspage.Itis typically used to
generatean appropriateresponseto theerror condition.
Exampleof JSP request implicit object:
5. index.html
<form action="welcome.jsp">
<input type="text"name="uname">
<input type="submit"value="go"><br/>
</form>
welcome.jsp
<%
String name=request.getParameter("uname");
out.print("welcome"+name);
%>
Q.8. Write a jsp that accepts user-logindetailsandforward the result either”Accessgranted” or Access denied” to
result.jsp
Ans: index.jsp
<formmethod="POST"action="logn">
Name:<inputtype="text"name="userName"/><br/>
Password:<inputtype="password"name="userPass"/><br/>
<input type="submit"value="login"/>
</form>
Login
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet")){
RequestDispatcherrd=request.getRequestDispatcher("/result.jsp");
rd.forward(request,response); }
else{
out.print("Sorry Accessdenied !!!");
RequestDispatcherrd=request.getRequestDispatcher("/index.jsp");
rd.include(request,response); }
result
out.print("Accessgranted !!!");
Q.9 Write a JSP based applicationthat servesthe purpose of simple calculator
Ans: Calculate.jsp
<h1>CALCULATE</h1>
<formmethod="post"action="calser">
Enter Number1 :<input type="text"name="t1"/>
Enter Number2 :<input type="text"name="t2"/>
<select name="t3">
<option value="+">+</option>
<option value="-">-</option>
<option value="/">/</option>
</select>
<inputtype="submit"name="CALCULATE"/>
6. </form>
Calser.java// servlet filecreated
protected void processRequest(HttpServletRequestrequest,HttpServletResponse
response)
throwsServletException,IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out= response.getWriter()) {
out.println("<!DOCTYPEhtml>");
out.println("<html>");
out.println("<head>");
out.println("<title>Calculate</title>");
out.println("</head>");
out.println("<body>");
int a=Integer.parseInt(request.getParameter("t1"));
int b=Integer.parseInt(request.getParameter("t2"));
String c =request.getParameter("t3");
out.println("<h1>Hello"+ c + "</h1>");
if(c.equals("+"))
out.println("<h1>Sum:"+ (a+b) + "</h1>");
else if(c.equals("-"))
out.println("<h1>Sub :"+ (a-b) +"</h1>");
else
out.println("<h1>Div :" + (a/b) + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
Q.10 Explainthe scrollable ResultSets with an example
Ans: The SQL statementsthatread data froma databasequery return thedata in a result set. The SELECT
statementis the standard way to selectrows froma databaseand view themin a result set.
Thejava.sql.ResultSetinterfacerepresentstheresultset of a databasequery.
A ResultSetobjectmaintainsa cursor thatpointsto thecurrent row in theresult set. The term "result set"
refers to the rowand column datacontained in a ResultSetobject.
Types :
ResultSet.TYPE_FORWARD_ONLY
The cursorcan only moveforward in the result set.
ResultSet.TYPE_SCROLL_INSENSITIVE
The cursorcan scroll forwardsand backwards,and theresultsetis notsensitiveto
changesmadeby othersto the databasethatoccurafterthe resultset was created.
ResultSet.TYPE_SCROLL_SENSITIVE
The cursorcan scroll forwardsand backwards,and theresultsetis sensitiveto
changesmadeby othersto the databasethatoccurafterthe resultset was created.
Methodsin the ResultSet interfacethat involvemovingthe cursor, including:
first()
Movesthecursor to the first row
next()
Movesthecursor to the nextrow.
7. Example:
public static void main(String[] args) throwsException
{
Connection connection =getConnection();
try {
String query = "SELECT id, title FROMbooks";
PreparedStatementps= connection.prepareStatement(query);
ResultSetrs = ps.executeQuery();
while (rs.next()){
// Read valuesusing column name
String id = rs.getString("id");
String title = rs.getString("title");
System.out.printf("%s.%s n",id,title);
}
}
Q.11 List & Explainany two JSP Actions?
Ans: JSPactionsuse constructsin XML syntax to controlthe behaviorof the servletengine.You can dynamically
insert a file, reuse JavaBeanscomponents,forward theuserto another page,orgenerateHTML for the
Java plugin.
There is only onesyntax fortheAction element,as it conformsto the XMLstandard:
<jsp:action_nameattribute="value"/>
<JSP:INCLUDE>
This action lets you insert files into thepagebeing generated.
The syntax lookslike this: <jsp:includepage="relativeURL"flush="true"/>
Unlike theincludedirective, which insertsthe file atthe time the JSPpageis translated into a servlet,this
action inserts the file at the time the pageis requested
<JSP:FORWARD>
The forwardaction terminatesthe action of the currentpageand forwardstherequestto anotherresource
such as a static page,anotherJSPpage,ora Java Servlet.
The simple syntax of thisaction is asfollows:
<jsp:forward page="RelativeURL"/>
Q.12 Servlet v/s JSP
Ans: Like JSP,Servletsare also used for generating dynamicwebpages.
Servlets:
Servlets areJava programswhich supportsHTMLtagstoo.
Generally used fordeveloping businesslayerof an enterpriseapplication.
Servlets arecreated and maintained by Java developers.
JSP :
JSPprogramis a HTML codewhich supportsjava statementstoo.
Used fordeveloping presentation layerof an enterpriseapplication
Frequenly used fordesiging websitesand used for web designers.