Javaweb Note 5: JSP

JSP

The full name of JSP is Java Server Pages, which is a dynamic web development technology. It uses JSP tags to insert Java code in HTML web pages. Tags usually start with <% and end with %>.

JSP is a Java servlet that is mainly used to implement the user interface part of Java web applications. Web developers write JSPs by combining HTML code and embedding JSP actions and commands.

JSP obtains user input data through web forms, accesses databases and other data sources, and then dynamically creates web pages.

JSP tags have multiple functions, such as accessing databases, recording user selection information, accessing JavaBeans components, etc., and can also transmit control information and share information in different web pages.

No JSP, only use servlet to output web page

response.setContentType("text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();
//动态的响应html页面
writer.write("<!DOCTYPE html>");
writer.write("<html>");
writer.write("<head>");
writer.write("<meta charset='UTF-8'>");
writer.write("<title>Insert title here</title>");
writer.write("</head>");
writer.write("<body>");
writer.write("<h1>这个页面很繁琐</h1>");
writer.write("</body>");
writer.write("</html>"); 

Servlets appeared first, and when there were only servlets, servlets had to process logic and output html. For example, the above implementation method is very cumbersome, and the code is difficult to maintain, so the jsp technology is introduced. JSP can easily write or modify HTML pages without having to face a large number of println statements.

jsp script

<%java代码%>The internal java code is translated to the interior of the service method

<%=java变量或表达式>Will be translated into service method internal out.print()

<%!java代码%>will be translated into the contents of the servlet's members

jsp comments

Different annotations have different visible ranges

Html comments: <!--注释内容-->visible range jsp source code, translated servlet, page display html source code

java comment: //单行注释 /*多行注释*/visible scope jsp source code, translated servlet

jsp comment: <%--注释内容--%>visible range jsp source code is visible

Html注释<%--<div></div>--%>java注释
    <%
      //int i=10;
      /*System.out.print(i);*/
    %>jsp注释
    <%--
     int i=10;
      /*System.out.print(i);*/
    --%>

jsp operating principle

The essence of jsp is servlet. When jsp is accessed for the first time, it will be translated into servlet by the web container and then executed. Process: first visit ---->helloServlet.jsp---->helloServlet_jsp.java---->compile and run. The translated servlet can be found in Tomcat's work directory.

Mapping is configured in web.xml under tomcat.
insert image description here
insert image description here

jsp instruction (3)

The command of jsp is the command to guide the translation and operation of jsp. jsp includes three major commands:

1. page instruction: the instruction with the most attributes (the default page instruction is fine in actual development), according to different attributes, guide the characteristics of the entire page. Format: <%@ page 属性名1= "属性值1" 属性名2= "属性值2" ...%>, common attributes are as follows:

  • language: the language types that can be embedded in the jsp script
  • pageEncoding: the encoding of the current jsp file itself, which can contain contentType
  • contentType:response.setContentType(text/html;charset=UTF-8)
  • session: whether jsp automatically creates a session when translating, the default is true
  • import: import java package
  • errorPage: Which page to jump to when the current page has an error
  • isErrorPage: The current page is an error-handling page
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

2. include instruction: page includes (statically included) instruction, which can include one jsp page into another jsp page, format:

<%@ include file="被包含的文件地址"%>

3. taglib instruction: import tag library (jstl tag library, struts2 tag library) into jsp page, format:

<%@ taglib uri="标签库地址" prefix="前缀"%>

jsp built-in/implicit objects (9)

After the jsp is translated into a servlet, there are 9 objects defined and initialized in the service method. We can use these 9 objects directly in the jsp script.
insert image description here

out object

The type of out: JspWriter, the function of out is to output content to the client, using out.write(), the out buffer is 8kb by default, and can be set to 0, which means that the out buffer is closed, and the content is directly written to the response buffer.
insert image description here
The out buffer will eventually be flushed to the response buffer, so the content of response.getWrite().write() will be output first.

pageContext object

The context object of the jsp page, the page object and the pageContext object are not the same thing, the functions are as follows:

1. pageContext is a domain object that is valid inside the current page.

setAttribute(String name,Object obj)
getAttribute(String name)
removeAttrbute(String name)

2. pageContext can access data to other specified domains

setAttribute(String name,Object obj,int scope)
getAttribute(String name,int scope)
removeAttrbute(String name,int scope)
findAttribute(String name)

Obtain attributes from the pageContext domain, request domain, session domain, and application domain in turn, and will not search backwards after obtaining them in a certain domain.

//使用pageContext向request域存数据
//request.setAttribute("name", "zhangsan");
//pageContext.setAttribute("name", "sunba");
//pageContext.setAttribute("name", "lisi", PageContext.REQUEST_SCOPE);
//pageContext.setAttribute("name", "wangwu", PageContext.SESSION_SCOPE);
//pageContext.setAttribute("name", "tianqi", PageContext.APPLICATION_SCOPE);
<%=request.getAttribute("name") %>
    <%=pageContext.getAttribute("name", PageContext.REQUEST_SCOPE)%>
    
    <!-- findAttribute会从小到大搜索域的范围中的name -->
    <!-- page域<request域<session域<application域 -->
    <%=pageContext.findAttribute("name") %>

3. You can get other 8 implicit objects

pageContext.getRequest();
pageContext.getOut();

Summary of the four scopes

  • page domain: current jsp page range
  • request field: a request
  • session domain: a session
  • application domain: the entire web application

jsp tag (action)

1) Page inclusion (dynamic inclusion): <jsp:include page="included page" />, what is the difference between static inclusion and dynamic inclusion?
insert image description here
insert image description here
Mainly analyze from the following five aspects (source):

  1. Syntax:
    Static include: <%@ include file=""%>
    Dynamic include: <jsp: include page=""%>

  2. When statically included, the html.head, body and other tags in the containing page and the included page only appear once in total, otherwise an error will be reported; while dynamic inclusion will not.

  3. Static inclusion does not check changes in the included files; but dynamic inclusion can check changes in included files and can take parameters

  4. Static inclusion is to import the content of the file into the included file first, then compile it together, and finally show it to the user (include first and then compile)

  5. Dynamic inclusion can automatically distinguish whether the included file is static or dynamic. If it is static, it will be processed in the same way as static inclusion; if it is a dynamic page, it can be processed
    dynamically before including the result. (compile first and then include)

2) Request forwarding: <jsp:forward page="Resources to be forwarded" />

Write java code in jsp:

<%
            //获得集合List<Product>
            List<Product> productList = (List<Product>)request.getAttribute("productList");
            if(productList!=null){
    
    
                for(Product product : productList){
    
    
                    out.write("<div class='col-md-2' style='height:250px'>");
                    out.write("<a href='product_info.htm'>");
                    out.write("<img src='"+product.getPimage()+"' width='170' height='170' style='display: inline-block;'>");
                    out.write("</a>");
                    out.write("<p><a href='product_info.html' style='color: green'>"+product.getPname()+"</a></p>");
                    out.write("<p><font color='#FF0000'>商城价:¥"+product.getShop_price()+"</font></p>");
                    out.write("</div>");
                }
            }
        %>

EL technology

EL (Express Language) expressions can be embedded in jsp pages to reduce the writing of jsp scripts. The purpose of EL is to replace the writing of scripts in jsp pages.

EL fetches data from domain

The main function of EL is to obtain the data in the four major domains, the format ${EL expression}

EL gets the value in the pageContext field: ( page Context Scope . key ) ; EL gets the value in the request field: (pageContextScope.key); EL gets the value in the request field:(pageContextScope.key);E L gets the value in the r e q u e s t field : (request.key);
EL gets the value in the session field:( session . key ); EL gets the value in the application field: (session.key); EL gets the value in the application field:(session.key);EL obtains the value in the a p p l i c a t i o n field : (application.key);
EL obtains a certain value $(key) from the four fields;
also from the pageContext field and the request field in turn , session domain, application domain to obtain attributes, after obtaining in a certain domain will not look backward.

Example:

  1. EL get normal string

  2. EL gets the value of the User object

  3. EL gets the value of List

  4. EL gets the value of List

  5. EL gets the value of Map<String, String>

  6. EL gets the value of Map<String, User>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.itheima.domain.*" %>
<%@ page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <!-- 模拟域中的数据 -->
    <%
        pageContext.setAttribute("company", "阿里");
    
        //存储字符串
        request.setAttribute("company", "企鹅");
    
        //存储一个对象
        User user = new User();
        user.setId(1);
        user.setName("zhangsan");
        user.setPassword("123");
        session.setAttribute("user", user);
        
        //存储一个集合
        List<User> list = new ArrayList<User>();
        User user1 = new User();
        user1.setId(2);
        user1.setName("lisi");
        user1.setPassword("123");
        list.add(user1);
        User user2 = new User();
        user2.setId(3);
        user2.setName("wangwu");
        user2.setPassword("123");
        list.add(user2);
        application.setAttribute("list", list);
        
    %>
    
    
    <!-- 脚本法是取出域中的值 -->
    <%=request.getAttribute("company") %>
    <%
        User sessionUser = (User)session.getAttribute("user");
        out.write(sessionUser.getName());
    %>
    <hr/>
    <!-- 使用EL表达式获得域中的值 -->
    ${
    
    requestScope.company }
    ${
    
    sessionScope.user.name }
    ${
    
    applicationScope.list[1].name}
    
    <!-- 使用el表达式 全域查找 -->
    ${
    
    company }
    ${
    
    user.name }
    ${
    
    list[1].name}
    
    <!-- el可以执行表达式运算 -->
    ${
    
    1+1 }
    ${
    
    1==1?true:false }
    <!-- empty 判定某个对象是否是nullnull返回true -->
    ${
    
    empty list}
    
    
</body>
</html>

EL's built-in objects (nine)

pageScope,requestScope,sessionScope,applicationScope;

Get data in domain in JSP

Receive parameters: param, paramValues;

Get request header information: header, headerValues;

Get global initialization parameters: initParam;

cookie in WEB development: cookie;

pageContext in WEB development: pageContext;

example:

<!-- 获得表单的参数 -->
    <%
        request.getParameter("username");
    %>
    
    <!-- 使用el获得参数 -->
    ${
    
    param.username }
    ${
    
    header["User-Agent"] }
    ${
    
    initParam.aaa }
    ${
    
    cookie.name.value }        ${
    
    cookie.abc.value }
<!-- 通过el表达式获得request对象 --> ${
    
    pageContext.request }与${
    
    requestScope}不同,对象不仅包含域,而且还有其他数据和方法<!--获得WEB应用的名称-->$(pageContext.request.contextPath)相当于<%=pageContext.getRequest().getContextPath%>

JSTL technology

JSTL (JSP Standard Tag Library), the JSP standard tag library, can be embedded in jsp pages to complete business logic and other functions in the form of tags. The purpose of jstl is the same as el is to replace the script code in the jsp page. The JSTL standard standard tag library has 5 sub-libraries, but with the development, its core library is often used at present.
insert image description here

JSTL download and import

JSTL download: Download the JSTL JAR package from the Apache website. Go to "http://archive.apache.org/dist/jakarta/taglibs/standard/binaries/" to download the JSTL installation package. jakarta-taglibs-standard-1.1.2.zip, and then decompress the downloaded JSTL installation package. At this time, you can see two JAR files in the lib directory, namely jstl.jar and standard.jar. Among them, the jstl.jar file contains the interfaces and related classes defined in the JSTL specification, and the standard.jar file contains the .class files used to implement JSTL and five tag library descriptor files (TLD) in JSTL.

Import the two jar packages into the lib of our project, and import:
insert image description here
3. Common tags of the JSTL core library

1. <c:if> tag

<!-- 用户没有登录 -->
<c:if test="${empty user}">
    <li><a href="login.jsp">登录</a></li>
    <li><a href="register.jsp">注册</a></li>
</c:if>
<!-- 用户已经登录 -->
<c:if test="${!empty user}">
    <li>${
    
    user.name }</li>
    <li><a href="#">提出</a></li>
</c:if>

2. <c:forEach> tag

There are two combinations of usage:

Method 1:
insert image description here
Method 2:

<h1>取出strList的数据</h1>
    <c:forEach items="${strList }" var="str">
        ${
    
    str }<br/>
    </c:forEach>
    
    <h1>取出userList的数据</h1>
    <c:forEach items="${userList}" var="user">
        user的name:${
    
    user.name }------user的password:${
    
    user.password }<br/>
    </c:forEach>
    
    <h1>取出strMap的数据</h1>
    <c:forEach items="${strMap }" var="entry">
        ${
    
    entry.key }====${
    
    entry.value }<br/>
    </c:forEach>
    
    <h1>取出userMap的数据</h1>
    <c:forEach items="${userMap }" var="entry">
        ${
    
    entry.key }:${
    
    entry.value.name }--${
    
    entry.value.password }<br/>
    </c:forEach>

References: 1. https://www.cnblogs.com/ginb/p/7231700.html

Guess you like

Origin blog.csdn.net/weixin_42838061/article/details/121175940