Servlet JSP (TOP)

Source: Internet
Author: User
Tags throwable

JSP is the same as the servlet nature. JSP is embedded in the Java code in html, the servlet is embedded in the Java code HTML.

After Tomcat gets the JSP page, in the work directory, it converts it to the Servlet's Java file (such as hello.jsp--->hello_jsp.java), and then compiles it, where the various parts of the JSP function are analyzed, Note that it is converted to a code structure in the Servlet. _jspservice in Hello_jsp.hava (final javax.servlet.http.HttpServletRequest request, Final Javax.servlet.http.HttpServletResponse Response) method is equivalent to the service in the servlet (javax.servlet.http.HttpServletRequest request, Final Javax.servlet.http.HttpServletResponse response).

--------------------------------------------------------------------------------------------------->

JSP scripting elements

Expression: <%= expression%> Output The expression result to the browser, the underlying parsing out.print (expression);
Code snippet: <% Java code%> full copy of "java code" into the service method Body. Service () {java Code fragment}
Script Declaration: <%! Declare content%> copy the "declared content" into the class class body, class Hello {script declaration}

<body>    Hello again!    <br>    <%=i%>    int5%>    <%=i%>     int  Ten; %>    i++    %><%= this .i%></body>

Here <%! %> is declared, so that i=10 is a member variable in Hello_jsp.java code, and <% int i = 5;%> is moved directly to _jspservice (httpservletrequest, Httpservletresponse) method body, So it belongs to a local variable, and the contents of <%=%> are output in the move to the method body with Out.print ().

--------------------------------------------------------------------------------------------------->

Comments in the JSP <%----%>, and the contents of the comments section in the Java source code will not Exist.

--------------------------------------------------------------------------------------------------->

JSP directives

JSP in the Web container is converted to servlet, file encoding, dependency class, Send to the browser output encoding, behavior, etc. need JSP page and Tomcat contract, This is based on JSP Instructions. The format of the directive is: <%@ directive Name attribute = value Attribute = value ...%>, directive has three, page, include, taglib.

<% @page Property = Value Property = value .....%>

> Use
* One instruction can write multiple properties
* Same instruction can be used multiple times
* Instructions can be used in any position
* Most properties can only be used once, otherwise the JSP throws an Exception. Then a few can be reused. For example: Import

> Coding

Pageencoding: encoding of the current page
Contenttype:jsp generate servlet response to browser encoding
Note: General Consistency
Contrast:
If only pageencoding, set the current encoding, you can also set the response encoding
If only contenttype, you can set the response encoding, you can also set the current page encoding

> Caching mechanisms

Buffer: Set Cache size, default: 8kb
Autoflush: if the cache overflows, it will automatically refresh, often set to true, and set false with the possible exception: Java.io.IOException:Error:JSP Buffer Overflow

> Common

Session: indicates whether the current JSP page can use the session built-in Object. True: you can use the session in a JSP script (expression, code Block)
Import:jsp use other classes to guide the Package. Import separately: java.util.List disposable import: java.util.list,java.util.arraylist asterisk: java.util.*
Language: indicates that the JSP supports embedded language (java)
info, using the 5th method on the servlet interface, getservletinfo ()

> Error handling mechanism

Set <%@ page errorpage= "error.jsp"%> on each display page, when the page error occurs, jumps to the JSP page, sets error.jsp page <%@ "true" in iserrorpage= > can refer to the exception object, get the cause of the error, and be flexible with its contents, like <%=exception.getmessage ()%>. When an error occurs on the page, the Chrome browser accesses it, and you can see that it causes the error and the page content to be printed to the Browser. however, IE browser will appear because the status code of the server response is 500,ie browser will give its own error page, you can use the filter to process it.

In general, we will be a unified page configuration, the entire project to make a friendly error page. The configuration in Web. XML is as Follows:

......     <error-page>        <exception-type></exception-type>        <location></location>    </error-page></web-app>

Looking at Error-page's instructions, it can be found that this tag requires two content, error definition and location, and there are two kinds of error definitions:

element:error-pagethe Error-page element contains a mapping between an error code or exception type to the< c2/>in: web-appcontent Model: ((error-code | exception-type), location)

The contents of these parameters are ((error code (status code) |java Exception type), friendly page location).

Taglib instructions after the special summary

Here is a summary of the usage and scenario of the <%@ include%> Directive.

In many portals, often a page will be cut into a lot of pieces, different developers will be different fast processing, but the whole page will also have a lot of public resources, such as frames, various links and so on, the same layout and content will be placed in a lot of separate sub-modules, if the submodule processing these public content, There is no doubt that the volume of the project is huge, and error-prone, not easy to expand, so we will make it a separate interface, and then refer to each of the required Sub-modules to reference the Interface. This interface is equivalent to merging the interface with the submodule, so this instruction is mainly about merging Work.

Here the merger is divided into two kinds, a static containing <% @include file= ""%>, and the other is dynamically including <jsp:include page= "" >. The former process is a.jsp contains b.jsp,tomcat will merge A and bjsp together, generate a A_jsp.java file, then compile, and finally run, the result is: ab merge (a servlet), so two pages in the processing of variables need attention; The latter process is a.jsp contains b.jsp, tomcat generates A A_jsp.java file, B generates B_jsp.java files, compiles separately, and outputs the content at run Time. Result: AB Merge (two servlets).

--------------------------------------------------------------------------------------------------->

JSP built-in objects

The so-called built-in object, a variable that can be directly used directly in <%=%> and <%%>, is the variable provided in _jspservice (httpservletrequest, httpservletresponse), looking at the Code:

   public void_jspservice (FinalJavax.servlet.http.HttpServletRequest request,FinalJavax.servlet.http.HttpServletResponse Response)throwsjava.io.IOException, javax.servlet.ServletException {FinalJavax.servlet.jsp.PageContext pagecontext; Javax.servlet.http.HttpSession Session=NULL; Java.lang.Throwable Exception=org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable (request); if(exception! =NULL) {response.setstatus (javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); }    FinalJavax.servlet.ServletContext application; FinalJavax.servlet.ServletConfig config; Javax.servlet.jsp.JspWriter out=NULL; FinalJava.lang.Object page = this; Javax.servlet.jsp.JspWriter _jspx_out=NULL; Javax.servlet.jsp.PageContext _jspx_page_context=NULL; ......

Page represents the current page, this reference.
Config indicates servlet configuration, type: servletconfig
Application represents the Web App context, type: ServletContext

The request represents a demand, type: httpservletrequest
Response represents one response: type: httpservletresponse

Session represents a conversation, type HttpSession
Out represents the output response body, type JspWriter

Exception indicates an exception occurred, type Throwable
PageContext represents the JSP page context (jsp manager) type: PageContext

Where page refers to the current page (a page); request, one time (the default is a page, if you can use a request to forward multiple pages); session, a conversation (can have multiple requests), application, an application (can be multiple sessions). The main view here is JspWriter and Pagecontext. We print out the object, we know:

[email protected]

Find the source in tomcat, view the write () in the method, and finally view the Initout ():

    Private void throws IOException {        ifnull) {            = response.getwriter ();        }    }

So the bottom layer here uses response.getwriter () to get the out object, which has been explained in the previous Servlet's detailed usage, which is skipped here.

In addition, there is a cache problem. Look at the code in the Page:

......     <br>    <%= out%>    <%        out.print ("111");        Out.print ("2222");        Response.getwriter (). Print ("3333");     %></body>

This code will be placed directly into the Hello_jap.java and then unified in the page according to the code logic output, but in fact, we look at the page source:

3333<!DOCTYPE HTML public "-//w3c//dtd HTML 4.01 transitional//en" "http://www.w3.org/TR/html4/loose.dtd "><HTML><Head><Metahttp-equiv= "content-type"content= "text/html; charset=utf-8"><title>Insert Title here</title></Head><Body>Hello again! <BR>Ten 5<BR>[email protected] 1112222</Body></HTML>

The contents of Request.getwriter (). print () are placed at the front of the Page. The reason is that the JSP is not consistent with the servlet cache (jspwriter<->response.getwriter ()), each has its own cache, the out content is first placed in the JSP cache, and Request.getwriter ( Output in the servlet cache, until finally, the servlet will output its own cache and JSP cache content to the page, resulting in this Situation. Knowing this principle, we can use Out.flush () to flush the contents of the JSP cache into the servlet cache and then store 3333 directly into the servlet when the JSP request.getwriter () all the content before it is written to the Cache. The Re-output is the display of the Code's logical sequence.

......    <BR>    <%= out%>    <%Out.print ("111"); Out.print ("2222");        Out.flush (); Response.getwriter (). Print ("3333"); %></Body>

PageContext is a JSP page manager, you can use getxxx () to get the other 8 object references; you can quickly manipulate the value of a specified scope property:

The default Scope property operates: page    getattribute (name)  obtains page scope data    SetAttribute (name, Value) to the    page scope settings content    RemoveAttribute (name)  Removes the contents of all scopes (page/request/session/application) specifies the scope    getattribute (name, Scope)  Gets the specified scope data    setAttribute (name, value, Scope)    to the specified scope set content    removeattribute (name, Scope)  Removes the contents of the specified scope (page/request/session/application) provides scope constants    Pagecontext.page_scope  page    Pagecontext.request_scope  REQUEST    pagecontext.session_scope  SESSION    Pagecontext.application_scope  Application

--------------------------------------------------------------------------------------------------->

JSP Action Tags

Here is the code in the actual scenario, which you can read:

<Jsp:includepage="" />Dynamic Inclusion<Jsp:forward/>forwarding<Jsp:param/>Processing the request parameters, the Chinese content can be url-encoded, similar to<formenctype= "application/x-www-form-urlencoded"><Jsp:includepage= "/error.jsp">    <Jsp:paramvalue= "uservalue"name= "username"/></Jsp:include><Jsp:usebeanID= "user"class= "com.itheima.User"></Jsp:usebean>  <%--User User= NewUser (); Pagecontext.setattribute ("User", User)--%><Jsp:setproperty property= "username"name= "user"value= "jack"/><%--User.setusername ("Jack") --%><Jsp:getproperty property= "username"name= "user"/><%--user.getusername ()--%>

Servlet JSP (TOP)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.