Você está na página 1de 18

applets or servlets servlets are more efficient web applications are for users web services are for

computers URL uniform resource locator CGI common gateway interface Java Servlets vs. CGI, faster Servlets, single process, so faster than CGI Java Servlets vs. CGI, scalable Servlets more scalable than CGI Java Servlets vs. CGI, uses java java servlets, duh Java Servlets vs. CGI, standardized logging Servlets Java Servlets vs. CGI, error handling and security Servlets Java Servlets vs. CGI, must use the Java programming language Servlets Java Servlets vs. CGI, concurrency servlets concurrency not limited to database draw java servlets architecture, module 1, slide 11 of 15 diff btwn servlets and CGI Java servlets are similar to CGI, but they execute in a Virtual Machine for the Java platform (Java Virtual Machine, or JVM machine) using threading Servlets extend javax.servlet.http.HttpServlet Servlets provide HTMl responses to the browser doGet the doGet method of a servlet can be used to impolement the required behavior of the servlet @WebServlet the @WebServlet annotataion can be used to tie oa servlet to a URL editing HTML is servlets is hard. WYSIWYG editors can't be used. Hand editing HTML is tedious and error pron e. JSP Java Server Pages JSPs embed Java in HTML how a JSP is processed 1. Convert to Servlet 2. Consider JSP as "source code" 3. Generated servlet defi nes variables including request and response MVC model view controller HTTP methods, OPTIONS request for the communications options available on the request/response chain HTTP methods, GET request to retrive information identified by the Request-URL HTTP methods, HEAD identical to the GET except that it does not return a message-body, only the hea ders HTTP methods, POST request for the server to accept the entity enclosed in the body of the HTTP mes sage HTTP methods, PUT

request for the server to store the entity enclosed in teh body of the HTTP mess age HTTP methods, DELETE request for the server to delete the resource identified by the Request-URL HTTP methods, TRACE request for the server to invoke an application-layer loop-back of the request m essage HTTP methods, CONNECT reserved for use with a proxy that can switch to being a tunnel What is the difference between HTTP GET and HTTP POST? GET is basically for just getting (retriving) data whereas POST may involve anyt hing. like storing or updating data, or ordering a product, or sending E-mail. T he HTML specifications technically define the difference between GET and POST so that former means that form data is to be encoded (by a browser) into a URL whi le the latter means that the form data is to appear within a message body. But t he specifications also give the usage recommendation that the GET method should be used when the form processing is "idempotent" (i.e. it has not lasting observ able effect on the state of teh world), and in those cases only. If the processi ng of a form is idempotent (i.e. it has no lasting observable effect on the stat e of the world), then the form method should be GET. Many database searches have no visible side-effects and make ideal applications of query forms. If the serv ice associated with the processing of a form has side effects (for example, modi fication of a database or subscriptiong to a service), the method should be POST . What is the life cycle of a Servlet? init(), service(), and destroy() What is the lifecycle of a JSP? page translating, compilation, load, instantiate, jsp_init(), jsp_service(), and jsp_destroy() What is the difference between Generic Servlet and HTTP servlet? javax.servlet.Servlet is the central interface in the Servlet.API. Every servlet class must directly or indirectly implement this interface. It has five methods : init(), service(), destroy(), getServletConfig(), and getServletInfo(). The se rvice (ServletRequest, ServletResponse) method handles requests and creates resp onses. The servlet container automatically calls this method when it gets any re quest for this servlet. a. GenericServlet: javax.servlet.GenericServlet class im plements the Servlet interface. It is an abstract class that provides implementa tion for all methods except the service() method of the Servlet interface. We ca n extend this class and implement the service() method to write any kind of serv let. b. HTTP Servlet: javax.servlet.http.HTTPServlet represents a HTTP capable s ervlet and is an abstract class that extends GenericServlet. It provides the sup port for HTTP protocol. It adds a new service() method with the signature: servi ce(HttpServletRequest, HttpServletResponse). For every HTTP method, there is a c orresponding method in teh HTTPServlet class, e.g.; doGet(), doHead(), doPost(), doDelete(), doPut(), doOPtions() and doTrace(). Depending on teh HTTP method, t he corresponding do.XXX() method is called on the servlet. How would you preinitialize/preload a servlet? The servlet specification defines the <load-on-startup> element which can be spe cified in the deployment descriptor to make the servlet container load and initi alize the servelt as soon as it starts up. What is ServletConfig? The ServletConfig is defined in the javax.servlet.package. It provides four meth ods: getInitParameter(String), Enumeration getInitParameterNames(), getServletCo ntext(), and getServletName(). A servlet container takes information specified a bout a servlet in the deployment of descriptor and wraps it intoa ServletConfig object. This information can then be retrieved by the servlet at the time of it s initialization. It is passed as parameter to the init method: init(javax.servl et.ServletConfig). Name some important tags in ServletConfig. Inside web.xml and inside a servlet tag: <init-param> <param-name><param-value><

/init-param> What is a ServletContext? ServletContext interface is a window fora servlet to view its environment. Ever y web application has one and only one ServletContext and it is available to all the active resources of that application. It is also used by the servlets to sh are data with one another. A servlet can use this interface to get information s uch as initialization parameters for the web application or the servlet containe r's version. This interface also provides utility methods for retriving MIME typ e for a file for retriving shared resources, for logging and so forth. Name some important tags in ServletContext. inside web.xml and outside all servlet tags: <context-param><param-name><param-v alue></context-param> How would you forward a request from a Servlet to a JSP? Using RequestDispatcher: RequestDispatcher dispatcher = httpServletRequest.getRe questDispatcher(url); dispatcher.forward (httpServletRequest,httpServletResponse ); What is the difference between RequestDispatcher.forward() and HttpServletRespon se.sendRedirect()? An important difference between RequestDispatcher.forward() and HttpServletRespo nse.sendDirect() is that foward() is handled completely on teh server side while redirect() sends a redirect message to the browser. In that sense, forward() is transparent to the browser while redirect() is not. Both javax.servlet.ServletC ontext and javax.servlet.ServletRequest have the method getRequestDispatcher(pat h) In which directory is web.xml located? \root\WEB-INF\ What is JSTL? JSTL stands for JSP Standard Template Library What are the various types of mark-up tags provided by JSP? JSP provides four major categories of markup tags: a. Directives- page, include, and taglib. b. scripting elements - are used to embed programming instructions. JSP provides three tyhpes of scripting elements: declarations, scriptlets, and expressions. i. Declarations allow the developer to define variables and methods for a page, which ay be accessed by other scripting elements. <%! Declarations %> or <jsp:declaration> declarations </jsp:declaration>. You can declare both me thods and variables. ii. Scriptlets are blocks of code to be executed each time the JSP page is processed for a request. <%scriptlet %>. iii. expressions are in dividual lines of code <%=expression%>. c. Comments- i. JSP comments - <%-- comm ent -%>, - the body of the these comments are ignored by the JSP container. When the page is compiled into a Servlet, anything appearing between these two delim iters is skipped while translating the page in to Servlet source code. ii. Scrip ting language comments - <% /* comment */ %> - Like JSP comments, scripting lang uage comments will not appear in the page's output. Unlike JSP comments, though, which are ignored by the JSP container, scripting language comments will appear in the source code generated for the Servlet. d. Actions What are the various scopes available in JSP? page, request, session, and application Can you name some of the implicit objects in JSP? JSP Container exposes a number of internal objects to the page author. These are referred to as implicit objects, because their availability in a JSP page is au tomatic. These objects are automatically assigned to varaible names and are acce ssible via JSP Scripting elements. Following are the nine implicit objects provi ded by JSP and they fall in to four main categories. a. Objects related to a JSP Page's Servlet i. page- Page's Servlet instance(represents the Servlet itself) ii. config- Servlet Configuration Data b. Objects concerned with page input and output i. request- Request data including parameters ii. response- Response data iii. out- output stream for page content. c. Objects providing information abou t the context within which a JSP page is being processed. i. session- user speci fic session data ii. application- Data shared by all application pages iii. page Context- Context data for page execution d. Objects resulting from errors i. Exc

eption- Uncaught error exception Can you name some of the standard Action Tags in JSP? A standard action is an action tag that has been defined by the JSP standard. St andard actions are associated with the namespace jsp and appear with a prefix js p: a. <jsp:forward page="localURL" /> b. <jsp:include page="localURL" flush="fla g" /> c. <jsp:plugin> is used to generate browser specific HTML for specifying j ava applets which rely on the Sun Microsystems java plug-in. d. <jsp:useBean>, < jsp:setProperty> and <jsp.getProperty> What is a Directive. Can you name some of the directives in JSP? Directives are used to convey special processing information about the page to t eh JSP container. Directives are applied at page. translation(compile) time. a. Page directive: <%@ page.attr1="val1"...%>. There are a list of attributes suppo rted by the page directive: info, language, contentType, pageEncoding, extends, import, session, buffer, autoFlush, isThreadSafe, errorPage, isErrorPage. i. The errorPage attribute is used to specify an alternate page to display if an uncau ght error occurs while the JSP container is processing the page. ii. When the is ErrorPage attribute is set to true, it indicates that the current page is intend ed for use as a JSP error page. As a result, this page will be able to access th e exceptino implicity object. b. Include directive: <%@ include... %> c. Taglibr ary directive: <%@ taglib url=" prefix=" %> What is the difference between a static and dynamic "include"? The static "include" is the result of an include directive and occurs during pag e translation of the jsp lifecycle. The dynamic "include" is the result of a sta ndard action tag occuring in teh body of the jsp. The two jsps are loaded separa tely and the results summed together at runtime. What are the different ways of handling a session? Cookies, URL rewriting, and the session object. What is the difference between XML, and HTML? Extensible Markup Language (XML) describes the data while Hypertext Markup Langu age(HTML) displays the data. How would you write a message back to the browser from inside a servlet? PrintWriter out = response.getWriter(); //Use out.println("...") to send content to the browser. sendRedirect() vs. getRequestDispatcher() sendRedirect does a CLIENT-side redirect, so the browser is instructed to fetch a different page instead of the one it requested. requestDispatcher does a SERVE R-side redirect or forward, so no network roundtrip is involved, but the new add ress needs to be accessible through the same servlet container.So you need to us e sendRedirect if the page is on a different server. servlets are programs that run on a Web or application server and act as a middle layer betwe en a request coming from a Web browser or other HTTP client and databases or app lications on the HTTP server. The job of a servlet 1.Read the explicit data sent by the client. 2. Read the implicit HTTP request d ata sent by the browser. 3. Generate the results. 4. Send the explicit data (i.e . the document) to the client. 5. Send the implicit HTTP response data. GET requests the usual type of browser requests for Web pages a browser generates a GET request when the user enters a URL on the address line, follows a link from a Web page, or su bmits an HTML form that either does not specify a METHOD or specifies METHOD="GE T" POST requests are generated when someone submits an HTML form that specifies METHOD="POST". scopes in a web application page, request, session, application 9 implicit objects in a JSP session, exception, application, config, request, response, out, page, pageConte xt

servlet equivalent of JSP implicit object: session HttpSession hs = request.getSession(); servlet equivalent of JSP implicit object: exception Exception e = new Exception(); servlet equivalent of JSP implicit object: application ServletContext servlet equivalent of JSP implicit object: config ServletConfig servlet equivalent of JSP implicit object: request HttpServletRequest servlet equivalent of JSP implicit object: response HttpServletResponse servlet equivalent of JSP implicit object: out PrintWriter out= response.GetWriter(); servlet equivalent of JSP implicit object: page unknown servlet equivalent of JSP implicit object: pageContext unknown page scope objects with page scope are accessible only within the page in which they're cre ated. The data is valid only during the processing of the current response; once the response is sent back to teh browser, the data is no longer valid. If the r equest is forwarded to another page or the browser makes another request as a re sult of a redirect, the data is also lost. Request scope objects with request scope are accessible from pages processing the same request in which they were created. Once the container has processed the request, the d ata is released. Even if the request is forwarded to another page, the data is s till available though not if a redirect is required. session scope objects with session scope are accessible from pages processing requsts that are in the smae session as the one in which they were created. A session is the tim e users spend using the application, which ends when they close their browser, w hen they go to another Web site, or when the application designer wants (aftera a logout, for instance). So, for example, when users log in, their username coul d be stored in teh session and displayed on every page they access. This data la sts until they leave the Web site or log out. application scope Objects with application scope are accessible from JSP pages that reside in the same application. This creates a global object that's available to all pages. Ap plication scope uses a single namespace, which means all your pages should be ca reful not to duplicate the names of application scope objects or change the valu es when they're likely to be read by another page (this is called thread safety) . Application scope variables are typically created and populated when an applic ation starts and then used as read-only for the rest of the application. four typical methods for session tracking cookies, URL Rewriting, hidden form fields, session objects what two arguments do doGet and doPost take? an HttpServletRequest and an HttpServletResponse what do you have to do to generate HTML with a servlet? 1. tell the browser that you're sending it HTML 2. Modify the println statements to build a legal Web page 3. Check your HTML with a formal syntax validator using a servlet, how do you tell the browser that you're sending it HTML? setting the HTTP Content-Type response header to text/html. In general, headers are set by the setHeader method of HTTPServletResponse, but setting the content type is such a common task that there is also a special setContentType method ju st for this purpose. The way to designate HTML is with a type of text/html, so t he code would look like this: response.setContentType("text/html"); what is the standard java solution for avoiding name conflicts? packages

when you put your sevlets in packages, you need to perform teh following two add itional steps 1. place the files in a subdirectory that matches the intended package name. 2. Insert a package statement in the class file. when the servlet is first created its init method is invoked, so init is where you put one--time setup code. once an init method is run, each user request results in a thread that calls the service method of the previously created inst ance. when a servlet is running, multiple concurrent requests normally result in multipe threads calling service simultaneously, although your servlet can implement a special interface (SingleThreadModel) that stipulates t hat only a single thread is permitted to run at any one time. The service method then calls doGet, doPost, or another doXxx method, depedning on teh type of HTT P request it received. each time the server recieves a request for a servlet, the server spawns a new thread and calls service. the service method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doP ost, etc., as apporpriate. a GET request results from a normal request for a URL or from an HTML form that has no METHOD specified. A POST request results from an HTML form that specifically lists POST as the METHOD. the init method is called when the servlet is first created, and not called again for each user request. the servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specif y that the servlet be loaded when the server is first started. the init method definition looks like: public void init() throws ServletException{ //initialization code} the init method performs two varieties of initializations general initializations and initializations controlled by initialization paramet ers general initialization, init simply creates or loads some data that will be used throughout the life of the s ervlet, or it performs some one-teim computataion. in principle, you can prevent multithreaded access by having your servlet implement the SingleThreadModel interface, as follows: publ ic class Yourservlet extends HttpServlet implements SingleThreadModel{ } if ACTION is omitted on a form the data is submitted to the URL of the current page to read a request (form) parameter you simply call the getParameter method of HttpServletRequest, supplying the cas e-sensitive parameter name as an argument. You supply the parameter name exactly as it appeared in the HTML source code, and you get the result exactly as the e nd user entered it; any necessary URL-decoding is done automatically. getParameter, if the parameter exists but has no value an empty String is returned (has no value i.e., the user left the corresponding textfield empty when submitting the form), and null is returned if there was no such parameter if the same parameter name might appear in teh form data more than once, you sho uld call getParameterValues(which returns an array of strings)instead of getParameter(whi ch returns a single string corresponding to the first occurrence of the paramete r.) getParameterNames returns a list of parameter names in the form of an enumeration, each entry of w hich can be cast to a String and used in a getParameter or getParameterValues ca

ll. if there are no parameters in teh current request, getParameterNames returns an empty Enumeration(not null) Enumeration is an interface that merely guarantees that the actual class will have hasMoreEleme nts and nextElement methods: there is no guarantee that any particular underlyin g data structure will be used. you should not count on getParameterNames returning the parameters in the order in which they appeared in the HTML form, s ince some common data structures (hash tables, in particular) scramble the order of the elements an alternative to getParameterNames is getParameterMap getParameterMap returns a map: the parameter names (strings are the table keys and the parameter values (string arrays as returned by the getParameterNames) are the table values rather than reading individual form parameters, you can access the query data di rectly by calling getReader or getInputStream on the HttpServletRequest and then using tha t stream to parse the raw input. Note, however, that if you read the data in thi s manner, it is not guaraneed to be available with getParameter. By default, request.getParameter interprets input using the server's current character set. To change the default , use the setCharacterEncoding method of ServletRequest. code using getParameterNames to read all parameters (in doRun) Enumeration paramNames = request.getParameterNemes(); while(paramName s.hasMoreElements()){String paramName = (String) paramNames.nextElement(); /* pr int or something */ Stringp[] paramValues = request.getParameterValues(paramName );... normally, when a servlet wants to generate HTML that will contain characters lik e < or >, it simply uses &lt; or &gt;, the standard HTML character entities. If a servlet wants a double wuote or an ampersand to appear inside an HTML attri bute value, it uses &quot; or %amp;/ whenever you perform concatenation within a loop to avoid the expense of generating and copying these temporary objects, you shou ld use a mutable data structure; and StringBuffer is the natural choice an ordinary Java object is considered to be a bean if the class uses private fields and has methods that follow the get/set naming con vention. an arbitrary Java class with a getName and a setName method is said to define a bean that has a property called name JSP pages are really servlets in disguise: each JSP page gets translated into a servlet, and it is th e servlet that runs at request time. generally, when integrating JSPs and servlets, it is often best to combine servlets and JSP pages in such a way that the servlets do the programmin g work and the JSP pages do teh presentation work. So, it is really more importa nt for servlets to be able ro read request parameters easily than it is for JSP pages to do so. populateBean takes a bean and a Map as input and passes all Map values ot the bean property t hat matches the assocated Map key name. This utility also does type conversion a utomatically, using default values (e.g. - for numeric values) instead of throwi ng exceptions when teh corresponding request parameter is malformed. If the bean has no property matching the name, the Map entry is ignored; again, no exceptio n is thrown. difference between form data and request headers Form data results directly from user input and is sent as part of the URL for GE

T requests and on a separate line ofr POST requests. Request headers, on the oth er hand, are indirectly set by the browser and are sent immediately following th e inital GET or POST request line. reading headers just call the getHeader method of HttpServletRequest with the name of the header . This call returns a String if the specified header was supplied in the current request, null otherwise. a few headers are so commonly used that they have special access methods in Http ServletRequest getCookies, getAuthType, getRemoteUser,(the last two break the Authorization hea der into its component pieces), getContentLength(returns int for Content-Length header value), getContentType(value of Content-Type header as a String), getDate Header, getIntHeader, getHeaderNames(Enumeration), getHeaders(Enumeration,use in stead of getHeaderNames for multiple occurences) four main methods to get information on the main request line itself getMethod, getRequestURI, getQueryString, getProtocol HTTP is a "stateless" protocol. Each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server does not automatically maintain contextual info rmation about the client. there are three typcial solutions to the session probl em cookies, URL rewriting, and hidden form fields URL Rewriting advantages works when browsers don't support cookies or when the user has disabled them URL Rewriting disadvantages URL rewriting has the same drawback as do cookies, namely, that the server-side program has a lot of straightforward but tedious processing to do. Even with a h igh-level API that handles most of the details for youj, you have to be very car eful that every URL that references your site and is returned to the user (even by indirect means like Location fields in server redirects) has the extra inform ation appended. This restriction means that you cannont have any static HTML pag es on your site (at least not any that have links back to dynamic pages at the s ite). So every page has to be dynamically generated with servlets or JSP. Even w hen all teh pages are dynamically generated, if the user leaves the session and comebs back via a bookmark or link, the session information can be lost because the stored link contains the wrong identifying information. Using sessions in servlets is straightforward and involves four basic steps: 1. Accessing the session object associated with the current request. 2. Looking up information associated with a session. 3. Storing information in a session. 4 . Discarding session data. session tracking, accessing the session object associated with the current reque st Call request.getSession to get an HttpSession object, which is a simple hash tab le for storing user-specific data. session tracking, Looking up information associated with a session Call getAttribute on the HttpSession object, cast the return value to the approp riate type, and check whether the result is null. session tracking, storing information in a sessiony Use setAttribute with a key and a value session tracking, discarding session data Call removeAttribute to discard a specific value. Call invalidate to discard an entire session. Call logout to log the client out of the Web server and invalida te all sessions associated with that user. session objects are of type HttpSession, but they are basically just hash tables that can store arbi trary user objects (each associated with a key). you look up the HttpSession object by calling the getsession method of HttpServletRequest, HttpSession session = reque st.getSession(); session request, behind the scenes

the system extracts a user ID from a cookie or attached URL data, then uses that ID as a key into a talbe of previously created HttpSession objects. But this is all done transparently to the programmer: you just call getSession. If no seesi on ID is found in an incoming cookie or attached URL information, the system cre ates a new, empty session. session request, if cookies are being used If cookies are being used (the default situation), the system also creates an ou tgoing cookie named JSESSIONID with a unique value representing the session ID. getSession timing Although you call getSession on the request, the call can affect the response. C onsequently, you are permitted to call request.getSession only when it would be legal to set HTTP response headers: before any document content has been sent (i .e., flushed or committed) to the client. If you plan to add data to the session regardless of whether data was there alre ady, getSession() (or, equivalently, getSession(true)) is the appropriate method call because it creates a new session if no session already exists. suppose you merely want to print out information on what is already in the sessi on It is wasteful to created a new session when no session exists already. So, you can use getSession(false), which returns null if no session already exists for t he current client. HttpSession objects live on the server; they don't go back and forth over the network; they're just autom atically associated with the client by a behind-the-scenes mechanism like cookie s or URL rewriting. session object structure session objects have a built-in data structure (a hash table) in which you can s tore any number of keys and associated values. look up a previously stored session value session.getAttribute("key"); the return type is Object, so you must do a typecas t to whatever more specific type of data was associated with that attribute name in the session. The return value is null if there is no such attribute, so you need to check for null before calling methods on objects associated with session s. representative sample of looking up information with a Session HttpSession session - request.getSession(); SomeClass value = (SomeClass) sessio n.getAttribute("someIdentifier"); if (value == null) {/* no such object already in session */ value = new SomeClass(...); session.setAttribue("someIdentifier", value);} do SomethingWith(value); you read infornmation associated with a session by using getAttribute To specify information associated with a session use setAttribute in general, session attributes merely have to be of type Object (i.e. they can be anything other than null or a primitve like int , double, or boolean). some application servers support distrubed Web applications in which an applicat ion is shared across a cluster of physical servers, what to do? Session tracking still needs to work, so the system needs to be able to move ses sion objects from machine to machine. You must make sure that session attributes implement the Serializable interface. When you are done with a user's session data, you have three options: remove only the data your sevlet created, delete the whole session (in the curre nt web application), log the user out and delete all sesssions belonging to him or her remove only the data your servlet created you can call removeAttribute("key") to discard the value associated with the spe cified key. This is the most common approach. delete the whole session (in the current Web application).

You can call invalidate to discard an entire session. Just remember that doing s o causes all of that user's session data to be lost, not just the session data t hat your servlet or JSP page created. So, all the servlets and JSP pages in a We b application have to agree on the cases for which invalidate may be called. discarding session data, log the user out and delete all sessions belonging to h im or her Finally, in servers that support servlets 2.4 and JSP 2.0, you can call logout t o log the client out of the Web server and invalidate all sesssions (at most one per Web application) associated with that user. Again, since this action affect s servlets other than your own, be sure to coordinate use of the logout command with the other developers at your site. methods available in the HTTPSession class getAttribute, getAttributenames (returns Enumeration), setAttribue(String name, Object value), removeAttribute, invalidate(), logout(),getId(), isNew(), getCrea tionTime(), getLastAccessedTime, getMaxInactiveInterval, setMaxInactiveInterval( int seconds) by default, session-tracking is based on cookies that are stored in teh browser's memory, not written to disk. Thus,, unl ess the servlet explicitly reads the incoming JSESSIONID cookie, sets the maximu m age and path, and sends it back out, quitting the browser results in the sessi on being broken: the client will not be able to access the session again. The problem with using session tracking with cookies in the browser is that the server does not know that the browser was closed and thus the server ha s to maintain the session in memory until the inactive interval has been exceede d. if you use URL rewriting for session tracking most or all of your pages will have to be dynamically generated. You cannot have any static HTML pages that contain hyperlinks to dynamic pages at your site. an example using encodeURL String original URL = someRelativeOrAbsoluteURL; String encodedURL = response.en codeURL(orignialURL); out.println("<A HREF=\"" + encodedURL + "\">...</A>"); encodeURL determines if URL rewriting is currently in use and appends the session informat ion only if necessary. The URL is returned unchanged otherwise JSP JavaServer Pages JSP technology enables you to mix regular, static HTML, with dynamically generated content. You simply write t he regular HTML in the normal manner, using familiar Web-page-building tools. Yo u then enclose the code for the dynamic parts in special tags, most of which sta rt with <% and end with %> JSP pages are translated into servlets, the servlets are compield, and at request time it is the complied serv lets that execute. So, writing JSP pages is really just another way of writing s ervlets. JSP with servlets provide the following benefits over servlets alone: it is easier to write and maintain teh HTML, you can use standard Web-site devel opment tools, you can divide up your development team. PHP a resursive acronym for PHP:Hypertext Preprocessor, is a free, open-source HTML -embedded scripting language that is somewhat similar to both ASP and JSP. some tasks are better accomplished by servlets than by JSP. JSP is good at generating pages that consist of large sections of fairly well st ructured HTML or other character data. Servlets are better for generating binary data, building pages with highly variable structure, and performing tasks (such as redirection) that involve little or no output. JavaScript which is completely distinct from the Java programming language, is normally use d to dynamically generate HTML on the client, building parts of the Web page as teh browser loads the document. This is a useful capability and does not normall

y overlap with the capabilities of JSP (which only runs on the server). jsp image files you do not need Java I/O to read image files; you just put the image in teh dire ctory for WEb resources (i.e., two levels up from WEB-INF/classes) and output a normal IMG tag. you create imgaes that change under the mouse by using client-side JavaScript, referned with the SCRIPT tag; this does not change just because the server is using JSP JSP and browsers Browsers do not "support" JSP at all- they merely see the output of the JSP page . So, make sure your JSP outputs HTML compatible with the browser, just as you w ould do with static HTML pages. JSP creation The JSP page is translated into a servlet and compiled only the first time it is accessed after having been modified. Loading into memory, initialization, and e xecution follow teh normal rules for servlets. JSP service method JSP pages use the _jspService method, (called for both GET and POST) requests) n ot doGet or doPost. JSP initialization method For initialization, JSPs use the jspInit method, not the init method. page first written, JSP page translated into servlet request 1 yes, request 2 no page first written, Servlet compile request 1 yes, request 2 no page first written, Servlet loaded into server's memory request 1 yes, request 2 no page first written, jspInit called request 1 yes, request 2 no page first written, _jspService called request 1 yes, request 2 yes server restarted, JSP page translated into servlet request 3 no, request 4 no server restarted, Servlet compiled request 3 no, request 4 no server restarted, servlet loaded into server's memory request 3, yes, request 4 no server restarted, jspInit called request 3 yes, request 4 no server restarted )jspService called request 3 yes, request 4 yes page modified, JSP page translated into servlet request 5 yes, request 6 no page modified, Servlet compiled request 5 yes, request 6 no page modified, Servlet loaded into server's memory request 5 yes, request 6 no page modified, jspInit called request 5 yes, request 6 no page modified, _jspService called request 5 yes, request 6 no Unlike JSPs, servlets require you to set you CLASSPATH, use packages to avoid name conflicts, install the class files in servlet-specific locations, and use special-purpose URLs. JSP pages can be placed in the same directories as normal HTML pages, ijmages, and style sheets; they ca n also be accessed thgrough URLs of the same form as those for HTML pages, image s, and style sheets for JSPs, where we list Some Directory, you can use any directory name you like, except that you are never allowed to use WEB-IN

F or META0INF as directory names. When using the default Web application, you al so have to avoid a directory name that matches the URL prefix of any other WEb a pplication. HTML comment HTML comment that is sent to eh client but not displayed by the browser <!--Blah --> template text text sent unchanged to the client. HTML text and HTML comments are just special cases of this. JSP comment Developer comment that is not sent to the client. <%-- Blah--> JSP Expression expression that is avaluated and sent to the client each time the page is reques ted. <%= Java value %> JSP Scriptlet statement or statements that are executed each time the page is requested. <% Ja va statement %> JSP declaration Field or method that becomes part of class definition when page is translated in to a servlet <%! Field Definition %> <%! Method Definition %> JSP Directive High-level information about the structure of the servlet code (page) code that is included at page-translation time (include), or custom tag libraries used (ta glib). <%@ directive att="val" %> JSP Action action that takes place when the page is requested. <jsp:blah>...</jsp:blah> JSP Expression Language Element Shorthand JSP expression ${ EL Expression } Custom Tag (Custom Action) Invocation of custom tag. <prefix:name> Body </prefix:name> Escaped Template Text Text that would otherwise be interpreted specially. Slash is removed and remaini ng text is sent to the client. <\% %\> there are two minor exceptions to the "template text is passed straight through" rule. First, if you want to have <% or %> in the output, you need to put <\% or %\> in the template text. Second, if you want a comment to appear in the JSP page but not in the resultant document, use <%-- JSP comment -->. HTML comments of the fo rm <!-- HTML Comment --> are passed through to the client normally. types of JSP Scripting Elements expressions, scriptlets, and declarations expression of the form <%= Java Expression %>, which are evaluated and inserted into the se rvlet's output Scriptlet of the form <% Java Code %>, which are inserted into the servlet's _jspService m ethod (called by service). Declarations of the form <%! Field/Method Declaration %>, which are inseted into the body of the servlet class, outside any existing methods. limit the amount of code that is in JSP pages. At the very least, use helper classes that are invoked from the JSP p ages. ONce you gain more experience, consider beans, MVC, and custom tags as wel l. Whenever you write Hava classes, the class files are deplyed in WEB-INF/classes/directoryMatchingPackageName( or inside a JAR file that is place d in WEB-INF/lib). This is true regardless of whether the clas is a servlet, a r egular helper class, a bean, a custom tag handler, or anything else. All code go es in the same place. A JSP expression is used to

insert values directly into the output. The expression is evaluated,, converted to a string, and inserted in the page. The JSP expression evaluation is performed at runtime(when the package is requested) and thus has full access to information a bout the request. Sample JSP expression: show the date/time the page was requested Current time: <%= new java.util.Date() %> (look into maybe using calendar) five important JSP expression predefined variables request, response, session, out, application JSP predefined variables, request the HttpServletRequest JSP predefined variables, reponse the HttpServletResponse JSP predefined variables, session the HttpSession associated with the request (unless disabled with the session at tribute of the page directive) JSP predefined variables, out the Writer (a buffered version of type JspWriter) used to send output to the cli ent JSP predefined variables, application the ServletContext. This is a data structure shared by all servlets and JSP page s in the Web application and is good for storing shared data. JSP expression basically become print (or write) statements in the servlet that results from teh JSP page. Where as regular HTML becomes print statements with double quotes around the text, JSP expression become print statements with no double quotes. Instead of being plac ed in the doGet method, these print statements are placed in a new method called _jspService that is called by service for both GET and POST requests. out is a JSP page is JspWriter XML authors can use the following alternative syntax for JSP expressions <jsp:expression> Java Expression </jsp:expression> JSP scriptlets let you insert arbitrary code into the servlet's _jspService method (which is called by service). Scriptlet's have the following form <% Java Code &> if an instance of the servlet does not exists, the web container a. loads the servlet class, b. creates an instance of the servlet class, c. init ializes the servlet instance by calling the init method. Scriptlets have access to the same automatically defined variables as do expression (request, response, se ssion, out, etc.). It is important to note that you need not set response headers or status codes a t the very top of a JSP page, even though this capability appears to violate the u rle that this type of response data needs to be specified before any document co ntent is sent to the client. It is legal to set headers and status codes after a small amount of document content because servlets that result from JSP pages us e a special variety of WRtier (of type JspWriter) that partially buffers the doc ument. This buffering behavior can be changed, however. how JSP scriptlets correspond to servlet code the scriptlet code is just directly inserted into the _jspService method: no str ings, no print statements, no changes whatsoever. JSP expressions contain Java values(which do not end in semicolons) JSP scriptlets contain Java statements, (which are terminated by semicolons.) to make it even easier to remember when to use a semicolon, simply remember that expressions get placed inside print or write statements, and out.print(blah;); i s clearly illegal the XML equivalent of <% Java Code %> is

<jsp:scriptlet> Java Code </jsp:scriptlet> JSP set the background color of the page <% string bgColor = request.getParameter("bgColor"); if ((bgColor == null) || (b gColor.trim().equals(""))) { bgColor = "WHITE"; } %> <BODY BGCOLOR ="<%= bgColor %>"> JSP print a coin flip message <% if (Math.random() < 0.5) { %> <h1>Heads</h1> <% } else { %> <h1>Tails</h1> <% } %> Overuse of this approach can lead to JSP code that is hard to undergstand and maintain. A JSP declaration lets you define methods or fields that get inserted into the main body of the servlet cla ss (outside the _jspService method that is called by service to process the requ est). A declaration has the following form <%! Field or Method Definition %> JSP declarations do not generate output declarations can contin anything that is legal to put inside a class definition but outsie any existing methods. In practice, however, declarations almost always contain field or metho d definitions. do not use JSP declarations to override the standard servlet life-cycle methods (service, doGet, init, etc). Th e servlet into which the JSP page gets translated already makes use of these met hods. There is no need for declarations to gain access to service, doGet, or doPost, since calls to service are automatically dispatched t o _jspService, which is where code resulting from expression and scriptlets is p ut. JSP, for initialization and cleanup you can use jspInit and jspDestroy, the standard init and destroy methods are guaranteed to call these two methods in servlets that come from JSP. for initialization and cleanup in JSP pages, use JSP declarations to override jspInit or jspDestroy, not init or destroy JSP, define methods define most methods with separate Java classes, not JSP declarations JSP declarations result in code that is placed inside the servlet class definition but outside the _jspService method. JSP, since fields and methods can be declared in any order, it does not matter whether the code from declarations goes at the top or bottom of the servlet. XML syntax for declarations The XML equivalent of <%! Field or Method Definition %> is <jsp:declaration> Fie ld or Method Definition</jsp:declaration> the following JSP snippet prints the number or times the current page has been r equested since the server was booted (or the servlet class was changed and reloa ded). A hit counter in two lines of code! <%! private int accessCount - 0; %> Acesses to page since server reboot: <%= ++a ccessCount %> multiple client requests to the same servlet result only in multiple threads calling the service method of a single servlet i nstance. They do not result in the creation of multiple servlet instances except possibly when the servlet implements the now-deprecated SingleThreadModel inter face. Instance variables (fields) of a normal servlet are shared by multiple requests are JSPs thread-safe? not always, so for values such as session identifiers, it is critical to have un ique values. One can use synchronized blocks to make them thread-safe. JSP, implementing a counter

A real hit counter would need to use jspInit and jspDestroy to read the previous count at startup and store the old count when the server is shut down. Even if you used jspDestroy, it would be possible for th server to crash unexpectedly (e .g., wehn a rolling blackout strikes Silicon Valley). So, you would have to peri odically write the hit count to disk. JSP changes the method from doGet to _jspService JSP uses what instead of a PrintWriter? JspWriter local variables in JSP expressions and scriptlets SEACRROPP: session, exception, application, config, request, response, out, page , pageContext. exception is only available in error pages JSP predefined variables, request This variable is the HttpServletRequest associated with the request; it gives yo u access to the request parameters, the request type (e.g., GET or POST), and th e incoming HTTP headers (e.g., cookies). JSP predefined variables, response This variable is the HttpServletResponse associated with the response to the cli ent. Since the output stream (see out) is normally buffered, it is usually legal to set HTTP status codes and response headers in teh body of JSP pages, even th ough the setting of headers or status codes is not permitted in servlets once an y output has been sent to the client. If you turn buffereing off, however, you m ust set status codes and headers before supplying any output. JSP predefined variables, out This variable is the Writer used to send output to the client. However, to make it easy to set response headers at variouis places in the JSP page, out is not t he standard PrintWriter but rather a buffered version of Writer called JspWriter . You can adjust the buffer size through use of the buffer attribute of the page directive. The out variable is used almost exclusively in scriptlets since JSP expressions are automatically placed in the output stream and thus rarely need t o refer tou out, explicitly. JSP predefined variables, session This variable is the HttpSeession object asociated with the request. Recall that sessions are created automatically in JSP, so this variable is bound even if th ere is no incoming session reference. The one exception is the use of the sessio n attribute of the page directive to disable automatic session tracking. In that case, attampts to refernce the session variable cause errors at the time the JS P page is translated into a servlet. JSP predefined variables, application This variable is the ServletContext as obtained by getServletContext. SErvlets a nd JSP pages can store persistent data in the ServletContext object rather than in sinstance variables. ServletContext has setAttribute and getAttirbute methods that let you stgore arbitrary data associated with specified keys. The differen ce between storing data in instance variables and storing it in the ServletConte xt is that the ServletContext is shared by akl servlets and JSP pages in the Web application, whereas, instance variables are available only to the same servlet that stored the data. JSP predefined variables, config This variable is the ServletConfig object for this page. In principle, you can u se it to read initialization parameters, but, in practice, initialization parame ters are read from jspInit, not from _jspService. JSP predefined variables, pageContext JSP introduced a class called PageContext to give a single point of access to ma ny of the page attributes. The PageContext class has methods getRequest, getResp onse, getOut, getSession, and so forth. The pageContext variable stores teh valu e of the PageContext object associated with the curreetn page. If a method or co nstructor needs access to multiple page-related objects, passing pageContext is easier than passing many separate references to request, response, out and so fo rth. JSP predefined variables, page

this variable is simply a synonym for this and is not very useful. It was create d as a placeholder for the time when the scripting language could be something o ther than Java. a JSP directive affects the overall structure of the servlet that results from teh JSP page. in JSP, there are three main types of directives page, include, and taglib the page directive lets you control the structure of the servlet by importing classes, customizing the servl et superclass, setting the content type, and the like. A page directive can be placed anywhere within the document the second directive, include, let you insert a file into the JSP page at the time the JSP file is translated into a se rvlet. An include directive should be placed in the document at the point at which you want the file to be inserted the third directive, taglib, defines custom markup tags the page directive lets you define one or more of the following case-sensitive a ttributes(listed in approximate order of frequency of use): import, contentType, pageEncoding, session, isELIgnored, buffer, autoFlush, info , errorPage, isErrorPage, isThreadSafe, language, and extends. The import attribute of the page directive lets you specify the packages that should be imported by the servlet into which the JSP p age gets translated. Using separate utility (helper) classes makes your dynamic code easier to write, maintain, debug, test, and reuse. when you use utility classes, remember that they should always be in packages. Packages are a good strategy on any larg e project because they help protect against name conflicts. With JSP, however, p ackages are absolutely required. The reason is that, in the abscence of packages , classes you reference are assumed to be in the same package as teh currect cla ss. by default, the servlet imports java.lang.*, javax.servlet.*, javax.servlet.jsp.*, javax.servlet.http.*, and pos sibly some number of server-specific entries. Never write code that relies on any server specific classes being imported automatically; doing so makes your co de nonportable. Use of the import attribute takes one of the following two forms: <%@ page import="package.class" %> <%@ page import="package.class1,...,package.c lassN" %> The import attribute is the only page attribute that is allowed to appear multiple times within the same document. Although page directives can appear anywhere within the document, it is traditional to place import statements either neaqr the top of the documen t or just before the first place that the referenced package is used. Note that, although the JSP pages go in the normal HTML directories of the serve r, the classes you write that are used by JSP pages must be placed in the special J ava-code directories (e.g., ...WE-B-INF/classes/directoryMatchingPackageName). page import ArrayList <%@ page import="java.util.*" %> the contentType attribute set the Content-Type response header, indicating the MIME type of the document b eing sent to teh client. use of the contentType attribute takes one of the two following forms: <%@ page contentType="MIME-Type" %> <%@ page contentType="MIME-Type; charset=Cha racter-Set" %> page contentType microsoft excel

<%@ page contentType="application/vnd.ms-excel" %> which has the same basic effe ct as the scriptlet <% response.setContentType("application/vnd.ms-excel"); %> difference between directives and scriptlets directives are parsed specially, they dno't directly become _jspService code at the location at which they appear. This means that response.setContentType can b e invoked ocnditionally whereas the page directive cannot be. Setting the conten t type conditionally is useful when the same content can be displayed in differe nt forms regular servlet default MIME type text/plain JSP default MIME type text/html with a default character set of ISE-8859-1. Thus JSP pages that output HTML in a lating character set need not use contentType at all. If you want to change both the content type and the cahracter set, you can do th e following <%@ page contentType="someMimeType; charset=someCharacterSet" %> However, if you only want to change the character set, it is simpler to use the pageEncoding at tribute. For example, Japanese JSP pages might use the following: <%@ page pageE ncoding="Shift_JIS" %> the session attribute controls whether the page participates in HTTP sessions. Use of the session attribute takes one of the following two forms: <%@ page session="true" %> <%-- Default --%> <%@ page session="false" %> page session attribute: a value of true (the default) signifies that the predefined variable session (of type HttpSession) should be bound to the exi sting session if one exists; otherwise, a new session should be created and boun d to session. page session attribute: a value of false means that no sessions will be automatically created and that attempts to access the variable session will result in errors at the time the JSP page is translat ed into a servlet. Using session="false may save significant amounts of server memory on high-traffic sites. However, note t hat using session="false" does not disable session tracking-it merely prevents t he JSP page from creating new sessions for users who don't have them already. So since sessions are user specific, not page specific, it doesn't do any good to turn off session tracking for one page unless you also turn it off for related p ages that are likely to be visited in the same client session. the isELIgnored attribute controls whether the JSP 2.0 Expression Language (EL) is ignored (true) or evalu ated normally (false). it is illegal to use it in a server that supports only JS P 1.2 or earlier. The buffer attribute specifies the size of the buffer used by the out variable, which is of type JspWriter the out variable is of type JspWriter The use of the buffer attribute takes one of two forms <%@ page buffer="sizekb" %> <%@ page buffer="none" %> Servers can use a larger buffer than you specify, but not a smaller one. <%@ page buffer="32kb" %> means the document content should be buffered and not sent to the client until at leas t 32 kilobytes are accumulated, the page is completed, or the output is explicit ly flushed (e.g., with response.flushBuffer). the default buffer size is server specific, but must be at least 8 kilobytes be cautious about turning off buffering; doing so requires JSP elements that set headers or status codes to ap pear at the top of the file, before any HTML content. On the other hand, disabli ng buffering or using a small buffer is occasionally useful when it takes a very

long time to generate each line of the ouitput; in this scenario, users would s ee each line as soon as it is ready, rather than waiting even longer to see grou ps of lines. the autoflush attribute controls whether the output buffer should be automatically flushed when it is full(the de fault) or whether an exceptino should be raised when the buffer overflows (autof lush="false"). Use of the autoFlush attribute takes one of the following two forms <%@ page autoFlush="true" %> <%-- Default --%> < %@ page autoFlush="false" %>

Você também pode gostar