Download presentation
Presentation is loading. Please wait.
Published byNickolas O’Brien’ Modified over 9 years ago
1
Which of the options locate the bean equivalent to the following action? (Select three) a request.getAttribute("address"); b request.getParameter("address"); c getServletContext().getRequestAttribute("address"); d pageContext.getAttribute("address",PageContext.REQUEST_SCOPE); e pageContext.getRequest().getAttribute("address"); f pageContext.getRequestAttribute("address"); g pageContext.getRequestParameter("address"); Answers: a, d, and e
2
HttpServletResponse.sendRedirect() works like this: if the URL is absolute http://www.google.com, it redirects to http://www.google.com. If the URL is not absolute, it redirects relative to the current URL. If the URL starts with / it redirects relative to the context root, Else it redirects to the current url Based on above rules in your case it redirects to http://currenturl/www.google.com. Instead modify your code like this response.sendRedirect("http://www.google.com"); return;
3
What is context root A name that gets mapped to the document root of a Web application.
4
Difference between forward and redirect forward Control can be forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved. This is the major difference between forward and sendRedirect. When the forward is done, the original request and response objects are transfered along with additional parameters if needed. the difference between the two is that sendRedirect always sends a header back to the client/browser. this header then contains the resource(page/servlet) which u wanted to be redirected. the browser uses this header to make another fresh request. thus sendRedirect has a overhead as to the extra remort trip being incurred. its like any other Http request being generated by ur browser. the advantage is that u can point to any resource(whether on the same domain or some other domain). for eg if sendRedirect was called at www.mydomain.com then it can also be used to redirect a call to a resource on www.theserverside.com. where as in case of forward() call, the above is not true. resources from the server, where the fwd. call was made, can only be requested for. but the major diff between the two is that forward just routes the request to the new resources which u specify in ur forward call. that means this route is made by the servlet engine at the server level only. no headers r sent to the browser which makes this very eficient. also the request and response objects remain the same both from where the forward call was made and the resource which was called.
5
Difference between forward and redirect redirect Control can be redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url. Since it is a new request, the old request and response object is lost. For example, sendRedirect can transfer control from http://javapapers.com to http://anydomain.com but forward cannot do this. ‘session’ is not lost in both forward and redirect. To feel the difference between forward and sendRedirect visually see the address bar of your browser, in forward, you will not see the forwarded address (since the browser is not involved) in redirect, you can see the redirected address.
6
When can we use forward and when can we use sendRedirect? Technical scenario: redirect should be used If you need to transfer control to different domain To achieve separation of task. For example, database update and data display can be separated by redirect. Do the PaymentProcess and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PyamenProcess will not be repeated. But if you use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosinstent data. For other than the above two scenarios, forward is efficient to use since it is faster than sendRedirect.
7
What is the pageContext implicit object? A pageContext implicit object is used for storing and retrieving page-related information and sharing objects within the same translation unit and same request. Also used as a convenience class that maintains a table of all the other implicit objects.
8
JSP LifeCycle The JSP page translated into a servlet The servlet is complied The Servlet is loaded into the server’s memory The jspInit() method is called The _jspService() is called
9
What is the pageContext implicit object? It stores referece to the implicit objects. The following example shows how PageContext is used to populate other implicit objects. public void _jspService (HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException {... try {... application = pageContext.getServletContext (); config = pageContext.getServletConfig (); session = pageContext.getSession (); out = pageContext.getOut ();... } catch (Throwable t) {... } finally {... } }
10
What is the pageContext implicit object? Provides convenience methods to get and set attributes in different scopes. This example uses attributes to save and retrieve data in each of the four scopes:
11
What is the pageContext implicit object? Provides convenience methods for transferring requests to other resources in your application: PageContext void include (String relativeURL) Includes the output of another resource in the output of the current page. Same as ServletRequest.getRequestDispatcher ().include (); void forward (String relativeURL) Forwards the request to another resource. Same as ServletRequest.getRequestDispatcher ().forward (); For example, to forward a request to another resource from a servlet, we have to write the following to lines: RequestDispatcher rd = request.getRequestDispatcher ("other.jsp"); rd.forward (request, response); In a JSP page, we can do that in just one line by using the pageContext variable: pageContext.forward ("other.jsp");
12
What is the pageContext implicit object? The pageContext object has a type of javax.servlet.jsp.PageContext and according to the API documents:API documents "A PageContext instance provides access to all the namespaces associated with a JSP page, provides access to several page attributes, as well as a layer above the implementation details. Implicit objects are added to the pageContext automatically" A PageContext instance is obtained by a JSP implementation class by calling the JspFactory.getPageContext() method, and is released by calling JspFactory.releasePageContext(). a single API to manage the various scoped namespaces a number of convenience API?s to access various public objects a mechanism to obtain the JspWriter for output a mechanism to manage session usage by the page a mechanism to expose page directive attributes to the scripting environment mechanisms to forward or include the current request to other active components in the application a mechanism to handle errorpage exception processing
13
How to get initialization parameters from jspInit() method you can call getServletConfig().getInitParameter(“name-of- init-param-in-jsp") in jspInit method Georgy Gobozov Jun 14 '13 at 13:41 Georgy GobozovJun 14 '13 at 13:41
14
Difference between ServletConfig and ServletContext paramName paramValue In the servlet code getSerlvetConfig().getInitParameter("paramName"); note: * Servlet Init Parameter Can't be used until the Servlet is initialized!! * Config parameter is read only once!! * Init Parameter is only for Servlet!! Each Servlet has it's own parameter
15
Difference between ServletConfig and ServletContext paramName paramValue In the servlet code getSerlvetContext().getInitParameter("paramName"); note: * Context init parameter is for whole web app!! * Context init only need to be defined in one DD and can be used anywhere in web app!! * In a distributed environment, one Servletcontext per JVM
16
Page implicit object The JSP implicit page object is an instance of the java.lang.Object class. It represents the current JSP page. 2. That is, it serves as a reference to the java servlet object that implements the JSP page on which it is accessed. It is not recommended to us this because it consumes large memory. 3. The page object works like “this” key word in java. 4. In the generated servlet, the variable is declared as follows Object page = this; Parent reference can be used to hold child class object but, by using that reference we are allow to call only the methods available in the parent class. Note : page cannot be used to directly call the servlet methods · page.getServletInfo() Error because page is java.lang.Object type · ((servlet)page).getServletInfo() · this.getServletInfo() 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 page object is really a direct synonym for the this object.
17
Request based sharing A second page shares request object of the first page if the second page is invoked with jsp:include, jsp:forward, or the include or forward methods of the RequestDispatcher
18
TAG LIBRARIES The Basics Creating and using custom tags utilizes SimpleTag api which was introduced in version 2.4 of servlet specification. Tag Library Components The tld (xml files) files map the xml element names to tag specification and are placed in WEB-INF/tld The tag handler class extends SimpleTagSupport and is placed in WEB-INF/classes The JSP file that uses the tag library NOTE: The taglib directive is placed in jsp file. It has two attributes. A] uri attribute giving the location of tld file and B] prefix attribute which is prefixed to every tag.
19
The Tag Handler Class This class extends SimpleTagSupport which is available in javax.servlet.jsp.tagext package This is a java class that tells the system what to do when it sees the tag. This class has a doTag() method. The code that does the actual work of the tag goes inside this method Every tag handler class must have a no-arg constructor or its instantiation will fail. A new instance of the tag handler class is created for every tag occurrence on the page. This alleviates worries about race conditions and cached values instance variables in the tag handler class. To obtain an instance of JspWriter class you call: JspWriter out = getJspContext().getOut(); You place the tag handler class in the same location you place a regular servlet inside the WEB-INF/classes
20
The Tag Handler Class package somepackage; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*; public class ExampleTag extends SimpleTagSupport{ public void doTag() throws JspException, IOException{ JspWriter out = getJspContext.getOut(); out.print(“ Hello World ”); }
21
The Tag Library Descriptor File The tag library descriptor file is in xml format This file identifies the tag handler class to the server and associates it with a particular XML tag name using the element. The tld file must be placed inside the WEB-INF directory or a subdirectory thereof. The element through the following subelements in their required order defines the custom tag. A] description – document the purpose of custom tag B] name – this is a required element and defines the name of the tag as it will be referred to by the JSP page (actually the tag suffix) C] tag-class – This a required element and it defines the fully qualifies class name of the implementing tag handler class D] body-content – This ia a required element and it tells the container how to treat the content between the beginning and ending occurrence of the tag. It can have the following values: 1]empty – no content allowed 2]scriptless, - can have JSP content but no scriptlets 3]tagdependent – can have any type of content as its body 4]JSP - provided for backward compatibility with the classic custom tag model.
22
The Tag Library Descriptor File (example.tld) Example Tag example somepackage.ExampleTag empty
23
The JSP File This file has the taglib directive which is of the following form: <%@ taglib uri=“/WEB-INF/tlds/example.tld” prefix=“test” A] uri – gives the location of tld file relative to the applications root directory. B] prefix – specifies a prefix that is used in front of any tag name defined in the tld of this taglib declaration. The tag created will be of the following form: Note: the name of the tag is example and is referenced in the tld file Note: This tag is placed in the JSP file where you want to obtain the output.
24
The JSP File Example JSP Page
25
Assigning Attributes to Tags The tag will assume the following form If you use attribute1 in your tag you need to have setAttribute1(String value1) method in your tag handler class You also need to add the elements to the tld file. This element is of the following form: N (prime number length> attribute1 false The attribute has the following sub elements: 1] name – this is the same as that mentioned in the tag 2] required – this can have two values true,false 3] rtexprvalue – this indicates whether the attribute can be either a jsp expression like or a JSP EL like ${bean.value} which is indicated by true or whether it must be a fixed String which is indicated by false. The default value is false. NOTE: these attributes are passed to the tag handler class or the.tag files as parameters
26
Include tag body in the output scriptless JSP content Note: the portion “scriptless JSP content” is the tag body To output the body content of the tag inside the doTag() method you need to use the below code: getJSPBody.invoke(null); Note: it is the output resulting from the execution of tag body’s Jsp content that gets passed to the client, not the JSP code itself. Given below is sample Tag Handler Class package somepackage; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*; public class ExampleTag extends SimpleTagSupport{ public void doTag() throws JspException, IOException{ JspWriter out = getJspContext.getOut(); out.print(“ Before Printing TagBody ”); getJSPBody.invoke(null); out.print(“ After Printing TagBody ”); }
27
How to get HttpServletRequest instance from PageContext and invokeing tag body conditionally package somepackage; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*; public class ExampleTag extends SimpleTagSupport{ public void doTag() throws JspException, IOException{ PageContext context = (PageContext)getJspContext(); HttpServletRequest request = (HttpServletRequest)context.getRequest(); if(request.getParameter(“debug”) != null){ getJSPBody.invoke(null); }
28
Creating Tag Files JSP based way to create custom tags using tag files. We do not create any tld files in this method These tag files run only on JSP 2.0 There are two stepsto creating a JSP-based custom tag: 1] Create a JSP based tag file. This file has a.tag extension and is placed inside the WEB-INF/tags or a subdirectory thereof 2] Create a JSP page that uses the tag file. The JSP page point to the directory where the tag file resides using the tagdir attribute of the taglib directive. i.e. uri attribute is replaced by tagdir attribute. The name of the tag file(minus the.tag extension) becomes the name of the custom tag therefore no tld connecting the implementation of the tag with its name is needed
29
Creating.tag file Name of the file: simplePrime2.tag <%= coreservlets.Primes.nextPrime (coreservlets.Primes.random(50)) %>
30
Creating the JSP file using.tag file <HTML Some 50 digit primes Some 50 digit primes
31
Using attributes with JSP based custom tags To use attributes with JSP based custom tags each attribute must be declared inside the.tag file This declaration is accomplished by the attribute directive.ie. This directive is used in the tag file You can use the attributes of the attribute tag like 1] name – name of the attribute 2] required – true/false prime2.tag file ____________________________________________________________________ <% int len = 50; try{ len = Integer.parseInt(length); } catch (NumberFormatException nfe){} %>
32
prime2.jsp Some N digit Primes Some N-Digit Primes Default (50-digit)
33
Outputting the tag body in.tag file using Heading2.tag
34
heading2.jsp Headings Some N-Digit Primes First Heading Second Heading Third Heading
35
Advanced Features – buffering the output of the tag body The below code snippet shows how to buffer the output of the tag body in StringWriter object. Later this output is modified using ServletUtilities.filter() method which is then sent to client. StringWriter myWriter = new StringWriter(); getJspBody().invoke(myWriter); HtmlFilterTag.java package coreservlets.tags; import javax.servlets.jsp.*; import javax.servlet.jsp.tagest.*; import java.io.*; import coreservlets.ServletUtilities; public class HtmlFilterTag extends SimpleTagSupport{ public void doTag() throws JspException, IOException{ StringWriter myWriter = new StringWriter(); getJspBody().invoke(myWriter); String output = ServletUtilities.filter(stringWriter.toString()); JspWriter out = getJspContext().getOut(); out.print(output); }
36
Advanced Features – Assigning Dynamic Values to Tag Attributes The is no change in tag handler class. If we have attribute1 in the tag we will have to provide the setter method public void setAttribute(String value1){ doSomethingWith(Value1) Set the true which means that the attribute can be either a JSP scripting expression or a JSP EL: attribute1 true Use the expression language to get the value of attribute1 in the taglib directive ” />
37
Advanced Features – Assigning complex objects as values to Tag Attributes ” /> If we wanted to pass a collection of Orders or some other complex structure, we still need to provide setter for the attribute as before. However the type of argument in the setter would now be complex object type instead of String public void setAttribute1(SomeComplexObject value1){ doSomethingWith(Value1); } Provide the rtexprvalue element with a value of true attribute1 true The taglib directive remains the same The usage of the tag is very much the same as the one we had for dynamic values ” /> Note: In the above tag the expression ${bean.value} must evaluate to either an instance of SuperClass or an instance of any class that inherits from SuperClass. By SuperClass we are referring to the methods parameters as below: public void setAttribute(SuperClass value1){ }
38
Advanced features – creating looping tag Corresponding to the for loop we use a custom tag as a looping structure in JSP – some text ${someBean.someValue} This tag would create some bean with appropriate values and pass to the JSP content inside the body of the tag. The attributes of the tag are only visible to the tag body. Use the following code inside the doTag() method to place an object as an attribute of the tagbody scope.ie. the object is available inside the tag body getJspContext().setAttribute(key,object) You then use JSP EL inside the body of custom tag to access this attibute some text ${someBean.someValue} While using this tag we use an attribute whose value can be accessed in the tag body using JSP EL Value is ${arrayValue} Note: the above array is generally set in request or session attribute in a servlet and is thus available to the forwarding JSP using EL ${array_name_used _to_set_the_attribute} e.g. request.SetAttribute(“servers”,servers); ${server}
39
Advanced Features– Creating Expression Language Functions Through this feature we are able to call a java method inside the body of the tag using EL without using scripting. The java method (say someMethod())is defined in a utility class say SomeClass.java public class SomeClass{ public static String someMethod(HttpServletRequest request){…} } Inside the tld file the fully qualifies class name anf the method gets mapped to some name that will be used inside the JSP page to invoke the method run</name somepackage.SomeClass java.lang.String someMethod(javax.servlet.HttpServletRequest) Declare the tag library inside the JSP page as below Invoke the method using the tag. The method alias is placed immediately after the tag prefix: ${csajsp:run(pageContext.request)}
40
Advanced Features – Handling Nested Custom Tags The tag body of a custom tag can also contain other custom tags If the inner tag and other tag don’t depend on each other the inner tag can appear without the presence of outer tag. The simple tag api provides two methods that let an inner tag get hold of the outer tag 1.getParent() 2.findAncestorWithClass() A] getParent The getParent() method is called on the instance of inner tag. It returns an object of type JSPTag which can be cast to the type of outer tag’s handler class If this method is called on the outmost tag in hierarchy it returns null. B] findAncestorWithClass(JspTag fromTag, Class toBeMatchedClass) this method starts searching the hierarchy of tags from a given tag instance, fromTag, looking at its parent tag up until it finds a tag instance that matches the type of toBeMatchedClass. If the search takes all the way to the top of the hierarchy with no results it returns null. If this method find the right instance of the tag class it returns it as a JspTag instance With this method you know the parent type in advance so if tis method returns anything but null you are guaranteed that you can successfully cast down te instane it returns using the class type that was provided in the second argument. With getParent() you need to anticipate a ClassCastException How to get at the inner tag from the outer tag – you can store some information in the outer tag that te inner tag can later review and act on. public class OuterTag extends SimpleTagSupport{ public void setSomeValue(SomeClass arg){….} } public class InnerTag extends SimpleTagSupport{ public int doTag() throws JSPException, IOException{ Outer Tag parent = (OuterTag)findAncestorWithClass(this,Outer.class); if(parent == null) { throw new JspTagException(“nestingError”); } SomeClass value= parent.getSomeValue(); DoSomethingWithValue(value); }}
41
JSP Standard Tag Library (JSTL) JSTL provides many useful tag libraries and has been universally accepted by the Java community The most common JSTL library is the core library. It contains the following tags: 1.out 2.if 3.forEach 4.forTokens 5.choose 6.when 7.otherwise 8.set 9.remove 10.import 11.url 12.param 13.redirect 14.catch
42
Installation of JSTL Copy standard.jar and jstl.jar into the WEB-INF/lib directory of your application. Jstl.jar contains only the interfaces that the jstl specification requires Standard.jar contains the actual implementations along with the tld files. Import the library into your JSP page with the taglib directive as below: http://java.sun.com/jsp/jstl/core Note: it’s a known convention that the JSTL core library is assigned “c” as the prefix and you should stick to it. It is also very useful to download the JSTL tag library documentation.
43
c:out tag This tag is very similar to JSP scripting expression and ${expression} where the value of expression is output. The value attribute is evaluated and the resulting expression is output. However the c:out tag lets the JSP developer specify a default value to output if the resulting expression inside the value tag evaluates to null. The attribute escapeXml=“true” allows the tag to automaticallty escapse any xml characters like,”,’ tag” />
44
c:forEach c:forEach provides basic iteration accepting many different collection types e.g. ${item} where list is of the type java.util.List Note: the var attribute allows the developer to specify a key with which to refer to the current element through iteration. c:forEach can also function as a counter-based for loop specifying a begin, end, and a step index i = ${i}
45
c:forTokens this tag is designed to iterate over a String of tokens separated by delimiters the delimiter is specified through its required delims attribute <c:forTokens var=“item” items=“<Once)Upon, a(Time%There…>” delims=“ ” > ${item}
46
c:if This tag evaluates the body if the condition supplied to the test attribute is true e.g. i = ${i} (greater than 3)
47
c:choose c:choose tag is a conditional tag that establishes a context for mutually exclusive operations marked by c:when and c:otherwise tags These tags work in the same way as java switch-case-default statements The c:choose tag itself does not have any attributes, its sole purpose is to provide the context to other two tags. c:when tag has a test attribute that allows the JSP developer to specify a condition, which if evaluated to true would signal the container to evaluate the body of c:when tag If a particular c:when tag evaluates to true no other c:when tag below it are evaluated and the processing jumps to line after the closing c:choose tag If the optional c:otherwise tag is specified and no c:when tag evaluates to true, the body of the c:otherwise tag is evaluated. i=${i} (less than 3) (less than 5) (it is 5! so exciting) (greater than 5)
48
c:set c:set attribute is used either for setting a scoped attribute or updating and creating bean properties and map values. John Dow Note: the last c:set tag does not specify the value attibute. Its value comes from the body of c:set tag the c:set tag provides two attributes var and target of which at least one is required. However these attributes are not allowed to appear at the same time. the var attribute is used to specify the name of the attribute to set. This attribute is set in the scope specified by the optional scope attribute. If the scope attribute is not specified it defaults to page scope. the target attribute must be an expression that evaluates to some object. If the object implements the map interface, the property attribute of the c:set tag is treated as a key with which to create a new map entry with the value specified. if the target evaluated to JavaBean the value of the c:set tag is passed to the property of the target JavaBean specified by the property attribute. When the value of c:set tag evaluates to null, the effect is no different than invoking someScopeReference.setAttribute(null) where someScopeReference is not of request,session,application which essentially removes the attribute from that scope.
49
c:remove the c:remove attribute specifies the name of the attribute to remove using the required var attribute and the scope to remove it from using the optional scope attribute. If the scope is not specified, the c:remove attribute will remove the attribute from all scopes Authors ${pageScope.authors}:${requestScope.authors} ${pageScope.authors}:${requestScope.authors}
50
c:import tag <c:import tag can include the content pointed to by the required attribute “url” even if the content resides on a different webserver. The imported content has to be a snippet of HTML that fits into the structure of the existing HTML page. The links inside the imported content have to be absolute. The behaviour of c:import tag is to output the included content into the included page at the pace where c:import tag appears However if the optional var and the likewise optional scope attributes are specified, the included content can be saved as a scoped attribute instead. If the var attribute is specified the c:import tag does not output the included content but caches it into a scoped var attribute. If the c:import tag does not specify a the included content is output into the place where the c:import tag appears If the scope attribute is omitted it defaults to page scope. If the imported attribute contains relative links it will not work. http://www.google.co.in ${outputBufferVar} http://www.google.co.in
51
c:url and c:param If the cookies are disables the container will not append the sessionID to the url that are sent back to the client inside your JSP pages. Every url within your page needs to be encoded if its to retain the sessionid info The c:url encodes the url specified in its required value attribute appending the sessionID if the client is not using cookies and leaves the url as it was if the client browser is able to accept a session cookie. 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. In such a case the resulting URL gets stored in in a optional “scope” attribute If omitted it defaults to page scope. We use the c:url tag in conjunction with c:param tag to encode a value with a space in it
52
c:redirect This tag is used or redirecting urls in JSP pages If its required attribute “url” specifies an absolute url the c:redirect tag acts just like the sendRedirectURL methodof the HttpServletResponse class However if the url specified in the url attribute is a relative url a dynamic forward occurs which is equivalent to the forward method of the RequestDispatcher class. The c:redirect tag can take advantage of the automatic encoding provided by nesting one or more param tags in its body in which case the name,value pairs are appended to the end of the url.
53
c:catch c:catch acts likek the try catch construct in java except that in the case of c:catch there is no try. You can surround the part of the page that may throw an exception with the c:catch tag and if an exception occurs the page will still render up to the point where the exception occurs and then continue rendering from the c:catch end tag. You can throw the thrown exception in a page scoped attribute specified by the optional var attribute. Avoid using the c:catch tag for anything other than debugging or experimentation. Exception handling should be a part of the business logic code not JSP code. After illegal operation Exception Message: ${myException.message}
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.