TY.BSc.IT Java QB U4

Lokesh Singrol
Lokesh SingrolSoftware Engineer em BizOneSoft Global Solution Pvt. Ltd.

Question Bank for Ty's student. (Java Unit-4)

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.

Recomendados

TY.BSc.IT Java QB U3 por
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3Lokesh Singrol
140 visualizações8 slides
TY.BSc.IT Java QB U5&6 por
TY.BSc.IT Java QB U5&6TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6Lokesh Singrol
362 visualizações20 slides
TY.BSc.IT Java QB U5 por
TY.BSc.IT Java QB U5TY.BSc.IT Java QB U5
TY.BSc.IT Java QB U5Lokesh Singrol
166 visualizações9 slides
TY.BSc.IT Java QB U6 por
TY.BSc.IT Java QB U6TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6Lokesh Singrol
370 visualizações9 slides
TY.BSc.IT Java QB U1 por
TY.BSc.IT Java QB U1TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1Lokesh Singrol
156 visualizações8 slides
Java Web Programming [6/9] : MVC por
Java Web Programming [6/9] : MVCJava Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCIMC Institute
1.5K visualizações23 slides

Mais conteúdo relacionado

Mais procurados

Java Web Programming [7/9] : Struts2 Basics por
Java Web Programming [7/9] : Struts2 BasicsJava Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 BasicsIMC Institute
658 visualizações19 slides
Java Web Programming [2/9] : Servlet Basic por
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicIMC Institute
1.7K visualizações33 slides
Working with Servlets por
Working with ServletsWorking with Servlets
Working with ServletsPeople Strategists
744 visualizações30 slides
Overview of JEE Technology por
Overview of JEE TechnologyOverview of JEE Technology
Overview of JEE TechnologyPeople Strategists
1.3K visualizações49 slides
JSP Technology I por
JSP Technology IJSP Technology I
JSP Technology IPeople Strategists
1.7K visualizações42 slides
Java Server Faces (JSF) - Basics por
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsBG Java EE Course
12.3K visualizações63 slides

Mais procurados(20)

Java Web Programming [7/9] : Struts2 Basics por IMC Institute
Java Web Programming [7/9] : Struts2 BasicsJava Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 Basics
IMC Institute658 visualizações
Java Web Programming [2/9] : Servlet Basic por IMC Institute
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet Basic
IMC Institute1.7K visualizações
Working with Servlets por People Strategists
Working with ServletsWorking with Servlets
Working with Servlets
People Strategists744 visualizações
Overview of JEE Technology por People Strategists
Overview of JEE TechnologyOverview of JEE Technology
Overview of JEE Technology
People Strategists1.3K visualizações
JSP Technology I por People Strategists
JSP Technology IJSP Technology I
JSP Technology I
People Strategists1.7K visualizações
Java Server Faces (JSF) - Basics por BG Java EE Course
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
BG Java EE Course 12.3K visualizações
Spring Framework - III por People Strategists
Spring Framework - IIISpring Framework - III
Spring Framework - III
People Strategists1.2K visualizações
Spring Framework-II por People Strategists
Spring Framework-IISpring Framework-II
Spring Framework-II
People Strategists1.3K visualizações
Server side programming bt0083 por Divyam Pateriya
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
Divyam Pateriya234 visualizações
Java Spring MVC Framework with AngularJS by Google and HTML5 por Tuna Tore
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
Tuna Tore4K visualizações
Java Web Programming [5/9] : EL, JSTL and Custom Tags por IMC Institute
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
IMC Institute1.9K visualizações
Struts Introduction Course por guest764934
Struts Introduction CourseStruts Introduction Course
Struts Introduction Course
guest7649341.7K visualizações
JSP Technology II por People Strategists
JSP Technology IIJSP Technology II
JSP Technology II
People Strategists897 visualizações
Exploring Maven SVN GIT por People Strategists
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
People Strategists1.5K visualizações
Spring Framework -I por People Strategists
Spring Framework -ISpring Framework -I
Spring Framework -I
People Strategists1.5K visualizações
Jsf intro por vantinhkhuc
Jsf introJsf intro
Jsf intro
vantinhkhuc918 visualizações
J2EE - JSP-Servlet- Container - Components por Kaml Sah
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
Kaml Sah3.8K visualizações
Spring MVC Basics por Bozhidar Bozhanov
Spring MVC BasicsSpring MVC Basics
Spring MVC Basics
Bozhidar Bozhanov12.4K visualizações

Destaque

TY.BSc.IT Java QB U2 por
TY.BSc.IT Java QB U2TY.BSc.IT Java QB U2
TY.BSc.IT Java QB U2Lokesh Singrol
165 visualizações9 slides
Pat por
PatPat
PatFred_macha
150 visualizações21 slides
Pra taruna por
Pra tarunaPra taruna
Pra tarunaAndre Wirasasmita
439 visualizações10 slides
Internet of Things por
Internet of ThingsInternet of Things
Internet of ThingsLokesh Singrol
104 visualizações12 slides
Sosok pilihan por
Sosok pilihanSosok pilihan
Sosok pilihanAndre Wirasasmita
2.8K visualizações18 slides
Computer institute website(TYIT project) por
Computer institute website(TYIT project)Computer institute website(TYIT project)
Computer institute website(TYIT project)Lokesh Singrol
582 visualizações18 slides

Destaque(12)

TY.BSc.IT Java QB U2 por Lokesh Singrol
TY.BSc.IT Java QB U2TY.BSc.IT Java QB U2
TY.BSc.IT Java QB U2
Lokesh Singrol165 visualizações
Pat por Fred_macha
PatPat
Pat
Fred_macha150 visualizações
Internet of Things por Lokesh Singrol
Internet of ThingsInternet of Things
Internet of Things
Lokesh Singrol104 visualizações
Sosok pilihan por Andre Wirasasmita
Sosok pilihanSosok pilihan
Sosok pilihan
Andre Wirasasmita2.8K visualizações
Computer institute website(TYIT project) por Lokesh Singrol
Computer institute website(TYIT project)Computer institute website(TYIT project)
Computer institute website(TYIT project)
Lokesh Singrol582 visualizações
HP Software Testing project (Advanced) por Lokesh Singrol
HP Software Testing project (Advanced)HP Software Testing project (Advanced)
HP Software Testing project (Advanced)
Lokesh Singrol520 visualizações
Project black book TYIT por Lokesh Singrol
Project black book TYITProject black book TYIT
Project black book TYIT
Lokesh Singrol49.7K visualizações
Testing project (basic) por Lokesh Singrol
Testing project (basic)Testing project (basic)
Testing project (basic)
Lokesh Singrol198 visualizações
Top Technology product failure por Lokesh Singrol
Top Technology product failureTop Technology product failure
Top Technology product failure
Lokesh Singrol2.7K visualizações
Getting started with CATIA V5 Macros por Emmett Ross
Getting started with CATIA V5 MacrosGetting started with CATIA V5 Macros
Getting started with CATIA V5 Macros
Emmett Ross26.1K visualizações
CATIA V5 Tips and Tricks por Emmett Ross
CATIA V5 Tips and TricksCATIA V5 Tips and Tricks
CATIA V5 Tips and Tricks
Emmett Ross38.7K visualizações

Similar a TY.BSc.IT Java QB U4

Arpita industrial trainingppt por
Arpita industrial trainingpptArpita industrial trainingppt
Arpita industrial trainingpptARPITA SRIVASTAVA
368 visualizações32 slides
Jsf2 overview por
Jsf2 overviewJsf2 overview
Jsf2 overviewsohan1234
633 visualizações32 slides
Bt0083, server side programming theory por
Bt0083, server side programming theoryBt0083, server side programming theory
Bt0083, server side programming theorysmumbahelp
251 visualizações4 slides
AJppt.pptx por
AJppt.pptxAJppt.pptx
AJppt.pptxSachinSingh217687
12 visualizações68 slides
Online grocery store por
Online grocery storeOnline grocery store
Online grocery storeKavita Sharma
38.3K visualizações35 slides
JAVA SERVER PAGES por
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGESKalpana T
72 visualizações28 slides

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

Arpita industrial trainingppt por ARPITA SRIVASTAVA
Arpita industrial trainingpptArpita industrial trainingppt
Arpita industrial trainingppt
ARPITA SRIVASTAVA368 visualizações
Jsf2 overview por sohan1234
Jsf2 overviewJsf2 overview
Jsf2 overview
sohan1234633 visualizações
Bt0083, server side programming theory por smumbahelp
Bt0083, server side programming theoryBt0083, server side programming theory
Bt0083, server side programming theory
smumbahelp251 visualizações
Online grocery store por Kavita Sharma
Online grocery storeOnline grocery store
Online grocery store
Kavita Sharma38.3K visualizações
JAVA SERVER PAGES por Kalpana T
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
Kalpana T72 visualizações
Advance Java Topics (J2EE) por slire
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
slire35.1K visualizações
J2EE - Practical Overview por Svetlin Nakov
J2EE - Practical OverviewJ2EE - Practical Overview
J2EE - Practical Overview
Svetlin Nakov1.2K visualizações
Jsf2 overview por musaibasrar
Jsf2 overviewJsf2 overview
Jsf2 overview
musaibasrar123 visualizações
Jsp and jstl por vishal choudhary
Jsp and jstlJsp and jstl
Jsp and jstl
vishal choudhary77 visualizações
Jsp por Rahul Goyal
JspJsp
Jsp
Rahul Goyal244 visualizações
Jsp por Rahul Goyal
JspJsp
Jsp
Rahul Goyal188 visualizações
J2 Ee Overview por Atul Shridhar
J2 Ee OverviewJ2 Ee Overview
J2 Ee Overview
Atul Shridhar2.5K visualizações
Jsp Comparison por Venky Sadasivam
 Jsp Comparison Jsp Comparison
Jsp Comparison
Venky Sadasivam3.4K visualizações
DataBase Connectivity por Akankshaji
DataBase ConnectivityDataBase Connectivity
DataBase Connectivity
Akankshaji2.2K visualizações
Developing Java Web Applications por hchen1
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applications
hchen116.4K visualizações
What’s new in Java SE, EE, ME, Embedded world & new Strategy por Mohamed Taman
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
Mohamed Taman2.7K visualizações
Jsp por DEEPAK SHEOGAN
JspJsp
Jsp
DEEPAK SHEOGAN179 visualizações

Mais de Lokesh Singrol

MCLS 45 Lab Manual por
MCLS 45 Lab ManualMCLS 45 Lab Manual
MCLS 45 Lab ManualLokesh Singrol
460 visualizações40 slides
MCSL 036 (Jan 2018) por
MCSL 036 (Jan 2018)MCSL 036 (Jan 2018)
MCSL 036 (Jan 2018)Lokesh Singrol
92 visualizações53 slides
Computer institute Website(TYIT project) por
Computer institute Website(TYIT project)Computer institute Website(TYIT project)
Computer institute Website(TYIT project)Lokesh Singrol
1.4K visualizações17 slides
Trees and graphs por
Trees and graphsTrees and graphs
Trees and graphsLokesh Singrol
6.4K visualizações23 slides
behavioral model (DFD & state diagram) por
behavioral model (DFD & state diagram)behavioral model (DFD & state diagram)
behavioral model (DFD & state diagram)Lokesh Singrol
2.6K visualizações16 slides
Desktop system,clustered system,Handheld system por
Desktop system,clustered system,Handheld systemDesktop system,clustered system,Handheld system
Desktop system,clustered system,Handheld systemLokesh Singrol
2.7K visualizações13 slides

Mais de Lokesh Singrol(8)

MCLS 45 Lab Manual por Lokesh Singrol
MCLS 45 Lab ManualMCLS 45 Lab Manual
MCLS 45 Lab Manual
Lokesh Singrol460 visualizações
MCSL 036 (Jan 2018) por Lokesh Singrol
MCSL 036 (Jan 2018)MCSL 036 (Jan 2018)
MCSL 036 (Jan 2018)
Lokesh Singrol92 visualizações
Computer institute Website(TYIT project) por Lokesh Singrol
Computer institute Website(TYIT project)Computer institute Website(TYIT project)
Computer institute Website(TYIT project)
Lokesh Singrol1.4K visualizações
Trees and graphs por Lokesh Singrol
Trees and graphsTrees and graphs
Trees and graphs
Lokesh Singrol6.4K visualizações
behavioral model (DFD & state diagram) por Lokesh Singrol
behavioral model (DFD & state diagram)behavioral model (DFD & state diagram)
behavioral model (DFD & state diagram)
Lokesh Singrol2.6K visualizações
Desktop system,clustered system,Handheld system por Lokesh Singrol
Desktop system,clustered system,Handheld systemDesktop system,clustered system,Handheld system
Desktop system,clustered system,Handheld system
Lokesh Singrol2.7K visualizações
Raster Scan display por Lokesh Singrol
Raster Scan displayRaster Scan display
Raster Scan display
Lokesh Singrol8.3K visualizações
Flash memory por Lokesh Singrol
Flash memoryFlash memory
Flash memory
Lokesh Singrol1.3K visualizações

Último

CWP_23995_2013_17_11_2023_FINAL_ORDER.pdf por
CWP_23995_2013_17_11_2023_FINAL_ORDER.pdfCWP_23995_2013_17_11_2023_FINAL_ORDER.pdf
CWP_23995_2013_17_11_2023_FINAL_ORDER.pdfSukhwinderSingh895865
527 visualizações6 slides
Psychology KS4 por
Psychology KS4Psychology KS4
Psychology KS4WestHatch
84 visualizações4 slides
Psychology KS5 por
Psychology KS5Psychology KS5
Psychology KS5WestHatch
93 visualizações5 slides
Computer Introduction-Lecture06 por
Computer Introduction-Lecture06Computer Introduction-Lecture06
Computer Introduction-Lecture06Dr. Mazin Mohamed alkathiri
89 visualizações12 slides
REPRESENTATION - GAUNTLET.pptx por
REPRESENTATION - GAUNTLET.pptxREPRESENTATION - GAUNTLET.pptx
REPRESENTATION - GAUNTLET.pptxiammrhaywood
100 visualizações26 slides
When Sex Gets Complicated: Porn, Affairs, & Cybersex por
When Sex Gets Complicated: Porn, Affairs, & CybersexWhen Sex Gets Complicated: Porn, Affairs, & Cybersex
When Sex Gets Complicated: Porn, Affairs, & CybersexMarlene Maheu
67 visualizações73 slides

Último(20)

CWP_23995_2013_17_11_2023_FINAL_ORDER.pdf por SukhwinderSingh895865
CWP_23995_2013_17_11_2023_FINAL_ORDER.pdfCWP_23995_2013_17_11_2023_FINAL_ORDER.pdf
CWP_23995_2013_17_11_2023_FINAL_ORDER.pdf
SukhwinderSingh895865527 visualizações
Psychology KS4 por WestHatch
Psychology KS4Psychology KS4
Psychology KS4
WestHatch84 visualizações
Psychology KS5 por WestHatch
Psychology KS5Psychology KS5
Psychology KS5
WestHatch93 visualizações
REPRESENTATION - GAUNTLET.pptx por iammrhaywood
REPRESENTATION - GAUNTLET.pptxREPRESENTATION - GAUNTLET.pptx
REPRESENTATION - GAUNTLET.pptx
iammrhaywood100 visualizações
When Sex Gets Complicated: Porn, Affairs, & Cybersex por Marlene Maheu
When Sex Gets Complicated: Porn, Affairs, & CybersexWhen Sex Gets Complicated: Porn, Affairs, & Cybersex
When Sex Gets Complicated: Porn, Affairs, & Cybersex
Marlene Maheu67 visualizações
The Open Access Community Framework (OACF) 2023 (1).pptx por Jisc
The Open Access Community Framework (OACF) 2023 (1).pptxThe Open Access Community Framework (OACF) 2023 (1).pptx
The Open Access Community Framework (OACF) 2023 (1).pptx
Jisc110 visualizações
Scope of Biochemistry.pptx por shoba shoba
Scope of Biochemistry.pptxScope of Biochemistry.pptx
Scope of Biochemistry.pptx
shoba shoba133 visualizações
ANATOMY AND PHYSIOLOGY UNIT 1 { PART-1} por DR .PALLAVI PATHANIA
ANATOMY AND PHYSIOLOGY UNIT 1 { PART-1}ANATOMY AND PHYSIOLOGY UNIT 1 { PART-1}
ANATOMY AND PHYSIOLOGY UNIT 1 { PART-1}
DR .PALLAVI PATHANIA249 visualizações
MIXING OF PHARMACEUTICALS.pptx por Anupkumar Sharma
MIXING OF PHARMACEUTICALS.pptxMIXING OF PHARMACEUTICALS.pptx
MIXING OF PHARMACEUTICALS.pptx
Anupkumar Sharma77 visualizações
MercerJesse2.1Doc.pdf por jessemercerail
MercerJesse2.1Doc.pdfMercerJesse2.1Doc.pdf
MercerJesse2.1Doc.pdf
jessemercerail169 visualizações
Class 10 English lesson plans por TARIQ KHAN
Class 10 English  lesson plansClass 10 English  lesson plans
Class 10 English lesson plans
TARIQ KHAN288 visualizações
Education and Diversity.pptx por DrHafizKosar
Education and Diversity.pptxEducation and Diversity.pptx
Education and Diversity.pptx
DrHafizKosar173 visualizações
UWP OA Week Presentation (1).pptx por Jisc
UWP OA Week Presentation (1).pptxUWP OA Week Presentation (1).pptx
UWP OA Week Presentation (1).pptx
Jisc88 visualizações
Drama KS5 Breakdown por WestHatch
Drama KS5 BreakdownDrama KS5 Breakdown
Drama KS5 Breakdown
WestHatch79 visualizações
Use of Probiotics in Aquaculture.pptx por AKSHAY MANDAL
Use of Probiotics in Aquaculture.pptxUse of Probiotics in Aquaculture.pptx
Use of Probiotics in Aquaculture.pptx
AKSHAY MANDAL100 visualizações
Narration ppt.pptx por TARIQ KHAN
Narration  ppt.pptxNarration  ppt.pptx
Narration ppt.pptx
TARIQ KHAN135 visualizações
Java Simplified: Understanding Programming Basics por Akshaj Vadakkath Joshy
Java Simplified: Understanding Programming BasicsJava Simplified: Understanding Programming Basics
Java Simplified: Understanding Programming Basics
Akshaj Vadakkath Joshy295 visualizações
AI Tools for Business and Startups por Svetlin Nakov
AI Tools for Business and StartupsAI Tools for Business and Startups
AI Tools for Business and Startups
Svetlin Nakov107 visualizações

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.