day08 JSP

Author: Xiang Zhongliang
Email: [email protected]
from: April 26, 2018Last
update date: May 1, 2018

Disclaimer: This note is recorded based on the content of the teaching video of Fang Lixun, a teacher of Chuanzhi Podcast, on Java Web, with my own understanding added in the middle. The purpose of this note is to reinforce your own learning. If there is any omission or inappropriateness, please point it out in the comment area. thanks.
The pictures involved will be updated at one time after the document is written.

day08 JSP

1. JSP introduction and JSP operation principle

1

Case: Create a new day08 web project and create a 1.jsp file with the following code:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>jsp入门(输出时间)</title>
  </head>

  <body>
     当前时间值是:
    <%
        Date date = new Date();
        out.write(date.toLocaleString());
    %>

  </body>
</html>

Browser input http://localhost:8080/day08/1.jspto see the results. The output page source code is:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>jsp入门(输出时间)</title>
  </head>

  <body>
     当前时间值是:
    2018-4-27 11:44:50

  </body>
</html>

Look at the content below to find the reason why the webpage becomes like the above.

Viewed C:\apache-tomcat-8.5.9\work\Catalina\localhost\day08\org\apache\jsp\_1_jsp.javacode snippet:

public final class _1_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent,
                 org.apache.jasper.runtime.JspSourceImports {

    ...

    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;

      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("\r\n");
      out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
      out.write("<html>\r\n");
      out.write("  <head>\r\n");
      out.write("    <title>jsp入门(输出时间)</title>\t\r\n");
      out.write("  </head>\r\n");
      out.write("  \r\n");
      out.write("  <body>\r\n");
      out.write("   \t 当前时间值是:\r\n");
      out.write("    ");

        Date date = new Date();
        out.write(date.toLocaleString());

      out.write("\r\n");
      out.write("    \r\n");
      out.write("  </body>\r\n");
      out.write("</html>\r\n");

      ···

As seen from the above example, the jsp file is translated into a servlet program by tomcat.
The best practice of servlet and jsp concluded by people's long-term practice results is: servlet writes logic and generates data; jsp does data display.

Through the above code, we can see that the commonly used objects of jsp are:

  • request
  • response
  • session
  • application
  • page

2. jsp syntax

Simple, boring but effective!

  • jsp template element
  • jsp script expression
  • jsp script snippet
  • jsp comments
  • jsp directive
  • jsp tag
  • jsp built-in object
  • How to find errors in jsp pages

2.1 jsp template element: the html content in the jsp page. It defines the basic skeleton of the web, that is, defines the page structure and appearance.

2.2 jsp script expression: <%= %>, which is used to output data to the browser.

2

An example is as follows:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>jsp入门(输出时间)</title>
  </head>

  <body>
     当前时间值是:
    <%
        Date date = new Date();
        String time = date.toLocaleString();
        /* out.write(date.toLocaleString()); 2种输出方式*/
    %>
    <%=time %>

  </body>
</html>

2.3 jsp script fragment:

3
4

<%int x=10; %>
aaa
<%out.print(x); %>

The reason why they can access each other is because they are all in the service method of the same servlet program.

5

2.4 jsp declaration

6

<%
  // 这是不行的
  public void run(){
  }
%>
<%!
  // 这个就可以
  public void run(){

  }
%>

The above jsp declaration will be translated to the outside of the servlet and become an independent method. Static code blocks can be written in jsp declarations.

2.5 jsp comments

<%-- jsp 注释--%>
And this <!-- html 注释 -->. If an html comment is used in the jsp fragment, the content of the comment will be passed to the browser, even if the browser does not display it.

2.6 jsp directive

7
8
9
10
11

Regarding the errorPage attribute, when jsp throws an exception, it jumps to the position indicated by errorPage. as follows:

The page that throws the exception /5.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" errorPage="/errors/error.jsp"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>errorPage属性展示</title>
  </head>

  <body>
    <%
        int x = 1/0;        
    %>
  </body>
</html>

Error apology page /errors/error.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>    
    <title>My JSP 'error.jsp' starting page</title>
  </head>

  <body>
     对不起,出错了 <br>
  </body>
</html>

Browser access to http://localhost:8080/day08/5.jspview the results.

We can also configure the error handling of the entire web application globally ! The configuration is as follows:

web.xml add the following content:

<error-page>
  <exception-type>java.lang.ArithmeticException</exception-type>
  <location>/errors/error.jsp</location>
</error-page>

<error-page>
  <exception-code>404</exception-code>
  <location>/errors/404.jsp</location>
</error-page>

<error-page>
  <exception-code>500</exception-code>
  <location>/errors/500.jsp</location>
</error-page>

The above code also gives the display page of the 404 error code. When a 500 error occurs, the output is "Sorry, there was an internal error in the server".

After the development of the website is over, when it is deployed online, these things must be matched.

Teacher Fang Lixun reminded that the size of the error.jsp page should not exceed 1KB at this time, otherwise the experimental effect will not appear.

Also errorPage takes precedence over error handling in web.xml.

isErrorPage="true|false": Defaults to false. If a jsp page is an error handling page, this property should be set to true. At this point, the exception object is passed to the error handling page, which can then log the exception.

12

2.7 Solve the problem of jsp garbled characters

For servers above Tomcat 6, there will be no garbled characters in jsp.

2.8 jsp syntax - include directive

Contains, there are two types of static containment and dynamic containment.

Static inclusion, also known as compile-time inclusion, all jsp it contains will be compiled into a servlet

Three jsp files are involved: 6.jsp, head.jsp, foot.jsp, the code is as follows:

6.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>jsp包含</title>
  </head>

  <body>
    <%@ include file="/public/head.jsp" %>
    aaaaaaaaaa<br/>
    <%@ include file="/public/foot.jsp" %>    
  </body>
</html>

/public/head.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    我是 head <br/>

/public/foot.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    我是 foot <br/>

Dynamic inclusion, also known as runtime inclusion. The included content is compiled into 3 jsp files.

<body>
<% request.getRequestDispatcher("/public/head.jsp").include(request, response); %>
<% response.getWriter().write("aaaaaaaaaaaaa<br/>"); %>
<% request.getRequestDispatcher("/public/foot.jsp").include(request, response); %>  
</body>

3. Introduction to the Nine Implicit Objects of JSP

jsp nine implicit objects:

  • request
  • response
  • session
  • application
  • config
  • page
  • exception
  • out
  • pageContext

out and pageContext are objects unique to jsp.

3.1 jsp nine implicit objects - out object

Example:
8.jsp:

<body>
<%
  out.write("hahahahaha");
  response.getWriter().write("woowowowowo");
%>
</body>

and

<body>
hahahahaha
<%
  response.getWriter().write("woowowowowo");
%>
</body>

The output is: woowowowowo hahahahaha. It is recommended to use only the out object for jsp output. The reason for outputting that result is that out is buffered.

3.2 jsp nine implicit objects - pageContext object (the most important object in jsp, representing the running environment of jsp page)

13
14

The pageContext (also known as page domain) domain is only valid in the current jsp page. It is 4 domains in web development (the other 3: request (available in the request scope), session (available in the session scope), ServletContext (all available in the web application scope) available)), the domain with the smallest scope.

View Jsp API

Methods of the pageContext object:

  • setAttribute(String name, Object value)
  • getAttribute(String name)
  • removeAttribute(String name)

pageContext methods to access other fields:

  • setAttribute(String name, int scope)
  • getAttribute(String name, int scope)
  • removeAttribute(String name, int scope)

Constants representing individual fields:

  • PageContext.APPLICATION_SCOPE
  • PageContext.SESSION_SCOPE
  • PageContext.REQUEST_SCOPE
  • PageContext.PAGE_SCOPE

The findAttribute method, key, finds attributes in various fields.

pageContext.findAttribute("data");

findAttribute() searches for page -> request -> session -> applicationthese , and returns if not found null.
EL expressions ${data}are equivalent to executingpageContext.findAttribute("data");

Example:
The pageContext object becomes the entry point for managing other domains. 12.jsp, as follows:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>pageContext 对象访问其他域</title>
  </head>

  <body>
    <%
        request.setAttribute("data", "aaa");
        /* pageContext 对象成为管理其他域的入口 */
        String data = (String)PageContext.getAttribute("data", pageContext.REQUEST_SCOPE);
        out.write(data);
    %>    
  </body>
</html>

Other common methods of pageContext: forward and include, as follows:

<%
  pageContext.forward("1.jsp");
  pageContext.include("/foot.jsp");  
%>

4. jsp common tags

Jsp tag (Jsp Action): Also called jsp action element, it is used to provide business logic functions in jsp pages and avoid writing java code directly in jsp pages (making jsp pages difficult to maintain).

Common jsp tags include:

about

<body>
    <jsp:forward page="/index.jsp"></jsp:forward>
    <jsp:include page="/public/foot.jsp"></jsp:include> <%-- 动态包含 --%>
</body>

<body>
    <jsp:forward page="/servlet/ServletDemo1">
      <jsp:param value="xxxx" name="username"/>
    </jsp:forward>
</body>

cn.wk.web.servlet.ServletDemo1 gets the incoming data, the code is as follows:

public class ServletDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String username = req.getParameter("username");
        System.out.println(username);
    }
}

Browser access 14.jsp, console output xxxx.

In addition, script expressions can also be passed in value, as follows:

<% int x = 10 %>
<jsp:param name="abc" value="<%=x%>"/>

5. jsp mapping

Jsp mapping: is to map a jsp to a web address. It is the same as servlet program mapping. It needs to be configured in the web.xml file.

as follows:

<servlet>
  <servlet-name>xxx</servlet-name>
  <jsp-file>/14.jsp</jsp-file>
</servlet>

<servlet-mapping>
  <servlet-name>xxx</servlet-name>
  <url-pattern>/15.html</url-pattern>
</servlet-mapping>

6. Page beautification topic - div and css basics and cases

relearn

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325221797&siteId=291194637