Javaweb review article 7 jsp and javaweb Article 7 jsp

Source: Internet
Author: User

Javaweb review article 7 jsp and javaweb Article 7 jsp
1: Why does JSP exist?

Jsp full name (java server pages) is called a java server Page in Chinese. In Servlet, we found that Servlet can generate dynamic pages, but we have written a lot of html tags in Servlet, in addition, in Servlet, We have to mix a large number of static display content and dynamic production content, making it impossible for our webpage editors and programmers to develop together, which will greatly increase the development efficiency, some people may say why ajax is not needed, because there was no ajax at that time. To overcome these problems, SUN released JSP.

2: JSP Operating Mechanism

Let's first write a very simple jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

This is a very common jsp. If we open the tomcat server and enter http: // localhost: 8080/jsp-test/index. jsp on the server, it will display Hello Jsp.

Of course, this is not my point. Then we open the compiled jsp file (located in. metadata \. plugins \ org. eclipse. wst. server. core \ tmp0 \ work \ Catalina \ localhost \ jsp-test \ org \ apache \ jsp) contains two files: index_jsp.java and index_jsp.class. These two files are generated by the jsp (web) container when we access jsp. Now let's take a look at the content of index_jsp.java.

package org.apache.jsp;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.*;public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase    implements org.apache.jasper.runtime.JspSourceDependent {  private static final javax.servlet.jsp.JspFactory _jspxFactory =          javax.servlet.jsp.JspFactory.getDefaultFactory();  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;  private javax.el.ExpressionFactory _el_expressionfactory;  private org.apache.tomcat.InstanceManager _jsp_instancemanager;  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {    return _jspx_dependants;  }  public void _jspInit() {    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());  }  public void _jspDestroy() {  }  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)        throws java.io.IOException, javax.servlet.ServletException {    final javax.servlet.jsp.PageContext pageContext;    javax.servlet.http.HttpSession session = null;    final javax.servlet.ServletContext application;    final javax.servlet.ServletConfig config;    javax.servlet.jsp.JspWriter out = null;    final java.lang.Object page = this;    javax.servlet.jsp.JspWriter _jspx_out = null;    javax.servlet.jsp.PageContext _jspx_page_context = null;    try {      response.setContentType("text/html; charset=UTF-8");      pageContext = _jspxFactory.getPageContext(this, request, response,                  null, true, 8192, true);      _jspx_page_context = pageContext;      application = pageContext.getServletContext();      config = pageContext.getServletConfig();      session = pageContext.getSession();      out = pageContext.getOut();      _jspx_out = out;      out.write("\r\n");      out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");      out.write(");  out.print("Hello Jsp");      out.write("\r\n"); out.write("</body>\r\n"); out.write("); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { out.clearBuffer(); } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }}

I believe everyone is familiar with this page. May I say this is not a Servlet? We can understand it as a dynamic Servlet. Among them, _ jspInit, _ jspService, and _ jspDestroy correspond to init, service, and destroy in Servlet respectively. They have the same functions, its advantages are obvious, so we don't need to write the above Code in Servlet. This accelerates the development efficiency. In this way, we can easily understand the jsp generation process. For example

Next, let's analyze the differences between Servlet and Jsp.

1: Jsp needs to be compiled into Servlet for the first time (only once)

2: Jsp is a Java and HTML file that can be combined into a. jsp file, and Servlet is directly separated from Html.

3: different focuses. SP focuses on views. Servlet is mainly used for control logic.

3: JSP syntax 3.1: command element

Command element: it is mainly used to provide information about the entire jsp page during the conversion phase, the command element does not generate any output to the current output stream (to put it bluntly, it defines some JSP-related information)

3.1.1: page command

The page command acts on the entire jsp page and defines many page-related attributes. Let's take a look at these attributes.

This code is often generated on the jsp page.<% @ Page language = "java" contentType = "text/html; charset = UTF-8"

PageEncoding = "UTF-8" %>

The preceding attributes are the directive elements.Language indicates the development language,ContentType indicates the text type,Charset andPageEncodingIndicates the encoding format.

After converting jsp into Servlet, we can find it in the _ jspService method.Response. setContentType ("text/html; charset = UTF-8"); then let's look at other directive Elements

<% @ Page import = "" %> This is the class for importing java and the function of referencing classes in development is the same, the Servlet generated after this command element is added will be imported into this class.

<% @ Page isELIgnored = "true" %> many parameters are used to determine whether to enable EL expressions. If the expression is set to Servlet2.3 or earlier, the default value is true. If the expression is set to 2.4 or later, the default value is false.

<% @ Page session = "true" %> whether to start the Session. If it is false, the Session in this jsp is invalid. The default value is true.

<% @ Page errorPage = "" %> the error page pointed to after an error occurs. In this case, the web. xml configuration is invalid.

<% @ Page isErrorPage = "false" %> specifies whether the JSP is an error page of another page. The default value is false.

<% @ Page buffer = "8kb" %> specify the size of the buffer used by the out object. The default value is 8 KB, and none means no buffer is set.

Of course, there are some command elements that you can refer to. Remember that the scope of these command elements is only the current page.

3.1.2: include command

From the literal meaning, we know that include is the meaning of include. So what is the meaning of this directive element? It is mainly used to include a static file in the JSP page. This file can be an html file, a jsp page, a text file, and a piece of java code. Let's take a look at the running results.

First write a simple jsp page

1 

Then we reference it in index. jsp.

1 <%@ include file="myinclude.jsp" %>

The running result is as follows:

If you want a piece of code, modify myinclede. jsp to the following:

1 <% @ page import = "java. util. * "%> 2 

The running result here is as follows:

3.1.3: taglib command

This command is used to customize tags.

Tablib has three attributes: uri, tagdir, and prefi, which will be described in detail in future custom tags (for a moment)

3.2: script Element

The script element consists of three parts: Declaration, script segment, and expression.

3.2.1: Declaration

This is the same as declaring a variable or method in java code. Let's look at its writing method.

<%! Int I = 1; %>
<% Out. print (I); %>

After the Declaration, we can directly use this variable. Remember to add the declaration after %!

Of course, you can also declare a method as follows:

<%! public String getUserName(){return "zhangsan";} %><% out.print(getUserName());%>
Note: Use <%! %> When the declared variables are converted into Servlet classes in the jsp Container, the instance variables or class variables of the class are added (static keywords are added during Declaration). Therefore, pay attention to thread security issues 3.2.2: script segment.

The script segment is the code in the java code <%> to be executed during request processing. This is not much to say <% out. print (getUserName (); %>.

3.2.3: Expression

The expression script element is an expression completed in java. When a request computes these complete expressions, the result is converted to a string and inserted into the current input stream. The expression ends with <% = start %>.

Name: <% = "zhangsan" %> This is an expression (you do not need to add any symbols later)

3.3: Action Element

Unlike JSP command elements, JSP action elements work in the request processing stage. JSP action elements are written in XML syntax. There are mainly 20 standard jsp action elements. Below I will mainly discuss them in common use.

1: <jsp: useBean>, <jsp: setProperty>, <jsp: getProperty>

<Jsp: useBean> an action is used to load a JavaBean that will be used on the JSP page. Its attributes include the id of the object to a name, and the class specifies the full package name of the Bean, scope indicates the range of the object.

<Jsp: setProperty> mainly sets the object value, where name is the bean object name,

<Jsp: getProperty> mainly used to obtain objects. Let's take a look at the example below.

public class UserBean {    private String userName;    private String realName;    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public String getRealName() {        return realName;    }    public void setRealName(String realName) {        this.realName = realName;    }
<Body> <jsp: useBean id = "user" class = "com. lp. beans. userBean "scope =" session "> </jsp: useBean> <jsp: setProperty property =" userName "name =" user "value =" zhangsan "/> <jsp: setProperty property = "realName" name = "user" value = "Zhang San"/> userName: <jsp: getProperty property = "userName" name = "user"/> real name: <jsp: getProperty property = "realName" name = "user"/> </body>

Running result:

2: <jsp: forward page = ""> </jsp: forward> This is the same as the previous forward.

3: <jsp: include page = ""> </jsp: include> contains pages.

I will not mention anything else here. I don't need to use this estimate for development now. You can take a look at it for yourself.

4: Nine built-in jsp objects

In Servlet, do we see many objects in Jsp, such as Request and response? We have said that Jsp is a dynamic Servlet. Of course, we will look at the built-in objects in Jsp 9.

4.1: request

4.2: response

4.3: out. The out object is JspWriter.

4.4: page is the Instance object page after jsp is converted to Servlet = this;

4.5: pageContext to get all attributes of the current page

4.6: application is an instance of javax. servlet. ServletContext.

4.7: config is a javax. servlet. ServletConfig instance.

4.8: session

4.9: exception indicates exception handling.

We should understand this at first glance.

5. Objects and ranges

Jsp4 range

5.1: request: Valid only once in a request

5.2: the page is valid only on the current page.

5.3: the Session is valid throughout the Session.

5.4: The application is valid throughout the application, knowing that the server is disabled

 

Related Article

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.