Q1) What is JSP? Explain its role in the development of web sites. Ans: JSP is an existing new technology that provides powerful and efficient creation of dynamic contents. It allows static web content to be mixed with java code. It is a technology using server-side scripting that is actually translated into servlets and compiled before they are run. Role of JSP in the development of websites: In todays environment dynamic content is critical to the success of any web site. There are a number of technologies available for incorporating the dynamic contents In a site. But most of these technologies hhave some problem. Servlets offer several improvements over other server extension methods. But still suffer from a lack of presentation and business logic separation. So the java community worked to define a standard for a servlet based server pages environment. JSP separates the presentation layer(i.e. web interface logic) from the business logic(i.e. back end content generation logic) so the web designer and web developers can work on the same web page without getting in each others way. . Q2) Explain various scripting elements used in JSP. OR Q3) What is JSP? Explain Scriptlets in JSP.
Ans: JSP is an exciting new technology that provides powerful and efficient creation of dynamic contents. It is a presentation layer technology that allow static web content to be mixed with java code.JSP allows the use of standard HTML, but adds the power and flexiblity of the java programming language. JSP does not modify static data. JSP is an extremly powerful choice for web devlopmen. It is a technology using server side scripting that is actually translataed into servlets and compiled before they are run. JSP uses the <% tag to note the start of JSP section, and the %> tag to note the end of a JSP section. JSP will interpret anything within these tags as a special section.These tag is known as scriptlets. Scripting Elements: we will understand different types of tags or scripting elements used in JSP. A JSP page contains HTML.( or other text based format such as XML) mixed with elements of the JSP syntax. There are five basic types of elements, as well as a special format for comments. These are 1. Scriptlets: The Scriptlet element allows java Code to be embedded directly into a JSP page. JSP Synatx: <% code %> XML Synatax: : <jsp:scriptlet>code</jsp:scriptlet> Scriptlets are the most common JSP syntax elements. As you have studied above, a scriptlet is a portion of regular java code embedded in the JSP content within
PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 2
< %....%> tags. The java code in scriptlets is executed when the user ask for the page. Scriptlets can be used to do absolutely anything the java language supports, but some of their more common tasks are: a. Executing logic on the server side; for example accessing a database. b. Implementing conditional HTML by posing a condition on the execution of portion of the page. c. Looping over JSP fragments, enabling operations such as populating a table with a dynamic content.
Example: <html> <head> <title>Scriptlet </title> </head> <body> <h2> <%@ page import="java.util.*"%> <% Date d = new Date(); out.println("Today is : "+d); %> </h2> </body> </html>
2. Expression: An expression element is a java language expression whose value is evaluated and returned as string to the page. JSP Synatx: <% =code %>
XML Synatax: : <jsp:expression>code</jsp:expression> Printing the output of a java fragment is one of the most common tasks utilized in JSP pages. For this purpose we can use the out.println() method. But having several out.println() method tends to be cumbersome. Realizing this author of the JSP specification created the expression elements. The expression begins with the standard JSP start tag followed by an equals sign (< %=).
Example: <Html> <Title> Current Date</title> </head> <body color=#FFFFFF> The current date is <%=new java.util.Date()%> //Expression element </body> </Html> PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 3
3. Declaration: A declaration element is used to declare method and variables that are initialized with the page. JSP Synatx: <%! code %> XML Synatax: : < jsp:declaration>code</jsp:declaration>
The third type of Scripting element is the Declaration element. The purpose of a declaration element is to initialize variable and method and make them available to other declaration, Scriptlets, and expression. Variables and methods created within declaration elements are effectively global. The syntax of the declaration element begin with the standard JSP open tag followed by an exclamation point (< %!). The declaration element must be a complex java statement. it ends with a semicolon, just as the scriptlet element does.
Example: <%! Private ClasJsp Obj; Public void jspInit() //methods and variable declaration {
} public void jspDestroy() { } %>
4. Directives: Directive elements contain global information that is applicable to the whole page. JSP Synatx: <%@ code %> Example: <%@ page import="java.util.*"%>
5. Action: Action elements provide information for the translation phase of the JSP page. And consist of a set of standard, built in methods. Custom action can also be created in the form of custom tags. This is new feature of the JSP 1.1 specification
The first three elements -----Scriptlets, Expression, and Declaration ----are collectively called scripting elements.
PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 4
Q4) What are various implicit objects used with JSP? OR Q5) What are predefined variable in JSP? Ans: PREDEFINED VARIABLES: To simplify code in JSP expression and scriptlets, Servlet also creates several objects to be used by the JSP engine; these are sometimes called implicit objects (or predefined variables). Many of these objects are called directly without being explicitly declared. These objects are: 1. The out Object 2. The request Object 3. The response Object 4. The page Context Object 5. The session Object 6. The config Object 7. The application Object 8. The page Object 9. The exception Object
The out Object: The major function of JSP is to describe data being sent to an output stream in response to a client request. This output stream is exposed to the JSP author through the implicit out object. The out object is an instantiation of a javax.servlet.jsp.JspWriter object. The Request Object: Each time a client request a page of JSP engine creates a new object to represent the request. This new object is an instance of javax.serblet.http.HttpServletRequest and is given parameters describing the request.This object is exposed to the JSP author through the request object. The Response Object: Just as the server creates the request object it also creates an object to represent the response to the client. the object is an instance of javax.servlet.http.HttpServletResponse and is exposed to the JSP author as the response object. The page Context Object: The Page Context Object is used to represent the entire JSP page. It is intended as a means to access information about the page while avoiding most of the implementation details.
The Application Object The application object is direct wrapper around the ServletContext Object for the generated servlet. It has the same methods and interfaces that the ServletContext object does in programming Java Servlets. This object is a representation of the JSP page through its entire lifecycle. The Config Object: The config object is an instantiation of javax.servlet.ServletConfig.this object is a direct wrapper around the ServletConfig object for the generated servlet. PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 5
The Page Object: This object is an actual reference to the instance of the page. It can be thought of as an object that represents the entire JSP page. The Exception Object: The error handling method utilizes this object. It is available only when the previous JSP page throws an uncaught exception and the <%@pageerrorPage=..%> tag was used.
The Session Object: A session of web browsing is a period of time during which particular person sitting a particular machine, view a number of different page of web and then call it quit. Session are used to store information between http request for a particular user or single user when user starts browsing a web site all the information for that particular users has to be stored.
Q6) What do you understand by JSP Action? OR Q7) what is the different between <jsp:include page=> and <%@ include file=.>? OR Q8) Write a note on jsp:fallback and jsp:param Element.
Ans: JSP has three main capabilities for including external piece into a jsp document. 1. JSP:include action This include generated a page, not JSP code. It can not access environment of main page in include code. Jsp:include action includes files at the time the client request and thus does not require you to update the main file when an included file changes. Jsp:include element has two required attributes Page: It refers to a relative URL referecing the file to be included Flush: This must have the value true. Syntax: <jsp:include page=relative URL flush=true/>
2. Include directive Include directives include dynamic page. i.e. JSP code, it is powerful, but poses maintenance challenges. You can include a file with JSP at the page translation time. In this case file will be included in the main JSP document at the time the document is translated into a servlet. In include directive if the include file changes, all the JSP files that use it need to be updated. Syntax: <%@ include file=relative URL %>
3. Jsp:plugin action This inserts applet into JSP that use the java plugin. It increase client side role in dialog.
PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 6
Jsp:plugin has four attributes : type,code,width and height. You supply value of applet of type attribute and use the other three attribute in exactly same way as with the APPLET element, with two exceptions, i.e. attribute names are case sensitive and single or double quotes are always required around the attribute value. Syntax: <APPLET CODE=MYApplet.class WIDTH=400 HEIGHT=200> </APPLET> You could replace this code with <jsp:plugin type=applet code=MyApplet.class width=400 height=200> </jsp:plugin>
The jsp:param and jsp:params Elements: The jsp:param element is used with jsp:plugin in a manner similar to the way that PARAM is used with APPLET. There are two main differences between jsp:param and param with applet. First jsp:param follows XML syntax, attribute names must be lower case and values must be enclosed single or double quotes. Second all jsp:param entries must be enclosed within a jsp:params element. Syntax: <APPLET CODE=MYApplet.class WIDTH=400 HEIGHT=200> <PARAM NAME=PARAM1 VALUE=VALUE1> </APPLET> You could replace this code with <jsp:plugin type=applet code=MyApplet.class width=400 height=200> <jsp:params> <jsp:param name=PARAM1 value=VALUE1/> </jsp:params></jsp:plugin> Jsp:fallback Element: The jsp:fallback element provides alternative text to browsers that do not support OBJECT or EMBED. You use this element in almost the same way as you would use alternative text placed within an APPLET element. Synatx: <APPLET CODE=MYApplet.class WIDTH=400 HEIGHT=200> <B>Error: this example requires Java</B> </APPLET> You could replace this code with <jsp:plugin type=applet code=MyApplet.class width=400 height=200> <jsp:fallback> <B>Error: this example requires Java</B> </jsp:fallback> </jsp:plugin>
..
PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 7
Q9) What is the different between <jsp:forward page=> and response.sendRedirect(url)?OR Q10) What is the different between Forwarding Request from JSP and Forwarding request from Servlet?
Ans: Forwarding Requests from JSP pages: The most common request forwarding scenario is that the request first comes to a servlet and the servlet forwards the request to a JSP page. The reason is a servlet usually handles the original request and destination page is usually JSP document. But it is also possible the destination page to be servlet and request forward from JSP page to servlet or elsewhere.for this purpose JSP use jsp:forward action. Syntax: <jsp:forward page=relative URL/> <% String destination; If(MATH.random()>.5) { Destination=/example/page1.jsp} Else{ Destination=/example/page2.jsp} %> <jsp:forward page=<%=destination%>/>
Forwarding Requests from Servlet: The key to letting servlets forward requests or include external content is to use a requestDispatcher. You obtain a RequestDispatcher by calling the getRequestDispatcher method of ServletContext, suuplying a URL relative to the server root. Once you have RequestDispatcher, you use forward to completely transfer control to the associated URL and use include to output the associated URLs content. In both case you supply the HttpServletResponse and HttpServletRequest as arguments. HttpServletResponse class also provides sendRedirect() method to forward request into another page. Syntax: String url=/examples/jsp/page1.jsp RequestDispatcher d=getServletContext().getRequestDispatcher(url); d.forward(request,response);
OR Response.sendRedirect(Relative URL);
PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 8
Q11) Give the names of JSP directive. Briefly explain all attributes of JSP page directive. Ans: Directives: Directive elements contain global information that is applicable to the whole page. JSP Synatx: <%@ code %> Types of directive tag: 1. Include directive Include directives include dynamic page. i.e. JSP code, it is powerful, but poses maintenance challenges. You can include a file with JSP at the page translation time. In this case file will be included in the main JSP document at the time the document is translated into a servlet. In include directive if the include file changes, all the JSP files that use it need to be updated. Syntax: <%@ include file=relative URL %>
2. Page directive The he page directive applies to an entire JSP file and any of its static include files, which together are called a translation unit. Syntax: <%@ page attributeName="values" %> <%@ page import=java.util.* %> 3. Taglib directive Once you have a tag handler implementation and a TLD. You are ready to write a JSP file that makes use of the tag. Somewhere in the JSP page you need to place the taglib directive. Syntax: <%@ taglib uri=. Prefix= %> The required uri attribute can be either an absolute or relative URL referring to a TLD file. The required prefix attribute specifies a prefix to use in front of any tag name defined in the TLD of this taglib declaration The list of the JSP page directive tag attributes is: Language, extends, import, session, info, errorPage, contentType, buffer, autoFlush, isThreadSafe IsErrorPage. . Q12) What is importance of JavaBeans in JSP? Explain important JSP actions to build and manipulate JavaBean component along with all its attributes. OR Q13) What is JavaBeans? Explain elements of JavaBean. Ans: JavaBeans are used to inserting dynamic content in JSP pages. Develop separate utility classes structured as beans. Use jsp:useBean, jsp:getProperty, and jsp:setProperty to invoke the code.
PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 9
Many types of benefit provide a separate Java classes instead of embedding large amounts of code directly in JSP pages. Separate classes are easier to write, compile, test, debug, and reuse. What do beans provide that other classes do not? Beans are merely regular java classes that follow some simple conventions defined by the JavaBeans. Beans extend no particular class. Beans do not use package. Beans do not use particular interface. Using beans, other program can automatically discover information about classes. JavaBeans provides three advantages: 1. No Java syntax: the programmer can manipulate java object using only XML syntax: no parentheses, semicolons, or curly braces by using beans. 2. Simpler object sharing: when you use the JSP bean, you can much more easily share objects among multiple pages or between requests. 3. Convenient correspondence between request parameters and object properties: the jsp bean constructs simplify the process of reading request parameters, converting from strings and putting the results inside objects. Beans class has three simple points : 1. A bean class must have a zero argument(default constructor. 2. A bean class should have no public instance variable. 3. Persistence values should be accessed through methods called getxx and setxx. Using Beans in JSP page: You use three main constructs to build and manipulate JavaBeans components in JSP pages: jsp:useBean. In the simplest case, this element builds a new bean it is normally used as follows. <jsp:useBean id=beanName class=package.class/> jSP:getproperty. This element reads and outputs the value of a bean property. This elements used as follows. <jsp:getproperty name=beanName property=propertyName/> Jsp:setproperty. This element modifies a bean property. It is used as follows. <jsp:setproperty name=beanName property=propertyName value=propertyValue/> .. Q14) Why MVC framework is required to build complex applications? Briefly explain the role of RequestDispatcher in MVC. OR Q15) What is MVC? Explain implementing MVC with ReqquestDispatcher.
Ans: MVC is used to inserting dynamic content in JSP pages. The servlet handles to original request , look up data, and store results in beans. Then servlet forward this beans to jsp page to present result. Jsp page uses beans. MVC Architecture or Approach: MVC (MODEL VIEW CONTROLLER) or (MODEL 2 ARCHITECTURE) The original request is handled by a servlet. The servlet invokes business logic and data access code and creates beans to store the data / to represent the results. So the bean is model. Then the servlet decides which JSP page is appropriate to present those particular result and forward request to jsp page. So the JSP page is the view. The servlet decides what business logic code applies and which JSP page should present the results. So the servlet is the controller. PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 10
MVC Frameworks: the key motivation behind the MVC approach is the desire to separate the code that creates and manipulates the data from the code that presents the data.the basic tools needed to implement this presentation layer separation are standard in the servlet API. However in very complex applications a more elaborate MVC framework is sometimes beneficial. The most popular of these frameworks is Apache Struts. Implementing MVC with RequestDispatcher: the most important point about MVC is the idea of separating the business logic and data access layers from the presentation layer. The syntax is quite simple. Here following steps are include. 1. Defines beans to represent the data: as you know beans are java object. First step define beans to represent the results that will be presented to the user. 2. Use a servlet to handle request: the servlet reads request parameters. 3. Populate the beans: the servlet invokes business logic or data access code to obtain the results. The results are placed in the beans. Example: Storing data into session: ValueObject value=new ValueObject(.); HttpSession session=request.getSession(); Session.setAttribute(key,value); Next the servlet would forward to a jsp page that uses the following to retrieve the data. <jsp:useBean id=key type=package.ValueObject scope=session/> Storing data into request ValueObject value=new ValueObject(.); request.setAttribute(key,value); <jsp:useBean id=key type=package.ValueObject scope=request/> Storing data into servletcontext ValueObject value=new ValueObject(.); getServletContext()..setAttribute(key,value); <jsp:useBean id=key type=package.ValueObject scope=application/>
4. Store the bean in the request,session or servlet context: the servlet calls setAttribute on the request, session or servlet context objects to store a reference to the beans that represent the results of the request. 5. Forward the request to a JSP page: the servlet determines which JSP page is appropriate to the situation and uses the forward method of RequestDispatcher to transfer control to that page. Example: RequestDispatcher d=request.getRequestDispatcher(address); d.forward(request,response); 6. Extract the data from the beans: the jsp page accesses beans with jsp:useBean and then use jsp:getproperty to output the bean properties. The jsp pages does not create or modify the bean. It merely extracts and displays data that the servlet created. Example: <jsp:useBean id=key type=package.ClassName scope=session/> <jsp:getproperty name=key propert=propertyName/>
.
PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 11
Q16) What is the JSP Expression Language? Explain elements supported by EL. OR Q17) What is the Scoped Variable? How to EL access Scoped Variables? OR Q18) What is Expression Language? Explain operator of Expression Language. Ans: Use the JSP Expression Language(JSP EL): The one inconvenient part about this approach is the presenting the results in the JSP page. You normally use jsp:useBean and jsp:getproperty but these elements only supports access to simple bean property. If the property is a collection of another bean or subproperty requires you to use complex java syntax. The jsp 2.0 expression language lets you simplify the presentation layer by replacing hard to maintain java scripting elements or jsp:useBean and jsp:getproperty elements with short and readable entries of the following form. ${expression} JSP EL use shorthand syntax to access and output object properties. Usually used in conjuction with beans and MVC. The expression language supports the following capabilities. 1. Concise access to stored object: To output scoped variable named saleItem, you use ${saleItem}. 2. Shorthand notation for bean properties: To output the companyName property of scoped variable company. You use ${company.companyName}. To access the firstname property of the president property of scoped variable named company. You use ${company.president.firstname}. 3. Simple access to collection elements: To acces an element of an arrayt, List or Map. You use ${variable[index or key]}. 4. Succinct access to request parameters, cookies and other request data: To access the standard types of request data, you can use on of several predefined implicit objects. 5. A small but useful set of simple operators: To manipulate objects within EL expression, you can use any of several arithmetic,relational,logic or empty testing operators. 6. Conditional output: To choose among output option you do not have to resort to java scripting elements, instead you can use ${test ? option1 : option2}. 7. Automatic type conversion:The expression language removes the need for most typecast and for much of the code that parses strings as numbers. 8. Empty values instead of error messages: In most cases, missing values or NullPointerExceptions result in empty strings not thrown exceptions.
Accessing Scoped Variables: the servlet invoke code that creates the data then uses RequestDispatcher.forward or response.sendRedirect to transfer control to the appropriate JSP page. The JSP page to access the data the servlet needs to use setAttribute to store the data in one of the standard locations: the HttpSession,HttpServletRequest and ServletContext. The objects in these locations are known as Scoped Variables and the expression language has a quick and easy way to access them. You can also have scoped variables stored in the PageContext object but this is much less useful because the servlet and the JSP page do not share PageContext objects. To output a scoped variable you simply use its anme in an expression language element. For example, ${name} is equivalent <%= pageContext.findAttribute(name) %> is equivalent <jsp:useBean id=name type=package.class scope= > <%= name %> PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 12
Using Expression Language Operators: Use the expression language operators for simple tasks oriented toward presentation logic(deciding how to present the data). Avoid using the operators for business logic(creating and processing the data). Instead put business logic in regular java classes and invoke the code from the servlet that starts the MVC process. The following types of operators are available. 1. Arithmetic Operators: +, -,*,/ and div % and mod 2. Relational operators == and eq != and ne < and lt, > and gt, <= and le, >= and ge 3. Logical operators &&,and,||,ot,!,not 4. Empty operator This operator returns true if its argument is null, an empty string, an empty array, an empty Map or an empty collection. Otherwise it returns false.
Q19) Explain Tag Library Components in detail. OR Q20) What is a custom tags in JSP? What are the components that make up a tag library in JSP? Ans: A custom tag is a user defined JSP language element. Custom JSP tags are also interpreted by a program but unlike HTML, JSP tags are interpreted on the server side not client side. The program that interprets custom JSP tags is the runtime engine in the application server as Tomcat,JRun etc. When a JSP page containing custom tag is translated into a servlet, The tag is converted to operations on an object called tag handler. The custom tag is used to generating dynamic content inside the JSP page. Tag Library Components: To use custom tags, you need to define three separate components: 1. The tag handler class that defines the tags behavior. 2. The TLD file that maps the XML element names to the tag implementations 3. The JSP file that uses the tag library The tag handler class: When define a new tag your first task is to define a Java class that tells the system what to do when it sees the tag. This class must implement the SimpleTag API interface. In practice you extend SimpleTagSupport class, which implements the SimpleTag interface and access some of its methods. The SimpleTag interface and SimpleTagSupport class are reside in the javax.servlet.tagext package. The code that does actual work of the tag goes inside the doTag method.usually, this code outputs content to the JSP page by invoking the print method of the JspWriter class. To obtain an instance of JspWriter class you call getJspContext().getOut() inside the doTag method. The doTag() methos is called at request time. The Tag library Descriptor File: Once you have defined a tag handler, your next task is to identify this class to the server and to associate it with a particular XML tag name. This task is accomplished by means of a TLD file in XML format. This file contains some fixed information such as description, name, tag class and body content. PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 13
Description: this optional element allows the tag developer to document the purpose of the custom tag. Name: this requires element defines the name of the tag as it will be referred to by the JSP page. Tag-class: this require element identifies the fully qualified name of the implementing tag handler class. Body-content: This required element tells the container how to treat the content between the beginning and ending of the tag. The value that appears here can be either empty, scriptless. The value of empty means that no content is allowed to appears in the body of tag. This means the declared tag can only appear following form: <prefix:tag/> or <prefix:tag></prefix:tag> The JSP File: Once you have a tag handler implementation and a TLD. You are ready to write a JSP file that makes use of the tag. Somewhere in the JSP page you need to place the taglib directive. This directive has the following form: <%@ taglib uri=. Prefix= %> The required uri attribute can be either an absolute or relative URL referring to a TLD file. The required prefix attribute specifies a prefix to use in front of any tag name defined in the TLD of this taglib declaration. For example , if the TLD file defines a tag named tag1 and the prefix attribute has a value of test, then the jsp page would need to refer to the tag as test:tag1. Syntax: <test:tag1>Arbitrary JSP</test:tag1> or <test:tag1/>
.. Q21) Explain all tags of JSTL with its all attributes. OR Q22) Explain plugin tags of JSP standard Tag Library. Ans: C:out Tag=> The c:out tag is very similar to jsp scripting expression like <%= .. %> and standard JSP EL use like ${.}. but it has many advantages. Unlike the JSP scripting, it is a regular tag. So it makes the HTML look cleaner. The title and heading of the page use the c:out tagto output special characters. <c:out value=hello />
C:forEach and c:forTokens=> the c:forEach tag provides basic iteration accepting many difference collection types. It can also function as a counter based for loop specifying a begin,end and a step index. It used var attribute. The c:forTokens tag functions much like c:forEach except it is designed to iterate over a string of tokens separated by delimiters. <c:forEach var =i begin=1 end=10 step=2> </c:forEach> <c:forTokens var=item items=<once)upon,A(time%there>delime=<),(%>> </c:forTokens>
C:if tag=> The c:if tag is a simple conditional tag that evaluate its body if the supplied condition is true. The condition evaluated through its required attribute test. <c:if test=${i>3}> Test body </c:if>
PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 14
C:choose tag=> the c:chose tag is a conditional tag that establishes a context for mutually exclusive conditional operations markes by the c:when and c:otherwise tags. These tag works like standard java switc- case-default. <c:choose> <c:when test=${i<3}>(less than 3)</c:when> <c:when test=${i<5}>(less than 5)</c:when> <c:otherwise>(greater than 5)</c:otherwise> </c:choose>
c:set and c:remove Tags=> The c:set tag is used either for setting a scoped attribute or updating and creating bean properties and map values. <c:set var=attributeName value=someValue> <c:set target=bean property=name>pgi</c:set> The c:remove tag works by instructing it to remove the authors attribute from every scope by omitting the scope attribute. <c:remove var=attributeName/>
C:import tag=>the c:import tag can just as easily import content from the same container. In such cases you use the c:param tag in the exact same way as you would use the jsp:param with the jsp:include standard action.
C:url and c:param Tag=> Just like encode URL method it encodes URL in its required value attribute appending the session id if the client browser is not using cookies. Just like the c:import tag the c:url tag is able to hold off on outputting the URL string if the optional var attribute is present. The c:url tag in combination with the c:param tag solves yet another problem. It is used if you need to append some parameters at the end of the URL. <c:url value=/out.jsp var=inputurl> <c:param name=name values=john dow/> </c:url>
C:redirect Tag=>The c:redirect tag acts just like the sendRedirectURL method of the HttpServletResponse class if its required url attribute specifies an absolute URL. <c:redirect url=http://www.google.com.search> <c:param name=h1 value=en/> <c:param name=q>core servlets</c:param> </c:redirect>
C:catch tag=> The c:catch tag acts like the try/catch construct in java, except in the case of c:catch, there is no try. <c:catch var=myException> <% int x=1/0; %> </c:catch>
PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 15
Q23) Explain advantage of JSP over Servlet. OR Q24) What is the different between JSP and Servlet? Ans: Servlet is a java program that runs in conjuction with a web server. A servlet executed in response to an Http request from a client browser. The servlet executes and then returns an HTML page back to the browser. A JSP is text document that describes how a server should handle specific requests. A JSP run by a JSP server, which interprets the JSP and performs the action the page describes. The JSP server compiles the JSP into a servlet to enhance performance. The server would then periodically check the JSP for changes and if there is any change in JSP, the server will recompile it into a servlet. JSP initial acces slower than servlets because they need to be interpreted or compiled by the server, response time for initial accesses may be slower than servlets. JSP separates the presentation layer(i.e. web interface logic) from the business logic(i.e. back end content generation logic) JSP can only support HTTP Protocol. But a servlet can support any protocol like HTTP,FTP,SMTP etc. thats why JSP is used only mainly for presentation . 1] Servlet is a pure java class..whereas JSP is not.... 2] We can put HTML Code inside servlets...and JSP. 3] when we use HTML in java code than it is called servlet and when we use Java code is html then it is called JSP.
. Q25) What types of comments are available in the JSP? JSP Comments Example : JSP comment starts <%-- and end --%> . <%-- Two expressions are listed below. Only one should print. --%>
..
PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 16
JDBC Q26) How does JDBC work? Explain JDBC API and also define objects of JDBC API.
Ans: How Does JDBC WORK 1. Establish a connection with a data source 2. Send SQL queries and update statement to the data source 3. Process the result at the front end.
JDBC
Component of Java database connectivity
The Java application calls JDBC classes and interfaces to submit SQL statement and retrieve results. JDBC API Noe we will learn about the JDBC API. The JDBC API is implemented through the JDBC driver. The JDBC driver is a set of classes that implement the JDBC interfaces to process JDBC calls and return result set to a java application. The Databse(or data store) store the data retrieved by the application using the JDBC Driver. The API interface is made up of 4 main interfaces. 1. java .sql .DriverManager 2. java.sql.Connection 3. java.sql.Statement 4. java.sql.Resultset in addition to these, the following support interface are also available to the developer. JDBC
Java Application JDBC Driver Database PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 17
Java.sql.driver Java.sql.Date Java.sql.Time Java.sql.Types Java.sql.Numeric The Main Objects of the JDBC API include: 1. A Data Source object is used to establish connection. Although the driver manager can also be used to establish a connection, connecting through a Data Source object is the preferred method. 2. A Connection object controls the connection to the database. An application uses the connection object to create statement. 3. Statement object are used for executing SQL queries. 4. A Result set object act like a workspace to store result of queries. A result set is returned to an application when a SQL query is executed by a statement object. . Q27) What are the JDBC? What are the advantages of using JDBC with java? Ans: JDBC is an API(Application Programming Interface)which consists of a set of java classes, interface and exceptions with the help of JDBC programming interface, java programmers can request a connection with a database, then send query statement using SQL and receive result of processing. According to Sun specialized JDBC drivers are available for all major databases including relational database from oracle corp., IBM, Microsoft Corp. The combination of Java with JDBC is very useful because it lets the programmers run his program on different platforms. Some of the advantages of using g java with JDBC are 1. Easy and economical 2. Continued usage of already installed database. 3. Development time is short. 4. Installation and version control simplified. . Q28) Why ODBC cannot be used directly with Java Program?
Ans: ODBC can not used directly with java program due to various reason describe below. 1. ODBC can not be used directly with java because it uses C interface. This will have drawbacks in the security, implementation and robustness. 2. ODBC makes use of pointers which have been removed from java. 3. ODBC mixes simple and advanced feature together and has complex structure. Hence, JDBC came into existence PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 18
Q29) Give the standard steps for connecting and querying database with java application. Also discuss the important methods of Statement class. OR Q30) What is JDBC ? How the transaction is carried out using JDBC API? Explain with Example. Ans: JDBC is an API(Application Programming Interface)which consists of a set of java classes, interface and exceptions with the help of JDBC programming interface, java programmers can request a connection with a database, then send query statement using SQL and receive result of processing. STEPS TO CONNECT TO A DATABASE: The Interface and classes of the JDBC API are present inside the package called as java.sql package.There any application using JDBC API must import java.sql package in its code. Import java.sql.*; STEP 1: Load the Drivers The first step in accessing the database is to load an appropriate driver.You can use one driver from the available four drivers which are described earlier.However, JDBC -ODBC Driver is the most preferred driver among developers.If you are using any other type of driver,then it shoud be installed on the system .in order to load the driver, you have to give the following syntax: Class.ForName(sun.jdbc.odbc.JdbcOdbcDriver); We can also the register the driver (if the third party driver) with the use of method registerMethod() whose syntax is as follows: DriverManager.registerDriver(Driver dr); Where dr is the new JDBC driver to be registered with the driver manager. there are number of
Step 2: Make the Connection The getConnection()method of the Driver Manager class is called to obtain the connection object. The syntax is Connection conn=DriverManager.getConnection(jdbc:odbc:<DSN NAME>); Here note that getConnection() is a static method, meaning itshould be accessed along with class associated with the method.The DSN(DATA source Name) neme is the name which you gave in the control panel->ODBC while registering the Database or table.
Step 3: Create JDBC Statement A statement object is used to send SQL query to the database management system .you can simply create a statement object and then execute it.Connection object conn here to create the statement object stmt the syntax is. Statement stmt=conn.createStatement(); As mentioned earlier we may use prepared Statement or callable Statement according to the requirement.
PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 19
Step 4: Execute the Statement In order to execute the query you have to obtain the Result Set object similar to Record Set in Visual Basic and called the execute Query()method of the statement. Actually the recordSet object contains both the data returned by query and the method for data retrival. The syntax is Result Set rs=stmt.executeQuery(select * from student); The executeUpdate() method is called whenever there is a delete or an update operation.
Step 5: Navigation or looping through the ResultSet The ResultSet object contains rows of data that is parsed using the next() method like rs.next().we use the getXXX() like getInt() to retrive Integer fields and getString() for string fields. System.out.println(rs.getInt(id));
Step 6: Close the Connection and Statement Objects After performing all the above steps you must close the connection, statement and Result set object by calling the close () method.
ResultSet object with rs.close(); Statement object with Stmt.close(); Connection object with
Q31) What is the Statement? What is the use of PreparedStatement in JDBC? List out various methods of PreparedStatement. OR Q32) What are different types of statements available in JDBC? Where do we use these Statements? Ans: Statement object are used for executing SQL queries. In order to execute the query you have to obtain the Result Set object similar to Record Set in Visual Basic and called the execute Query()method of the statement. Actually the recordSet object contains both the data returned by query and the method for data retrival. The syntax is Result Set rs=stmt.executeQuery(select * from student); The executeUpdate() method is called whenever there is a delete or an update operation. The executeQuery() method is called when select query is fired. Both methods are available into Statement class. Different Types of JDBC SQL Statement: 1. java.sql.Statement: Top most interface which provides basic methods useful for executing SELECT, INSERT, UPDATE and DELETE SQL Statement. 2. java.sql.PreparedStatement: it is an enhanced version of java.sql.Statement which is used to execute SQL queries with parameters and can be executed multiple times.
3. java.sql.CallableStatement: it allows you to execute stored procedures within a RDBMS which supports stored procedure.
PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 21
Methods of PreparedStatement: PreparedStatement st= st = con.prepareStatement(mysql); st.setInt(1, 1007); st.setString(2,"Pandya Chaitanya"); st.setString(3,"Manager"); st.setString(4,"20-01-2010"); st.setInt(5,15000); st.executeUpdate();
. Q33) What is the use of ResultSet in JDBS? Write a code in JDBC for view list of records from a table. Ans: A Result set object act like a workspace to store result of queries. A result set is returned to an application when a SQL query is executed by a statement object. Methods of ResultSet are getInt() and getString() and close(). CODE: import java.sql.*; class Example1 { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException cnf) { System.out.println("Error : "+cnf); } try { Connection con=DriverManager.getConnection("jdbc:odbc:emp"); Statement smt=con.createStatement(); ResultSet rs=smt.executeQuery("select * from employee"); while(rs.next()) { System.out.println("empid="+rs.getInt(1)+"ename="+rs.getString(2)); } } catch(SQLException se) { System.out.println("Error in SQL : "+se); }} } . PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 22
Q34) What is the most important package used in JDBC? Explain different methods to load the drivers in JDBC. Ans: The most important package used in JDBC is java.sql package. The first step in accessing the database is to load an appropriate driver 1. Class.ForName takes a string class name and loads the necessary class dynamically at run time as specified in the example to load the JDBC-ODBC driver following syntax may be used.
Syntax: Class.ForName(sun.jdbc.odbc.JdbcOdbcDriver); 2. To register the third party driver one can use the method registerMethod() whose syntax is follows: Syntax: DriverManager.registerDriver(Driver dr); 3. Use new to explicitly load the driver class. This hard codes the driver and (indirectly) the name of database into your program. 4. The System class has static property list.if this has a property jdbc.drivers set to a : separated list of driver class names, then all of these drivers will be loaded and registered automatically. Syntax: Properties props=new Properties(); FileInputStream in=new FileInputStream(Database.Properties); Props.load(in); String drivers=props.getproperty(jdbc.drivers); Class.forName(drivers);
.
PATEL GROUP OF INSTITUTIONS Subject: WTAD Topics: JSP & JDBC (UNIT 6, 7, 8, 9) Developed by: Prof. ADNAN AHMAD PATHAN Page 23