SlideShare a Scribd company logo
1 of 7
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.
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
{
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.
 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:
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"/>
</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.
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.

More Related Content

What's hot

Java Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 BasicsJava Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 BasicsIMC Institute
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicIMC Institute
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsBG Java EE Course
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083Divyam Pateriya
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsJava Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsIMC Institute
 
Struts Introduction Course
Struts Introduction CourseStruts Introduction Course
Struts Introduction Courseguest764934
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsKaml Sah
 

What's hot (20)

Java Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 BasicsJava Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 Basics
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet Basic
 
Working with Servlets
Working with ServletsWorking with Servlets
Working with Servlets
 
Overview of JEE Technology
Overview of JEE TechnologyOverview of JEE Technology
Overview of JEE Technology
 
JSP Technology I
JSP Technology IJSP Technology I
JSP Technology I
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
Spring Framework - III
Spring Framework - IIISpring Framework - III
Spring Framework - III
 
Struts course material
Struts course materialStruts course material
Struts course material
 
Spring Framework-II
Spring Framework-IISpring Framework-II
Spring Framework-II
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsJava Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom Tags
 
Struts Introduction Course
Struts Introduction CourseStruts Introduction Course
Struts Introduction Course
 
JSP Technology II
JSP Technology IIJSP Technology II
JSP Technology II
 
Jdbc
JdbcJdbc
Jdbc
 
Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
 
Spring Framework -I
Spring Framework -ISpring Framework -I
Spring Framework -I
 
Jsf intro
Jsf introJsf intro
Jsf intro
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
Spring MVC Basics
Spring MVC BasicsSpring MVC Basics
Spring MVC Basics
 

Viewers also liked

Computer institute website(TYIT project)
Computer institute website(TYIT project)Computer institute website(TYIT project)
Computer institute website(TYIT project)Lokesh Singrol
 
HP Software Testing project (Advanced)
HP Software Testing project (Advanced)HP Software Testing project (Advanced)
HP Software Testing project (Advanced)Lokesh Singrol
 
Project black book TYIT
Project black book TYITProject black book TYIT
Project black book TYITLokesh Singrol
 
Testing project (basic)
Testing project (basic)Testing project (basic)
Testing project (basic)Lokesh Singrol
 
Top Technology product failure
Top Technology product failureTop Technology product failure
Top Technology product failureLokesh Singrol
 
Getting started with CATIA V5 Macros
Getting started with CATIA V5 MacrosGetting started with CATIA V5 Macros
Getting started with CATIA V5 MacrosEmmett Ross
 
CATIA V5 Tips and Tricks
CATIA V5 Tips and TricksCATIA V5 Tips and Tricks
CATIA V5 Tips and TricksEmmett Ross
 

Viewers also liked (12)

TY.BSc.IT Java QB U2
TY.BSc.IT Java QB U2TY.BSc.IT Java QB U2
TY.BSc.IT Java QB U2
 
Pat
PatPat
Pat
 
Pra taruna
Pra tarunaPra taruna
Pra taruna
 
Internet of Things
Internet of ThingsInternet of Things
Internet of Things
 
Sosok pilihan
Sosok pilihanSosok pilihan
Sosok pilihan
 
Computer institute website(TYIT project)
Computer institute website(TYIT project)Computer institute website(TYIT project)
Computer institute website(TYIT project)
 
HP Software Testing project (Advanced)
HP Software Testing project (Advanced)HP Software Testing project (Advanced)
HP Software Testing project (Advanced)
 
Project black book TYIT
Project black book TYITProject black book TYIT
Project black book TYIT
 
Testing project (basic)
Testing project (basic)Testing project (basic)
Testing project (basic)
 
Top Technology product failure
Top Technology product failureTop Technology product failure
Top Technology product failure
 
Getting started with CATIA V5 Macros
Getting started with CATIA V5 MacrosGetting started with CATIA V5 Macros
Getting started with CATIA V5 Macros
 
CATIA V5 Tips and Tricks
CATIA V5 Tips and TricksCATIA V5 Tips and Tricks
CATIA V5 Tips and Tricks
 

Similar to TY.BSc.IT Java QB U4

Similar to TY.BSc.IT Java QB U4 (20)

Arpita industrial trainingppt
Arpita industrial trainingpptArpita industrial trainingppt
Arpita industrial trainingppt
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overview
 
Bt0083, server side programming theory
Bt0083, server side programming theoryBt0083, server side programming theory
Bt0083, server side programming theory
 
AJppt.pptx
AJppt.pptxAJppt.pptx
AJppt.pptx
 
Online grocery store
Online grocery storeOnline grocery store
Online grocery store
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
 
WEB TECHNOLOGIES JSP
WEB TECHNOLOGIES  JSPWEB TECHNOLOGIES  JSP
WEB TECHNOLOGIES JSP
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
J2EE - Practical Overview
J2EE - Practical OverviewJ2EE - Practical Overview
J2EE - Practical Overview
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overview
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 
Jsp
JspJsp
Jsp
 
Jsp
JspJsp
Jsp
 
J2 Ee Overview
J2 Ee OverviewJ2 Ee Overview
J2 Ee Overview
 
Jsp Comparison
 Jsp Comparison Jsp Comparison
Jsp Comparison
 
DataBase Connectivity
DataBase ConnectivityDataBase Connectivity
DataBase Connectivity
 
Developing Java Web Applications
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applications
 
What’s new in Java SE, EE, ME, Embedded world & new Strategy
What’s new in Java SE, EE, ME, Embedded world & new StrategyWhat’s new in Java SE, EE, ME, Embedded world & new Strategy
What’s new in Java SE, EE, ME, Embedded world & new Strategy
 
JSP overview
JSP overviewJSP overview
JSP overview
 
Jsp
JspJsp
Jsp
 

More from Lokesh Singrol

Computer institute Website(TYIT project)
Computer institute Website(TYIT project)Computer institute Website(TYIT project)
Computer institute Website(TYIT project)Lokesh Singrol
 
behavioral model (DFD & state diagram)
behavioral model (DFD & state diagram)behavioral model (DFD & state diagram)
behavioral model (DFD & state diagram)Lokesh Singrol
 
Desktop system,clustered system,Handheld system
Desktop system,clustered system,Handheld systemDesktop system,clustered system,Handheld system
Desktop system,clustered system,Handheld systemLokesh Singrol
 

More from Lokesh Singrol (8)

MCLS 45 Lab Manual
MCLS 45 Lab ManualMCLS 45 Lab Manual
MCLS 45 Lab Manual
 
MCSL 036 (Jan 2018)
MCSL 036 (Jan 2018)MCSL 036 (Jan 2018)
MCSL 036 (Jan 2018)
 
Computer institute Website(TYIT project)
Computer institute Website(TYIT project)Computer institute Website(TYIT project)
Computer institute Website(TYIT project)
 
Trees and graphs
Trees and graphsTrees and graphs
Trees and graphs
 
behavioral model (DFD & state diagram)
behavioral model (DFD & state diagram)behavioral model (DFD & state diagram)
behavioral model (DFD & state diagram)
 
Desktop system,clustered system,Handheld system
Desktop system,clustered system,Handheld systemDesktop system,clustered system,Handheld system
Desktop system,clustered system,Handheld system
 
Raster Scan display
Raster Scan displayRaster Scan display
Raster Scan display
 
Flash memory
Flash memoryFlash memory
Flash memory
 

Recently uploaded

How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Economic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesEconomic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesSHIVANANDaRV
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111GangaMaiya1
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningMarc Dusseiller Dusjagr
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfstareducators107
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSAnaAcapella
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 

Recently uploaded (20)

VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Economic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesEconomic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food Additives
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 

TY.BSc.IT Java QB U4

  • 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.