[Java advanced learning] JSP introduction and use, syntax and instructions

JSP introduction

  • problem:

    After learning Servlet, using Servlet to display the page, the code writing is too troublesome. Greatly affects the efficiency of development, so is there a way for us to program web pages like writing web pages? ? ?

  • solve:

    ​ Use JSP technology: (HTML+CSS+JS+jQuery+Java code)

  • concept:

    The full name of JSP is Java Server Pages, and the Chinese name is java server pages. It is basically a simplified Servlet design. It is a dynamic web page technology standard initiated by Sun Microsystems and established by many companies.

  • advantage:

    • Achieve a greatly reduced coupling between Java code and HTML pages, which is convenient for development and testing
    • jsp has its own scripting language, which can separate Java code from HTML code
  • Disadvantages: When the amount of JSP data is too large, because the bottom layer is Java code, it will affect the server

Features

  • Essentially Servlet
  • Cross-platform, write once and run everywhere
  • Component cross-platform
  • Robustness and safety

JSP access principle

Tomcat does not know JSP, only executes Servlet

The browser initiates a request, requests a JSP, the request is received by the Tomcat server, executes the JspServlet, escapes the requested JSP file into the corresponding Java file (also a Servlet), and then executes the escaped Java file

  • Browser address bar input:http://localhost:8080/Jsp/1.jsp

  • Although it is 1.jsp, Tomcat will look for *.jspconfiguration in conf/web.xml under the server

    <servlet-mapping>
        <servlet-name>jsp</servlet-name>
        <url-pattern>*.jsp</url-pattern>
        <url-pattern>*.jspx</url-pattern>
    </servlet-mapping>
    
  • After there is a matching jsp configuration, the <servlet></servlet>JSP Servlet class will be found in it

    <servlet>
        <servlet-name>jsp</servlet-name>
        <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
        <init-param>
            <param-name>fork</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>xpoweredBy</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>3</load-on-startup>
    </servlet>
    
  • This class will read the Jsp file through the IO stream, and then output the .class file in Servlet format.

    • The Java code in the JSP file will be read and written as-is
    • The HTML code in the JSP file will be written line by line in the form of Servlet write


JSP syntax and instructions

It is very troublesome to write local code blocks and global code blocks in JSP files. In general development, the logic code of Java is written in Servlet and then passed to the corresponding JSP file.

Three major instructions :

  • page
  • taglib
  • include

Three annotations of Jsp

  • Front-end comments <!-- -->(generally don't use)

    Will be translated and sent, but will not be executed by the browser

    <!--
      前端注释
         会被转译,也会被发送,但是不会被浏览器执行
    -->
    
  • Java notes

    Will be translated, but not executed

    <%
    	//java注释
    	int a = 5;
    %>
    
  • JSP annotations <%-- --%>(use JSP annotations as much as possible for JSP files)

    Will not be translated. The client code will not display the commented out code

    <%--
    	Jsp注释
       		不会被转译
    --%>
    

JSP page directive

<%@page 属性名="属性值" 属性名="属性值" .......%>

You can write multiple lines, multiple pages

effect:

​ Configure the translation related parameters of the jsp file

<%@ page contentType="text/html;charset=UTF-8" language="java" import="java.util.*" %>
  • Attributes in the page: a total of 12 attributes

    Attributes Explanation
    language Declare the language to be translated into jsp
    import Statement translated file to import Java packages use different packages ,separated by
    pageEncoding Set the encoding format saved by the current JSP;
    at the same time set the encoding format of the Servlet response
    contextType After the translation is:
    resp.setContextType("text/html;charset=UTF-8");,
    high version only write pageEncoding="utf-8"on the line
    session Set whether to enable session support in the translated servlet (the built-in session object in JSP)
    is enabled by default.
    True means on; false means off
    errorPage Set the page where the jsp operation error jumps
    errorPage=url
    isErrorPage The Exception object can be used to capture exceptions in the error page, which encapsulates the exception object thrown in the previous page
    extends Set the parent class
    parent class to be inherited from the Java file translated by jsp : package name + class name
    buffer Buffer representing the response stream
    buffer="none | 8kb | sizekb"
    autoFlush Auto refresh buffer
    is true by default
    without human intervention
    isThreadSafe Whether the servlet implements SingleThreadModel
    true: single thread
    false: multi thread (default)
    isELIgnored Whether to ignore EL expressions,
    default false, support EL expressions

JSP include directive

Refers to the current page contains a certain other page

Not very commonly used, just understand the meaning

<%@include file="jsp01.jsp" %>

JSP taglib directive

Refers to the introduction of third-party lib libraries

Mainly used in the JSTL standard tag library

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

JSP partial code block

Intersperse the Java logic code in the HTMl code in the JSP file to make logical judgments

  • Features:

    • The Java code declared in the partial code block will be translated as-is to the _JspService method of the servlet file corresponding to the jsp
    • The variables declared in the code block are all local variables, all in the _JspService()method
  • use:<% java代码%>

    <html>
        <head>
            <title>jsp基本语法学习</title>
            <meta charset="UTF-8">
        </head>
    
        <body>
            <h3>jsp基本语法学习</h3>
            <hr>
            <%
                int a = 5;
                if (a>3) {
          
          %>
            <b>jsp学习很简单</b>
            <%}%>
        </body>
    </html>
    
  • Disadvantages:

    • Use partial code blocks to make logical judgments in jsp, which is troublesome to write and difficult to read
  • Used in development:

    • Servlet for request logic processing
    • JSP for page display

JSP global code block

  • Features: The declared Java code is translated into the corresponding servlet class as a global code

  • use:<%! 全局代码%>

    <html>
        <head>
            <title>jsp基本语法学习</title>
            <meta charset="UTF-8">
        </head>
    
        <body>
            <h3>jsp基本语法学习</h3>
            <hr>
            <%
                int a = 5;
                if (a>3) {%>
            <b>jsp学习很简单</b>
            <%test();}%>
            <%!
                public void test(){
                    System.out.println("这是全局代码块");
                }
            %>
        </body>
    
    </html>
    
  • Note: The code declared by the global code block needs to be called by the local code block

JSP script segment statement (commonly used)

  • Help us quickly get the return value of the variable/method as a data response to the browser

  • use:<%=变量名或者方法 %>

    <%=str%>

    <%=test()%>

    <body>
        <h3>jsp基本语法学习</h3>
        <hr>
        <%
        	String str = "jsp学习很简单";
        	int a = 5;
        	if (a>3) {%>
        <b><%=str%></b>
        <%test();}%>
        <%!
        public void test(){
        System.out.println("这是全局代码块");
    		}
        %>
    </body>
    
  • Note: Do not put a semicolon (;) after the variable name or method

  • Location: Any location other than JSP syntax requirements


JSP static introduction and dynamic introduction (include)

The two introduced display effects are the same. One can have a variable with the same name, and one cannot have a variable with the same name

advantage:

  • Reduce the redundancy of jsp code, easy to maintain and upgrade

Static introduction

<%@include file="要引入的jsp文件的相对路径"%>

Information used on every page

  • Create a new JSP file (includeStatic.jsp), and write public information to the JSP file
    • The JSP file will not be translated into a Java file because it is called by other JSPs and written into other JSPs
  • Call in the corresponding page <%@include file="includeStatic"%>-fill in the JSP relative path

Features:

  • The imported jsp file and the current jsp file will be translated into a Java (Servlet) file for use
  • The combined display effect is also displayed on the web page

note:

  • Statically imported jsp files will not be translated into Java files separately
  • Java code blocks cannot be used to declare variables with the same name in the current file and statically imported jsp files
  • includeStatic.jsp file

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    </head>
    <body>
        <b>我是静态引入——网站声明</b>
    </body>
    </html>
    
  • A certain JSP file

    <html>
        <head>
            <title>jsp基本语法学习</title>
            <meta charset="UTF-8">
        </head>
    
        <body>
            <hr>
            <%-- jsp静态引入--%>
            <%@include file="includeStatic.jsp"%>
        </body>
    
    </html>
    

Dynamic introduction

<jsp:include page="要引入的jsp文件的相对路径"></jsp:include>

Features:

  • The imported jsp file will be translated separately, and the translation file of the imported jsp file will be called in the Java file that the current file has been translated
  • Display the combined display effect on the web page

note:

  • Dynamic introduction allows variables with the same name to be declared in the file
  • includeActive.jsp code

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
        <head></head>
        <body>
            <i>jsp动态引入---网站声明</i>
        </body>
    </html>
    
  • Page to introduce dynamic jsp

    <body>
        <h3>jsp基本语法学习</h3>
        <hr>
        <%-- jsp动态引入 --%>
        <jsp:include page="includeActive.jsp"></jsp:include>
    </body>
    

JSP tags

JSP forward forwarding label

Similar to Servler's request forwarding, the address bar of the browser remains unchanged after forwarding, which is a request

  • use

    <jsp:forward page="要转发的jsp文件的相对路径"></jsp:forward>

    <%-- jsp的转发forward --%>
    <jsp:forward page="forward.jsp"></jsp:forward>
    
  • Features:

    • One request
    • The address bar information does not change
  • note:

    • It <jsp:param />will not report an error if there is a sub- tag between the two tags of the forwarding tag , and any other characters will be reported as an error
    • <jsp:param name="str" value="aaa"/>Used to transfer data to the forwarded jsp
      • name attribute: the key name of the attached data
      • value attribute: attached data content
      • The label will end the data with? The form of is spliced ​​behind the forwarding path and obtained through request
    <%--    jsp的转发forward--%>
    <jsp:forward page="forward.jsp">
        <jsp:param name="str" value="aaa"/>
    </jsp:forward>
    
  • Get the data of the subtag

    <%=request.getParameter("str")%>

    Output to the page through JSP script segment statement

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
        <head>
        </head>
        <body>
            <b>
                我是转发页面---forward---<%=request.getParameter("str")%>
            </b>
        </body>
    </html>d
    

JSP include dynamically introduces tags (see the previous title)

<jsp:include page="要引入的jsp文件的相对路径"></jsp:include>

<body>
    <h3>jsp基本语法学习</h3>
    <hr>
    <%-- jsp动态引入 --%>
    <jsp:include page="includeActive.jsp"></jsp:include>
</body>

JSP nine built-in objects

Built-in objects (implicit objects):

  • The JSP file is automatically generated and declared when it is translated into its corresponding Servlet file. We can use it directly in the JSP page

note:

  • Built-in objects are used in JSP pages, using partial code blocks or script segment statements. Cannot be used in global code blocks.
  • (Reason: The built-in object has been automatically generated in the service method body during translation, and the written JSP is the service method of the Servlet, so it can only be used in the partial code block/script segment statement)

Content: Nine objects

Domain scope: pageContext <request <session <application

Object Explanation Attention/Scope/Function
pageContext The page context object stores other built-in objects. Archived the current running information of JSP Each JSP file has a separate pageContext object
request Archive the object of the currently requested data. Created by the Tomcat server. One request
response The response object is an object used to respond to the request processing result to the browser. Set response headers, redirect
session This object is used to store the shared data of different requests from users One session
application It is the ServletContext object, there is only one for a project. Store the objects that users share data, and perform other operations. Within the project
out Response object, used internally by Jsp. Response objects with buffers are more efficient than response objects
exception Exception object. Store the current abnormal information To use this object, you need to use the attribute in the page specification: isErrorPage="true"open
page Represents the current Jsp object. Equivalent to this in Java
config That is, ServletConfig , which is mainly used to obtain configuration data in web.xml and complete some initialization data reading

pageContext object

Get 8 other built-in objects

Exception()=<%=pageContext.getException()%>
Page()=<%=pageContext.getPage()%>
Request()=<%=pageContext.getRequest()%>
Response()=<%=pageContext.getResponse()%>
ServletConfig()=<%=pageContext.getServletConfig()%>
ServletContext()=<%=pageContext.getServletContext()%>
Out()=<%=pageContext.getOut()%>
Session()=<%=pageContext.getSession()%>

Get the properties of the four domain objects

<%=PageContext.PAGE_SCOPE%>//page域对象(pageContext)常量----[1]
<%=PageContext.REQUEST_SCOPE%>//request域对象常量----[2]
<%=PageContext.SESSION_SCOPE%>//session域对象常量----[3]
<%=PageContext.APPLICATION_SCOPE%>//application域对象常量----[4]

SetAttribute() method of operating domain object

<%
    //设置session的属性键值对 key : session-value
    pageContext.setAttribute("key","session-value",PageContext.SESSION_SCOPE);
    //设置application的属性键值对 key : application-value
    pageContext.setAttribute("key", "application-value", PageContext.APPLICATION_SCOPE);
    //设置request的属性键值对 key : request-value
    pageContext.setAttribute("key","request-value",PageContext.REQUEST_SCOPE);
    //设置pageContext的属性键值对 key : pageContext-value
    pageContext.setAttribute("key","pageContext-value");
%>

Get the key-value pairs in the domain object

//1.session-key:
<%=pageContext.getAttribute("key",PageContext.SESSION_SCOPE)%>
    
//2.application-key:
<%=pageContext.getAttribute("key",PageContext.APPLICATION_SCOPE)%>
    
//3.request-key:
<%=pageContext.getAttribute("key",PageContext.REQUEST_SCOPE)%>
    
//4.pagecontext-key:
<%=pageContext.getAttribute("key")%>

Delete/get the attributes of the four domain objects

  1. 没有scope参数的getAttribute(String key,int scope)默认获取pageContext域对象的数据
  2. findAttribute()会一次从最小的作用域对四大作用域依次查找
    • 如果小作用域数据删除,就获取大作用域中的数据,只要找到一个就停止
  3. removeAttribute(String key,int scope)如果不指定scope,会删除四大域对象中所有对应的key-value
  4. scope:
    • PageContext.PAGE_SCOPE----1
    • PageContext.REQUEST_SCOPE----2
    • PageContext.SESSION_SCOPE----3
    • PageContext.APPLICATION_SCOPE----4
//获取pageContext:
<%=pageContext.getAttribute("key")%>
//删除pageContext中的key:
<%pageContext.removeAttribute("key",PageContext.PAGE_SCOPE);%><br>

//获取Request:
<%=pageContext.findAttribute("key")%>
//删除Request中的key:
<%request.removeAttribute("key");%>

//获取session:
<%=pageContext.findAttribute("key")%>
//删除session中的key:
<%session.removeAttribute("key");%>

//获取application:
<%=pageContext.findAttribute("key")%>
//删除application中的key:
<%application.removeAttribute("key");%>

JSP中的资源路径使用

四个作用域对象:

  • pageContext:当前页面。解决了在当前页面的数据共享问题。获取其他内置对象
  • request:一次请求。一次请求的servlet的数据共享。通过请求转发将数据流转给下一个Servlet
  • session:一次会话。一个用户的不同请求的数据共享。将数据从一次请求流转给其他请求
  • application:项目内。不同用户的数据共享问题。将数据从一个用户流转给其他用户

作用:数据流转

Jsp路径

在Jsp中资源路径可以使用相对路径

  • 问题一:资源的位置不可以随意更改
  • 问题二:需要使用…/进行文件夹的跳出。使用比较麻烦

在Jsp中资源路径可以使用绝对路径(必须会,开发中常用)

  • /虚拟项目名/资源路径

    <a href="/jsp/jspPro.jsp">jspPro.jsp</a>
    <a href="/jsp/a/a.jsp">a.jsp</a>
    
  • 注意:

    • 在Jsp中资源的第一个/表示的是服务器根目录,相当于:localhost:8080

使用JSP中自带的全局路径声明:

  • 代码:

    • <%
      String path = request.getContextPath();
      String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
      %>
    • <base href="<%=basePath%>">
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    
    <%
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    %>
    <html>
        <head>
            <base href="<%=basePath%>">
            <title>a.jsp</title>
        </head>
        <body>
            我是a.jsp </br>
            <a href="jspPro.jsp">jspPro.jsp</a>
        </body>
    </html>
    
  • 作用:给资源起那面添加项目路径

    • http://127.0.0.1:8080/虚拟项目名/

在信息管理系统中查询所有用户信息

servlet层—service层—Dao层—service层—servlet层,查询到的数据以List集合返回,然后请求转发到对应的jsp显示界面,通过req.setAttribute("usersList",usersList)转发到对应页面。不要使用session—重定向,会造成脏读

  • 脏读:查询到数据存放在session中,有效时间没过,如果用户改了性别或者其他的,查询到的数据依然是改之前了,就造成了脏读
  • 使用请求转发每次查询都会查询数据,不会造成脏读

如果注册中有空字符串,数据库也允许为空,再向数据库插入该空字符串时不应该插入'',因该插入null

if (user.getBirth().equals("")) {
    
    
    ps.setString(5, null);
}else {
    
    
    ps.setString(5,user.getBirth());
}

Guess you like

Origin blog.csdn.net/weixin_54707168/article/details/114058501