Stage 2 Lesson 16 JSP core technology

Course review

The concept of JSP

JSP execution process

The relationship between JSP and Servlet

Difference: there are three things about Servlet: ① get data ② call business methods ③ process control, and JSP focuses on data display.

Contact: JSP is Servlet. JSP inherits HttpServlet.

EL expression

${} can access scope data

Comprehensive case

Nine built-in objects

What are built-in objects

Built in object is the object that can be used directly in JSP. We need new to create ordinary object, but built-in object can be used directly without creation. Built in object is created by server and passed to JSP page object.

Nine built-in objects

  1. Request object: get request data HttpServletRequest
  2. Response object: response data object HttpServletResponse
  3. Session object: session object, which stores the user's session information HttpSession
  4. Application object: application app, DAMA,application represents the entire web application ServletContext
  5. Page Object: current page Object
  6. PageContext object: the current page context object PageContext
  7. Exception object: indicates the page's exception information Throwable
  8. config object: indicates the configuration information of jsp, ServletConfig
  9. out object: output data to browser JspWriter output stream object, character

request object

Obtain the information submitted by the client and the information of the server itself;

  • reques.getParamter("name") gets a single value
  • request.getParameterValues("check box") get multiple values String []
  • request.getParameterNames(); return enumeration
  • request.getParameterMap(); return map < string, string [] >
  • request.getContextPath(); return web and path information
  • request.getRequestDispatcher("path"). Forward (request, response); forward

response object

Response object to send data to the client browser.

  • response.sendRedirect( “ fail.jsp ”); redirection
  • response.setContextType(""); sets the content type of the browser response
  • response.setHeader("key", "value"); set response header information
  • response.addHeader("key", "value"); add response header information
  • response.getOutputStream(); get output byte stream object
  • response.getWriter(); get output character stream object
  • response.addCookie (Cookie); add Cookie information

session object

Represents client and server sessions, browser and server multiple requests and responses. The process of shopping is conversation, multiple interactions with the server.

Next class with Cookie

application object

It is a ServletContext object, a global object. When the server loads the web application to create the object, the server stops unloading the web application, and the server stops destroying the object. Declaration cycle is accompanied by web application, so it is not suitable to store a large amount of data, which will always occupy server memory.

  • application.setAttribute( "key", "value" );
  • application.getAttribute("key");
  • application.getAttributeNames(); / / get all property names
  • application.removeAttribute("key"); delete attribute
  • application.getRealPath("image/00.jpeg"); get the real path of the file
  • application.getContextPath(); get the project name of the web application
  • application.getResourceAsStream( “/WEB-INF/classes/jdbc.properties ”); / / Note: classes/config/jdbc.properties

page object

Page represents the current page Object. The type of the Object is Object. There is no special method for this Object. All methods are Object object Object methods.

This object is a reference to the page instance. It can be seen as a representation of the entire JSP page. Page object is synonymous with this object.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
out.println( page );
%>
</body>
</html>

pageContext object

The pageContext object represents the environment of the page and is used to represent the entire JSP page; this object stores the references of the request object and the response object. application object, config object, session object and out object can be exported by accessing the properties of this object.

pageContext object also contains instruction information passed to JSP page, including cache information, ErrorPage URL, page scope, etc.

The PageContext class defines some fields, including PAGE_SCOPE,REQUEST_SCOPE,SESSION_SCOPE, APPLICATION_SCOPE. It also provides more than 40 methods, half of which are inherited from javax.servlet.jsp.JspContext class.

pageContext scope method

  • pageContext.setAttribute("key","value")
  • pageContext.getAttribute( "key" )
  • pageContext.getAttribute("key", scope)
  • pageContext.getAttributeNamesInScope (SCOPE)
  • pageContext.removeAttribute("key")

exception object

Display exception information,

a.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" errorPage="ex.jsp" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
out.println(5/0);
%>
</body>
</html>

b.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" isErrorPage="true" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Error page</title>
</head>
<body>
//Error message: <%= exception.getMessage () %>
</body>
</html>

config object

ServletConfig type, get configuration information,

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Config object: <br/>obtain ServletName:<%=config.getServletName() %><br/>
//Get ServletContext object: <%= config.getServletContext ().getContextPath() %><br/>

</body>
</html>

out object

That outputs data to the client browser. out object is javax.servlet.jsp An instance of the. Jspwriter class that writes to the response object.

  • out.println(); supports output of various data types
  • out.flush(); refresh buffer
  • out.close(); close output stream
  • out.write(); output data

Four scope objects

Scope: pageContext current page < request request < session session < application object

page.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
out.println( page );
pageContext.setAttribute("name", "Zhao Min");
pageContext.setAttribute("age", 30, PageContext.REQUEST_SCOPE);
request.setAttribute("req_address", "Emei School of Emei in Sichuan Province");
session.setAttribute("ses_money", 10000);
application.setAttribute("app", "Xinyang green tea-Hair tip");
%>
<h1>Value</h1>
pageContext Default scope for:  <%=pageContext.getAttribute("name") %><br/>
pageContext Specified scope of: <%=pageContext.getAttribute("age", PageContext.REQUEST_SCOPE) %><br/>
request Scope of: <%=request.getAttribute("req_address") %><br/>
session Scope of: <%=session.getAttribute("ses_money") %><br/>
application Scope of:<%=application.getAttribute("app") %>

<%
//response.sendRedirect("show.jsp");
request.getRequestDispatcher("show.jsp").forward(request, response);
%>

</body><br/>
</html>

show.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1>Value</h1>
pageContext Default scope for:  <%=pageContext.getAttribute("name") %><br/>
pageContext Specified scope of: <%=pageContext.getAttribute("age", PageContext.REQUEST_SCOPE) %><br/>
request Scope of: <%=request.getAttribute("req_address") %><br/>
session Scope of: <%=session.getAttribute("ses_money") %><br/>
application Scope of:<%=application.getAttribute("app") %>
</body>
</html>

Summary:

  • The default property of pageContext is the current page, which can't be obtained whether it's forwarding or redirecting
  • pageContext.setAttribute(“age”, 30, PageContext.REQUEST_SCOPE); specifies that scope forwarding can be obtained, and redirection cannot be obtained
  • request scope: forwarding is OK, redirection is not OK
  • session scope: both forwarding and redirection are OK, but only for the current client browser
  • application scope: all can be obtained, shared data can be stored, number of people online, and cases can be explained when they arrive at the listener

EL expression explanation

EL Express Language expression language, ${} is used to simplify the coding of JSP pages. JSP technology is used to display data, but there is a lot of Java code. How to optimize and simplify java code? EL is one solution and another JSTL.

EL can access objects of four scopes, and supports accessing the properties of objects, arrays and collection classes. Common arithmetic operators, + - * / and so on are also supported. Application scenario of EL expression:

  1. Get the value of the variable
  2. Get the property value of the object
  3. Get elements of array
  4. Get elements of collection
  5. Get execution expression

1. Get the value of the variable

Search according to the scope sequence of page → request → session → application, and return when found, and return null when not found. You can also specify the scope:

Property range Name in EL
page Pagescope, for example${ pageScope.username }Indicates to find the variable username in the page scope, and return null if not found
request requestScope
session sessionScope
application applicationScope
package com.ujiuye.controller;

import java.io.IOException;

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 com.ujiuye.serivce.UserService;
import com.ujiuye.serivce.impl.UserServiceImpl;
@WebServlet("/userServlet")
public class UserServlet  extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private UserService userService = new UserServiceImpl();
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1. Get the value of the variable: the variable can be defined by itself, passed in by the outside world, or database
		String name = "Hu Yidao";
		String age  = request.getParameter("age");
		int count = userService.getCount();
		request.setAttribute("name", name);
		request.setAttribute("age", age);
		request.setAttribute("count", count);
		
		request.getRequestDispatcher("el.jsp").forward(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}

2. Get the property value of the object

Syntax: ${object name. Property name} access getter method

package com.ujiuye.controller;

import java.io.IOException;

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 com.ujiuye.entity.User;
import com.ujiuye.serivce.UserService;
import com.ujiuye.serivce.impl.UserServiceImpl;
@WebServlet("/userServlet")
public class UserServlet  extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private UserService userService = new UserServiceImpl();
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1. Get the value of the variable: the variable can be defined by itself, passed in by the outside world, or database
		String name = "Hu Yidao";
		String age  = request.getParameter("age");
		int count = userService.getCount();
		request.setAttribute("name", name);
		request.setAttribute("age", age);
		request.setAttribute("count", count);
		//2. Get the property value of the object
		String userCode = request.getParameter("userCode");
		User user = userService.findById(userCode);
		request.setAttribute("u", user);
		request.getRequestDispatcher("el.jsp").forward(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}

el.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Accessing the value of a variable</h1>
Custom variable: ${name }, Incoming parameter variable: ${age }, Database data: ${count } <br/>
<h1>Value of access object</h1>
userCode:  ${u.userCode },loginCode: ${u.loginCode },userName:${u.userName }<br/>
</body>
</html>

3. Get elements of array

//3. Get the elements of the collection. The array can also
String [] citys = {"Beijing","Shanghai","Hangzhou","Zhengzhou City"};
List<String> list = new ArrayList<>();
list.add("zhang wuji");
list.add("Zhao Min");
list.add("Xiaozhao");
List<User> ulist = userService.findAll();
request.setAttribute("list", list);
request.setAttribute("ulist", ulist);
request.setAttribute("citys", citys);

el.jsp

<h1>Accessing the value of an array</h1>
Arrays: ${citys[0]}, ${citys[1]}, ${citys[2]},
<h1>Access the value of the collection List</h1>
Common data: list [0] = ${list [0]}, list [1] = ${list [1]}, list [2] = ${list [2]}, list [3] = ${list [3]} < br / >
Object data: userList: ${ulist [0]. Username}, ${ulist [1]. Username}

4. Get elements of collection

//4. Get Map data
Map<String, String> map1 = new HashMap<String, String>();
map1.put("k1", "White browed eagle king");
map1.put("k2", "Exterminate abbess");
request.setAttribute("m1", map1);
Map<String,User> map2 = new HashMap<String, User>();
map2.put("uk", user);
request.setAttribute("m2", map2);

el.jsp

<h1>visit map Data in</h1>
//Simple map: K1 = ${M1. K1}, K2 = ${M1. K2} < br >
//Object map: ${m2 uk.userName  } === ${m2. uk.password  }

5. Get execution expression

//5. Calculate the value of the expression
String sex = null;
request.setAttribute("sex", sex);
request.getRequestDispatcher("el.jsp").forward(request, response);

el.jsp

<h1>Accessing the value of an expression</h1>
5> 3 ${5 > 3} < br / > empty determines whether the string is null or 0 in length: ${empty sex};

JSTL tag library

JSTL: JSP standard tag library Java standard tag library; provides a set of standard tags, which is also used to simplify the writing of Java code. EL can't make logical judgment and if, for loop. For example, we need to display the List collection on the page, write java code, how to simplify it, and use JSTL. Build development environment:

  1. Add jar package: jstl1.2.jar
  2. Introduce tag library in JSP page <% @ taglib prefix = "c" uri=“ http://java.sun.com/jsp/jstl/core ”%>Taglib instruction
    1. Prefix of prefix tag library, which can be customized. Generally, core tag prefix is c
    2. Format format label: <% @ taglib prefix = "FMT" uri=“ http://java.sun.com/jsp/jstl/fmt ” %>

The JSTL tag library includes the following set of tags:

  1. core tags: the most commonly used
  2. fmt format label: commonly used
  3. Function tag: function tag, mainly used to process String, String truncation, secondary common
  4. sql label: database label. You can directly access the database on the jsp page. It does not conform to the three-tier structure. Generally, it is not used
  5. xlm Tags: processing XML files or data, rarely using

Note: the development mode is front-end and back-end separated, the front-end engineer uses HTML Vue; JSP technology is not used, so there is a B-station up main saying that JSP can be eliminated, but JSP is the basis of our understanding of modern development mode, so it is necessary to understand that JSP needs Tomcat environment, after the front-end and back-end separated, the front-end engineer does not use Tomcat development, so it is impossible to use JSP, it is Vue. By sending AJAX requests to get data, axios is a JavaScript library to send requests.

core tag

General label: C: Set C: out C: remove

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<c:set var="name" value="Zhang Sanfeng" scope="request"></c:set>
<c:set var="age" value="65" scope="request"></c:set>
<c:remove var="age"/>
//Name: < C: out value = "${name}" > < C: out > < br / >
//Age: < C: out value = "${age}" >
</body>
</html>

Condition label: C: if C: choose

LoginServlet.java

package com.ujiuye.controller;

import java.io.IOException;

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 com.ujiuye.entity.User;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Get User name and password, call business class, return User object
		User user = new User();
		user.setUserName("admin");
		request.setAttribute("u", user);
		request.getRequestDispatcher("jstl.jsp").forward(request, response);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}

jstl.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>c:if label</h1>

<c:if test="${ empty u }">
<h3>User login</h3>
<form action="userServlet?flag=login" method="post">
User account: <input type="text" name="username"/><br/>
User password: <input type="text" name="password"/><br/>
<input type="submit" value="Sign in"/>
</form>
</c:if>
<c:if test="${! empty u }">
<h3>Welcome to ${u.userName}</h3>
</c:if>
</body>
</html>

Iteration label: c:forEach

LoginServlet.java

package com.ujiuye.controller;

import java.io.IOException;
import java.util.List;

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 com.ujiuye.entity.User;
import com.ujiuye.serivce.UserService;
import com.ujiuye.serivce.impl.UserServiceImpl;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private UserService userService = new UserServiceImpl();
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Get User name and password, call business class, return User object
		User user = new User();
		user.setUserName("admin");
		request.setAttribute("u", user);
		
		List<User> list = userService.findAll();
		request.setAttribute("list", list);
		request.getRequestDispatcher("jstl.jsp").forward(request, response);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}

jstl.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
#t1{
	border: 1px solid #000;
	width: 1000px;
	border-collapse: collapse;
}

#t1 tr td, #t1 tr th{
	border: 1px solid #000;
}
</style>
</head>
<body>
<h1>c:forEach ergodic</h1>
<table id="t1">
	<tr>
		<th>User number</th>
		<th>User code</th>
		<th>Login account</th>
		<th>User name</th>
		<th>User password</th>
		<th>mail box</th>
	</tr>
	<c:forEach items="${list}" var="u" varStatus="s">
	<tr <c:if test="${s.index % 2 == 0 }" > style="background-color:#CCCCFF" </c:if>   >
		<td> ${s.index }</td>
		<td> ${u.userCode } </td>
		<td> ${u.loginCode } </td>
		<td> ${u.userName }</td>
		<td> ${u.password }</td>
		<td> ${u.email } </td>
	</tr>
	</c:forEach>
</table>
</c:if>
</body>
</html>

Multiplication table

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>c:ForEach Multiplication table</h1>
<c:forEach begin="1" end="9" step="1" var="i">
	<c:forEach var="j" begin="1" end="${i}" step="1">
	  ${j} * ${i} = ${j*i}&nbsp;&nbsp;&nbsp;&nbsp; 
	</c:forEach>
	<br>
</c:forEach>
</body>
</html>

Traverse Map

//c:forEach traversal map
Map<String, String> map1 = new HashMap<String, String>();
map1.put("k1", "White browed eagle king");
map1.put("k2", "Exterminate abbess");
request.setAttribute("m1", map1);

User u1 = new User("Zhou Zhiruo","zhouzhiruo@163.com");  
User u2 = new User("Xiaozhao","xiaozhao@sohu.com");
Map<String, User> map2 = new HashMap<String, User>();
map2.put("u1", u1);
map2.put("u2", u2);
request.setAttribute("m2", map2);

request.getRequestDispatcher("jstl.jsp").forward(request, response);

jstl.jsp

<h1>c:forEach ergodic Map aggregate</h1>
<h4>Ergodic ordinary Map</h4>
<c:forEach var="entry" items="${m1}">
${entry.key }---->${entry.value }<br/>
</c:forEach>
<h4>Traversal object Map</h4>
<c:forEach var="u" items="${m2}">
${u.key}---${u.value.userName }---${u.value.email }<br/>
</c:forEach>

Three layer structure

Data access layer

Business logic layer

Presentation layer

Comprehensive case: single table addition, deletion, modification and query

According to the three-tier structure.

Tags: JSP Java Session Database

Posted on Fri, 05 Jun 2020 03:32:36 -0700 by stemp