1. JSP origin
(1) In many dynamic Web pages, most of the content is fixed, only the local content needs to be dynamically generated and changed.
(2) If the servlet program is used to output a page that only the local content needs to be dynamically changed, and all the static content needs to be generated by the programmer in Java program code, the entire Servlet program code will be very bloated, writing and maintenance will be very difficult.
(3) The design of a large amount of static content and the writing of related HTML statements is not the work that programmers do, and programmers are not necessarily good at it. Web design and production staff do not understand the Java programming, is not able to complete such work.
(4) To compensate for the shortcomings of the servlet, Sun has introduced the JSP (Java Server Pages) technology as a solution based on the servlet.
(5) JSP is a technology to simplify the servlet writing, it mixes the Java code and HTML statements in the same file, only the content to be dynamically generated in the Web page is written in Java code, and fixed static content with a normal static HTML page of the way to write.
2, establish the intuitive understanding of JSP
(1) A JSP page is an ordinary text file consisting of an HTML statement and a nested Java code, and the JSP page must have a. jsp file name extension.
(2) Java code written in JSP pages needs to be nested in <% and%>, and Java code nested between <% and%> is called a script fragment (Scriptlets), not nested in <% and%> The content between is called the JSP template element.
(3) Java code in the JSP can use the OUT.PRINTLN statement to output the resulting string generated by other Java program code to the client, or you can use the SYSTEM.OUT.PRINTLN statement to print them to a command-line window.
(4) JSP files, like normal HTML files, can be placed in any directory other than Web-inf and its subdirectories in the Web application, and the access path to the JSP page is exactly the same as that of the normal HTML page.
(5) In the JSP page can also use a kind of called JSP expression elements, only the variables or expressions to be exported directly into the <%= and%>, you can output to the client this variable or expression of the results of the operation. A variable or expression nested within a JSP expression cannot have a semicolon after it.
3, the operation Principle of JSP
(1) When a Web container (servlet engine) receives a request for access to a URL with a. jsp extension, it will hand over the access request to the JSP engine for processing.
(2) Each JSP page is accessed for the first time, the JSP engine translates it into a servlet source program, and then compiles the servlet source program into a servlet class file. The Web container (servlet engine) is then loaded and interpreted in the same way as a normal servlet program to execute the servlet program translated by the JSP page.
(3) The JSP specification does not explicitly require that the script code in the JSP must be in the Java language, the script code in the JSP can be written in a scripting language other than the Java language, but the JSP page must eventually be converted to a Java servlet program.
(4) You can pre-compile all of the JSP pages in a servlet program before the Web application is officially published.
4. Example
(1) Create a new hello.jsp
(2) compiling into a servlet program
(3) View Hello_jsp.java
(4) at Eclipse Press Ctrl+t to view the Httpjspbase class, as you can see, it also inherits from the HttpServlet
Public abstract class Httpjspbase extends HttpServlet implements Httpjsppage {private static final long Serialversionu ID = 1L; Protected httpjspbase () {} @Override public final void init (ServletConfig config) throws Servletexception {super.init (config); Jspinit (); _jspinit (); } @Override Public String Getservletinfo () {return localizer.getmessage ("Jsp.engine.info"); } @Override public final void Destroy () {Jspdestroy (); _jspdestroy (); } @Override Public final void service (HttpServletRequest request, httpservletresponse response) throws Servle Texception, IOException {_jspservice (request, response); } @Override public void Jspinit () {} public void _jspinit () {} @Override public void Jspdestroy () { } protected void _jspdestroy () {} @Override public abstract void _jspservice (HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException;}
? 5, JSP implicit object
Implied variables for JSP pages: an object that can be used without a declaration. There are 9 hidden objects in the JSP page.
Code written with <%%> in this position, you can use Request,response, pagecontext,session,application,config,out,page these 8 hidden objects. (You can actually use an implicit object called exception.)
An object of ①. Request:httpservletrequest.
②. Response:httpservletresponse an object (any method of response is rarely called in a JSP page.)
③. PageContext: The context of the page, which is an object of PageContext. You can get the other 8 hidden objects from this object. You can also get additional information from the current page. (Use it when learning custom labels)
④. Session: A conversation that represents a browser and a server, which is an object of HttpSession. Learn more later.
⑤. Application: Represents the current WEB app. is a ServletContext object.
⑥. config: The ServletConfig object (almost unused) of the Servlet corresponding to the current JSP. If you need to access the initialization parameters of the current JSP configuration, you need to pass the mapped address. Mapping JSPs
⑦. Out:jspwriter object. Call Out.println () to print the string directly to the browser.
⑧. Page: A reference to the Servlet object corresponding to the current JSP, but for type object, only methods of the object class are called (hardly used)
⑨. Exception: can only be used if the iserrorpage= "true" of the page directive is declared. *<%@ page iserrorpage= "true"%>
6. The application comparison between JSP and Servlet
(1) JSP is a Web development technology centered on generating Web page display content, it can directly use template element to produce the content of Web document.
(2) The JSP page source file is simpler than the servlet source file, and the JSP page development process is much simpler than the servlet development process.
(3) The JSP engine can detect the modification of JSP pages and automatically re-translate and compile the modified JSP files.
(4) JSP technology is based on the servlet technology, all JSP pages will eventually be converted into Servlets to run.
(4) in the development of large-scale Web applications, Servlets and JSPs are often mixed, their roles are common, servlets are often used as control components, and some complex background services are handled, and JSPs are used as display components.
(5) A response process can be divided into several functional modules to work together, first by the servlet to complete the process control and business processing, and to store the result data in the request or session domain, and then forward the request (forward) to the JSP page, The JSP page then extracts the result data from the request or Session field and completes the output of the response content. This approach separates the business logic from the display content, separating the application developer from the work of the Web page author.
7, JSP basic Syntax 7.1, JSP template elements
(1) The static HTML content in the JSP page is called the JSP template element, and in the static HTML content can nest various other elements of JSP to produce dynamic content and execute business logic.
(2) The JSP template element defines the basic skeleton of a Web page, which defines the structure and appearance of the page.
7.2. JSP expression
The JSP expression provides a simplified way of outputting the results of a Java variable or expression to the client, and it encapsulates the variables or expressions that will be output directly in <%= and%>.
Example: Current time: <%= new Java.util.Date ()%>
(1) The result of a variable or expression in a JSP expression is converted to a string and then inserted into the corresponding location of the output of the entire JSP page.
(2) The variable or expression in the JSP expression cannot be followed by a semicolon (;), and the JSP expression is translated into a out.print (...) in the servlet program. Statement.
7.3. JSP Script Fragment
(1) JSP script fragment (scriptlet) refers to one or more Java program code nested within <% and%>.
(2) in the JSP script fragment, you can define variables, perform basic program operations, invoke other Java classes, access the database, access the file system and other common Java programs can be implemented by the functions.
(3) The JSP script fragment can use the implicit object provided by JSP directly to complete the functionality unique to the Web application.
(4) The Java code in the JSP script fragment will be moved into the _jspservice method of the servlet translated by the JSP page intact, so the JSP script fragment can only be the program code that conforms to the Java syntax requirements, in addition to any text, HTML tags, Other JSP elements must be written outside of the script fragment.
(5) Java code in the JSP script fragment must strictly follow the Java syntax, for example, each command execution statement must end with a semicolon (;).
(6) There can be multiple script fragments in a JSP page (each script fragment code is nested between separate pairs of <% and%>), text, HTML tags, and other JSP elements can be embedded between two or more script fragments, and code in multiple script fragments can be accessed from one another.
(7) The Java statements in a single script fragment can be incomplete, but the result of a combination of multiple script fragments must be a complete Java statement.
7.4. JSP declaration
(1) JSP declaration encapsulates Java code in <%! And%>, the code inside it will be inserted outside the servlet's _jspservice method, so the JSP declaration can be used to define the static code blocks, member variables, and methods of the servlet program that the JSP page translates into.
(2) Multiple static code blocks, variables, and functions can be defined in a JSP declaration or individually in multiple JSP declarations.
(3) JSP implicit objects are scoped to the _jspservice method of the servlet, so these implicit objects cannot be used in JSP declarations.
7.5. JSP annotations
<%--JSP Comment--%>
The difference: JSP annotations can block the execution of Java code, and HTML comments are not allowed.
8. Properties-related methods
1). method
void SetAttribute (String name, Object o): Setting properties
Object getattribute (String name): Gets the specified property
Enumeration Getattributenames (): Gets all the names of the properties of the enumeration object
RemoveAttribute (String name): Removes the specified property
2). PageContext, request, session, application objects all have these methods!
These four objects are also called domain objects.
PageContext: The scope of the property is limited to the current JSP page
Request: The scope of the property is limited to the same request.
Session: The scope of the property is limited to one conversation: The browser opens until it is closed as a session (session is not invalidated during this time)
Application: The scope of the property is limited to the current WEB application. is the largest range of property scopes, as long as the property is set in one place and can be obtained in a JSP or Servlet everywhere.
attr_1.jsp
attr2.jsp
After you close the browser, access the Attr_2.jsp,session property value disappears
9. Forwarding and redirection of requests 9.1, RequestDispatcher interface
(1) The RequestDispatcher instance object is created by the Servlet engine, which wraps a resource to be called by another resource (for example, a servlet, HTML file, JSP file, and so on), and through which the client's request can be forwarded to the wrapped resource.
(2) The RequestDispatcher interface defines two methods: The forward method and the include method.
(3) The two parameters received by the forward and include methods must be the two ServletRequest and Servletresponse objects that are passed to the service method of the current servlet. Or a servletrequestwrapper or Servletresponsewrapper object that has been packaged for them.
(4) How to get the RequestDispatcher object:
Servletcontext.getrequestdispatcher (parameter can only be a path beginning with "/")
Servletcontext.getnameddispatcher
Servletrequest.getrequestdispatcher (parameter can be a path that does not start with "/")
9.2, using the Sendredirect method to achieve request redirection
(1) The Sendredirect method can redirect not only to other resources in the current application, but also to resources in other applications at the same site, even to resources that are redirected to other sites using absolute URLs.
(2) If the relative URL passed to the Sendredirect method begins with "/", it is relative to the root of the entire Web site, not to the root directory of the current Web application.
9.3. Comparison of request redirection and request forwarding
(1) The Requestdispatcher.forward method can only forward requests to components in the same Web application, while the Httpservletresponse.sendredirect method also redirects to resources in other applications at the same site , even resources that are redirected to other sites using an absolute URL.
(2) If the relative URL passed to the Httpservletresponse.sendredirect method begins with "/", it is relative to the root of the entire Web site, and the relative URL specified when the RequestDispatcher object is created starts with "/" , which is relative to the root directory of the current Web application.
(3) After the access process that calls the Httpservletresponse.sendredirect method redirects, the URL displayed in the browser address bar changes, and the initial URL address becomes the redirected destination URL; call Requestdispatcher.forward The browser address bar keeps the initial URL address intact after the request-forwarding process for the method is completed.
(4) The Httpservletresponse.sendredirect method responds directly to the request of the browser, and the result of the response is to tell the browser to re-issue the access request to another URL; The Requestdispatcher.forward method forwards the request internally on the server side To another resource, the browser only knows that a request has been made and has responded to the result, and does not know that a forwarding behavior has occurred inside the server program.
(5) The caller and the callee of the Requestdispatcher.forward method share the same request object and the response object, which belong to the same access request and response procedure, while the Httpservletresponse.sendredirect method calls And the callee use their respective request objects and response objects, which belong to two separate access request and response procedures.
Example:
Example 2:
Essential difference: The forwarding of the request only makes one request, while the redirect makes two requests.
Javaweb (vi) JSP-1