JavaWeb development - JSP technology

Chapter Four: JSP Technology


1. Introduction to JSP


Introduction to JSP

JSP (full name Java Server Pages) Java server page technology is a technical specification under the JavaEE platform. It allows specific tags to be used to insert Java codes into HTML webpages to realize dynamic page processing, so JSP is a complex of HTML and Java codes. JSP technology can quickly implement the development of a page, which will become easier than implementing page development in Servlet.

Common View Layer Techniques

HTML、JSP、Thymeleaf等。

Front-end and back-end separate development methods

In projects where the front and back ends are separated, it is truly possible to achieve "specialization in technology" (separation of developers). In the front-end and back-end separation development method, the front-end page is developed by a professional team, and the API interface of the back-end is called through the request for data interaction. In the development team of front-end pages, more attention should be paid to technologies such as: html, CSS, jQuery, Vue, Nodejs and other front-end technologies. What the front end pursues are: page performance, smooth speed, compatibility, user experience, etc. The back-end team is more about the specific realization of the business. In the back-end development team, more attention should be paid to technologies such as: design patterns, distributed architecture, microservice architecture, database operations, Java performance optimization, and database optimization technologies. The separation of front and back ends has become the industry standard usage method for Internet project development, especially for large-scale distributed architecture, elastic computing architecture, micro-service architecture, multi-terminal services (multiple clients, such as browsers, vehicle terminals, Android, etc.) lay a solid foundation.

Two, JSP operating principle

insert image description here

JSP technical characteristics

JSP and Servlet are essentially the same technology. When a JSP file is requested for the first time, the JSP engine will compile the JSP into a Servlet and execute the Servlet. If the JSP file is modified, the JSP engine will recompile the JSP.
When the JSP engine compiles JSP, it will generate two files, which are the .java source file and the compiled .class file, and put them in the org\apache\jsp directory in the virtual host directory corresponding to Catalina in the work directory of Tomcat. The names of the two files will use the name of the JSP plus "_jsp". Such as: index_jsp.java, index_jsp.class

The difference between JSP and Servlet

JSPs are deployed into the container as source files. The Servlet needs to be compiled into a class file and then deployed to the container.
JSP is deployed to the root directory of the web project or other subdirectories under the root directory are located in the same location as static resources. The Servlet needs to be deployed to the WEB-INF/classes directory.
The HTML code in the JSP will be put into the out.write() method of the Servlet by the JSP engine. In Servlet, we need to generate a response page by operating on the output stream of the character stream.
JSP is better at displaying pages, and Servlet is better at logic control.

Third, the use of JSP tags

insert image description here

Three original tags of JSP

The original tag of JSP can be used in any version of JSP.

Declaration tag <%! %>

Declaration tags are used to define member variables and method definitions in JSP. The content in the tag will appear in the {} of the Servlet class after the JSP is compiled.
Code example:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  Welcome JSP!
  <%!
      int a = 10;
      int add(int a,int b){
    
    
        return a+b;
      }
  %>  //声明标签
  <%
    int c = 20;
  %>
  <%=a %>
  <%=c %>
  </body>
</html>

script tag <% %>

Script tags are used to write business logic in JSP. The content in the tag will appear in the _jspService method body of the Servlet after the JSP is compiled.

Assignment tag <%= %>

Assignment tags are used for content output in JSP. The content in the label will appear in the parameters of the out.print() method of the _jspService method.
Note: There is no need to add ";" in the code when using the assignment tag.

Use of JSP raw tags

Make a Simple Random Judgment

Requirements: Display "Go to pet the cat" with a 20% probability, "Continue to learn happily" with an 80% probability, and display the corresponding random number at the same time.

<%@ page import="java.util.Random" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%
        int flag = new Random().nextInt(100)+1;
        if(flag <= 20){
    
    
    %>
    去撸猫 <%= flag%>
    <%}else{
    
    %>
        继续快乐学习 <%= flag%>
    <%}%>
</body>
</html>

JSP instruction tag

The role of the JSP instruction tag is to declare some attributes and actions of the JSP page.
Format: <%@command name attribute = "value" attribute = "value 1, value 2..." %>

Classification of JSP instruction tags

insert image description here

Page directive tag

contentType : Set the response type and encoding.

pageEncoding : Set the encoding of the page.

import : Import the required packages.

language : The language that can be nested in the current JSP page.

session : Set whether the JSP page obtains the session built-in object.

buffer : Set the buffer size of the stream of the JSP page.

autoFlush : Whether to automatically refresh.

exends : Declares that the current JSP page inherits from that class. What must be inherited is httpservlet and its subclasses.

isELIgnored : Whether to ignore el expressions.

errorPage : The JSP page to jump to when the current JSP page is abnormal.

isErrorPage : Whether the current JSP page is an error page. If the value is true, a built-in object exception of the JSP page can be used.

Include directive tag

Static inclusion, you can include other page content, compile and run together, and generate a java file.
Format: <%@include file="the relative path of the included JSP" %>

Taglib directive tags

Import tag library.
Format: <%@taglib prefix="prefix" uri="namespace" %>

Fourth, the built-in object of JSP

A total of 9 such objects are predefined in JSP, namely: request, response, session, application, out, pagecontext, config, page, exception.

The request object
The request object is an object of type HttpServletRequest.

The response object
The response object is an object of type HttpServletResponse.

session object
The session object is an object of type HttpSession. It can only be used in pages containing session="true".

application object
The application object is an object of type ServletContext.

out object
The out object is an object of type JspWriter.

The config object
The config object is an object of type ServletConfig.

pageContext object
The pageContext object is an object of type PageContext. The function is to obtain parameters in any range, through which objects such as out, request, response, session, and application of JSP pages can be obtained. The creation and initialization of the pageContext object is done by the container, and the pageContext object can be used directly in the JSP page.

The page object
The page object represents the JSP itself.

exception object
The function of exception object is to display exception information, which can only be used in the page that contains isErrorPage="true".

5. Request Forwarding

What is request forwarding

Request forwarding is a request method on the server side, which is equivalent to directly requesting a certain resource on the server side.
Example:
RequestDispatcher dispatcher = request.getRequestDispatcher(“/test.jsp”);
dispatcher.forward(request,response);
shorthand:
request.getRequestDispatcher(“/test.jsp”).forword(request,response);

insert image description here

The difference between request forwarding and redirection

<Request forwarding is completed in one request and response for the client browser, while redirection is completed in two requests and two responses.
<Request forwarding does not change the content in the address bar of the client browser. Redirection will change the content in the address bar of the client browser.
<Request forwarding can use the request object to transfer data, but redirection cannot use the request object to transfer data.
<If it is a DML operation, it is recommended to use the redirection method to generate a response for the client browser, which can solve the phenomenon of repeated form submission.

request forwarding case

Requirement: Obtain the language supported by the client browser in the Servlet, and respond the language supported by the client browser to the client browser through the JSP page.

//Servlet代码
package com.packagename.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 在Servlet中获取客户端浏览器所支持的语言,
 * 并通过JSP页面将客户端浏览器所支持的语言响应给客户端浏览器。
 */
@WebServlet("/url")
public class LanguageServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //获取请求头中所支持的语言
        String header = req.getHeader("Accept-Language");
        //将数据存放到Request对象中
        req.setAttribute("header",header);
        //使用请求转发跳转到JSP
        req.getRequestDispatcher("jspname.jsp").forward(req,resp);
    }
}

//JSP代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    String header = (String)request.getAttribute("header");
%>
<font color="blue"><%= header%> </font>
</body>
</html>

Six, the four major scope objects in JSP

Scope: "The scope of data sharing", that is to say, how far the data can be valid.

object name Scope of action
application The entire application works
session valid for the current session
request valid for the current request
page Valid on current page

Seven, JSTL tag library

What is the JSTL tag library

JSTL (Java server pages standard tag library, that is, JSP standard tag library) JSTL tags are based on JSP pages. These tags can be inserted into the JSP code. In essence, JSTL is also a set of tags defined in advance. These tags encapsulate different functions. When calling tags on the page, it is equivalent to calling the encapsulated functions. The goal of JSTL is to make JSP pages more readable, simplify the design of JSP pages, realize code reuse, and improve efficiency.

The JSTL tag library is supported after the JSP2.0 version. When using the JSTL tag library, you need to add the corresponding taglib instruction tag in the JSP.

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

JSTL tag classification

According to the functions provided by JSTL tags, they can be divided into 5 categories.

core tag

The most commonly used, most important, and most basic tags

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

insert image description here

formatting tags

JSTL formatting tags are used to format and output text, date, time, and numbers.

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

insert image description here

SQL tags

The JSTL SQL tag library provides tags for interacting with relational databases (Oracle, MySQL, SQL Server, etc.).

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

insert image description here

XML tags

The JSTL XML tag library provides tags for creating and manipulating XML documents.

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

insert image description here

JSTL function

JSTL contains a series of standard functions, most of which are general-purpose string processing functions.

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

insert image description here

Eight, EL expression

What are EL expressions

EL (Expression Language) is an expression language. It is to make JSP easier to write, reduce java code, and make it very simple to obtain data stored in Java objects. EL expressions are supported after the JSP2.0 version.

Grammatical structures

${expression}
${object.property name}

Operators in EL expressions

operator describe
( ) priority
+ add
- reduce
* take
/ or div remove
% or mod model
== or eq test for equality
!= or ne Does the test not equal
< 或 lt Tests whether it is less than
> or gt Test whether greater than
<= or le Tests for less than or equal to
>= or ge Tests for greater than or equal to
&& 或 and test logic and
! or not test negation
empty test for null

Implicit objects for EL expressions

hidden object describe
pageScope page scope
requestScope request scope
sessionScope session scope
applicationScope application scope
param Request object parameter, string
paramValues The parameters of the Request object, a collection of strings
header HTTP headers, string
headerValues HTTP information header, a collection of strings
initParams Context initialization parameters
cookie cookie value
pageContext the pageContext of the current page

Use EL expressions to get the value in the scope

${pageScope.name}

${requestScope.name}

${sessionScope.name}

${applicationScope.name}

When obtaining the data in the scope attribute, you can also only write the attribute name, and the EL expression will search for the value of the attribute in the order of pageScope, requestScope, sessionScope, and applicationScope.

${name}

Nine, the use of JSTL tag library and EL expressions

Steps to use the JSTL tag library

1. Add jstl.jar
2. Add the taglib instruction tag to the JSP page.

Use of JSTL core tags

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

The <c:if>
tag judges the value of the expression, and if the value of the expression is true, executes its main content.
Example:<c:if test="${1==1}"> Hello JSTL! </c:if>

< c:choose >, < c:when >, < c:otherwise > The
< c:choose > tag has the same function as the Java switch statement and is used to choose among many options.
There are cases in the switch statement, and <c:when> in the <c:choose> tag, default in the switch statement, and <c:otherwise> in the <c:choose> tag.
Example:

<c:choose>
        <c:when test="${2==1}">
            Hello When 1!
        </c:when>
        <c:when test="${2==1}">
            Hello When 2!
        </c:when>
        <c:otherwise>
            Hello Otherwise!
        </c:otherwise>
    </c:choose>

< c:forEach >

迭代器,用于迭代集合。

属性 描述
items 被迭代的集合
begin 迭代器的起始因子
end 迭代器的结束因子
step 迭代因子的增长数
var 代表当前迭代元素的变量名称
varStatus 代表循环状态的变量名称

varStatus 属性
current: 当前这次迭代的(集合中的)项

index: 当前这次迭代从 0 开始的迭代索引

count: 当前这次迭代从 1 开始的迭代计数

first: 用来表明当前这轮迭代是否为第一次迭代的标志

last: 用来表明当前这轮迭代是否为最后一次迭代的标志

begin: 属性值

end: 属性值

step: 属性值

示例:

<c:forEach begin="0" end="9" step="2" varStatus="suibian">
        ForEach.....${
    
    suibian.count},${
    
    suibian.first},${
    
    suibian.last},${
    
    suibian.index}<br/>
    </c:forEach>

效果图:
insert image description here

案例:使用ForEach迭代List

需求:

创建Users对象,含有userid,username属性。

创建一个Servlet,在Servlet中创建多个Users对象并放到List集合中,在showUsers.jsp的页面中显示所有的Users对象的信息。

1.Users类

package com.package.pojo;

public class Users {
    
    
    private Integer userid;
    private String username;

    public Users(Integer userid, String username) {
    
    
        this.userid = userid;
        this.username = username;
    }

    public Users() {
    
    
    }

    public Integer getUserid() {
    
    
        return userid;
    }

    public void setUserid(Integer userid) {
    
    
        this.userid = userid;
    }

    public String getUsername() {
    
    
        return username;
    }

    public void setUsername(String username) {
    
    
        this.username = username;
    }
}

2.Servlet

package com.package.servlet;

import com.package.pojo.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/url")
public class FindUsersServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //创建测试数据
        Users users1 = new Users(1,"海绵宝宝");
        Users users2 = new Users(2,"派大星");

        //实例化List
        List<Users> list = new ArrayList<>();
        list.add(users1);
        list.add(users2);

        //将List添加到request对象中
        req.setAttribute("list",list);

        //通过请求转发方式跳转
        req.getRequestDispatcher("jname.jsp").forward(req,resp);
    }
}

3.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table border="1" align="center">
    <tr>
        <th>用户ID</th>
        <th>用户姓名</th>
    </tr>
    <c:forEach items="${list}" var="Lname">
        <tr>
            <td>${
    
    Lname.userid}</td>
            <td>${
    
    Lname.username}</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

效果图:
insert image description here

使用ForEach迭代Map

需求:

创建Users对象,含有userid,username属性。

创建一个Servlet,在Servlet中创建多个Users对象并放到Map集合中,在showUsers2.jsp的页面中显示所有的Users对象的信息。

1.Users类

package com.package.pojo;

public class Users {
    
    
    private Integer userid;
    private String username;

    public Users(Integer userid, String username) {
    
    
        this.userid = userid;
        this.username = username;
    }

    public Users() {
    
    
    }

    public Integer getUserid() {
    
    
        return userid;
    }

    public void setUserid(Integer userid) {
    
    
        this.userid = userid;
    }

    public String getUsername() {
    
    
        return username;
    }

    public void setUsername(String username) {
    
    
        this.username = username;
    }
}

2.Servlet

package com.itbaizhan.servlet;

import com.itbaizhan.pojo.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/url")
public class FindUsers2Servlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //创建测试数据
        Users users1 = new Users(1,"林黛玉");
        Users users2 = new Users(2,"贾宝玉");

        //实例化Map
        Map<String,Users> map = new HashMap<>();
        map.put("users1",users1);
        map.put("users2",users2);


        //将List添加到request对象中
        req.setAttribute("map",map);

        //通过请求转发方式跳转
        req.getRequestDispatcher("jname.jsp").forward(req,resp);
    }
}

3.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table border="1" align="center">
    <tr>
        <th>MapKey</th>
        <th>用户ID</th>
        <th>用户姓名</th>
    </tr>
    <c:forEach items="${map}" var="Mname">
        <tr>
            <td>${
    
    u.key}</td>
            <td>${
    
    u.value.userid}</td>
            <td>${
    
    u.value.username}</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

效果图:
insert image description here

十、JSTL格式化标签的使用

<%@ taglib prefix=“fmt” uri=“http://java.sun.com/jsp/jstl/fmt” %>

对日期的格式化处理

<fmt:formatDate value="${data}" pattern="yyyy-MM-dd"/>

对数字格的式化处理`

<fmt:formatNumber value="${balance}" type="currency"/>

十一、MVC模式

什么是MVC模式

MVC模式:Model、View、Controller即模型、视图、控制器。是软件的一种架构模式(Architecture pattern)。MVC要实现的目标是将软件的用户界面和业务逻辑分离,可提高代码可扩展性、可复用性、可维护性、以及灵活性。

View(视图):用户的操作界面。如:html、jsp。

Model (model) : specific business model and data model. Such as: service, dao, pojo.

Controller (control) : process the request sent from the view layer, select the business model of the model layer to complete the business implementation of the response, and generate a response. Such as: Servlet.

insert image description here

The difference between MVC pattern and application layering

The MVC pattern is a way of software architecture, and application layering is a way of organizing code. The goal of the MVC pattern and application layering is the same: to decouple and improve code reusability.
insert image description here


Guess you like

Origin blog.csdn.net/TIpotencial/article/details/123702165