JavaBean and EL expressions

Keywords: Java Eclipse server

Learning objectives
1: JavaBean
2: EL expression
Learning content
1: Initial JavaBean
1,1 what is a JavaBean
JavaBean is a reusable software component in java development language. Its essence is a Java class.
In order to standardize the development of JavaBeans, Sun company released the JavaBean specification, which requires a standard JavaBean component to follow certain coding specifications, as follows.
1) It must have a public, parameterless constructor, which can be the default constructor automatically generated by the compiler
(2) It provides public setter and getter methods for external programs to set and obtain JavaBean properties. In order to make readers have an intuitive understanding of JavaBeans, next, write a simple JavaBean. First, create a Web project named Chapter8 in Eclipse, then create a package named cn.itcast.chapter8.javabean in the SrC directory of the project, and then create a Book Class under the package. The code is as follows.

package cn.itcast.chapter8;

public class Book {
	
	private double price;
	public double getPrice() {
	return price;
	}
	public void setPrice(double price) {
	this.price =price;
	}
}

1.2 accessing properties of Java beans
When explaining object-oriented, we often use class attributes, which refer to class member variables. There are also attributes in JavaBean s, but they are not a concept with member variables. They appear in the form of method definitions. These methods must follow certain naming conventions.
A relationship between member variables and attributes of a class:
In ordinary java classes, member variables can be said to be attributes.
In JavaBean s, there are differences between member variables and attributes.
What is a member variable in a JavaBean? For example: private String id; Then id is the member variable
What are properties in a JavaBean? It is the field name after get or set (the first letter of the field name is lowercase), which is the attribute.
For example:

public class Student {
		//Here are the four member variables of javaBean
		private String sid;//The purpose is to receive the value passed from the outside world
		private String name;
		public Student() {
			
		}
		//The attribute consists of the field after the get or set method. The initial lowercase is the attribute, and the attribute is the id
		public String getId() {
			return sid;
		}
		public void setId(String id) {//Write method, write an id to the student
			this.sid = id;
		}
		//The attribute is name
		public void setName(String name) {
			this.name = name;
		}
	}

1.3 BeanUtils tool
Most Java program developers used to create JavaBeans and then access properties by calling getter and setter methods of JavaBean property pairs. However, due to the endless emergence of various java tools and frameworks, the corresponding getter and setter methods can not always be called. Therefore, it is very necessary to dynamically access the properties of Java objects. In this regard, the Apache Software Foundation provides a set of simple and easy-to-use API - BeanUtils tool. Mastering its use will help to improve the efficiency of program development. This section will explain the relevant knowledge of BeanUtils tool in detail.
Up to now, the latest version of BeanUtils is Apache Commons BeanUtils 1.9.x. readers can Download the corresponding version as needed. The homepage address of the official website of BeanUtils toolkit is“ http://commons.apache.org/propercommons-beanutils ”, after logging in to the homepage of the official website, click bean utils → Download in the left menu bar to jump to the Download page of BeanUtils
example
(1) Add the downloaded Commons beautils - 1.9.2.JAR and Logging JAR package commons -logging-1.2.jar in the lib directory of the chapter8 project, and publish the two JAR packages to the classpath.
(2) Create a package named cn.itcast.chapter8 under the src directory of the project, and create a Person class under the package. The Person class defines two properties: name and age, and provides corresponding getter and setter methods for the outside world to access these two properties. The specific code is shown in the figure below:

package cn.itcast.chapter8;

public class Person {
	
	private String name;private int age;
	public String getName() {
	return name;
	}
	public void setName(String name) {
	this.name = name; 
	}
	public int getAge() {
	return age;}
	public  void setAge(int age) {
	this.age = age;
	}
	public Person() {
	super();
	}
	public String toString() {
	return"Person[name="+name +",age="+ age +"]";
	
}
}

(3) Create the BeanUtilsDemo class under the package of cn.itcast.chapter8, which uses the common methods of the BeanUtils class, as shown in the following figure:

package cn.itcast.chapter8;
import java.util.HashMap;
import java.util.Map;
public class BeanUtilsDemo {
	 

	 public static void main(String[] args) throws Exception{
	 Person p = new Person();
	/* BeanUtils.setProperty(p,"name","zrb");
	 BeanUtils.setProperty(p,"age","20");
	 Stringname = BeanUtils.getProperty(p,"name");
	 int' age = Integer.parseInt(BeanUtils.getProperty(p,"age")); System.out.println(name);
	 System.out.println(age);
	 */
	 Map<String,Object> map= new HashMap<String,Object>();
	 map.put("name", "zrb");
	 map.put("age",20);
	  BeanUtils.populate(p,map);
	  String name=BeanUtils.getProperty(p,"name");
	 int age=Integer.parseInt(BeanUtils.getProperty(p,"age"));
	  System.out.println( name);
	  System.out.println(age);
	 

}
}

2. Getting to know EL
2.1 initial knowledge of EL expression
In development, EL is usually used to obtain the value saved in the domain object. The basic syntax is ${name of domain object}.
For example: request.setAttribute("key", "value123"): ${key}, the obtained value is value123
If the name of the domain object is misspelled, use the el expression to get the value, which is ""

example
(1) Create a package named cn.itcast.chapter8.servlet under the src directory of the project, and create a class MyServlet for storing user name and password under the package, as shown in the following figure:

package cn.itcast.chapter8.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class myservlet
 */
@WebServlet("/myservlet")
public class myservlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public myservlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setAttribute("username", "Big data 2003 zrb");
		request.setAttribute("password", "1314520");
		RequestDispatcher dispatcher=request.getRequestDispatcher("/myjsp.jsp");
		dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

(2) Write a JSP file named myjsp in the WebContent directory and use the file to output the storage information, as shown in the following figure:

<%@ 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>
	user name:<%=request.getAttribute("username") %><br/>
	password:<%=request.getAttribute("password") %><br/>
	<hr/>
	use EL expression:<br/>
	user name:${username}<br/>
	password:${password}<br/>
</body>
</html>

(3) Start the Tomcat server and enter in the browser address bar“ http://localhost:10081/chapter8/myservlet ”Access the MyServlet page from the following address:

2.2 identifier in El expression
In the process of el writing, some symbols are used to mark variables, function names, etc. these symbols are called identifiers.
Writing specification:
1. Cannot start with a number
2. Keywords in el cannot be included: and, or, etc
3. The implicit object of el expression cannot be used.
4. It cannot contain special symbols, such as forward slash, etc

2.3 variables in El
Basic format: ${name of domain object}. The name of this domain object can be understood as a variable in el,
Then this variable does not need to be defined and can be used directly.

2.4 constants in El
1. Boolean constant: true or false
2. Numeric constants: integer and floating-point constants, which are used in the same way as java
3. String constant: similar to java, for example: "string constant of e l" 4. N u l constant: {"string constant of el"} 4.Null constant: "string constant of el" 4.Null constant: {null}

2.5 operators in El
1. Dot operator: get the value of the attribute in the domain object.
For example:

${person.name }

2. Square bracket operator: in the domain object, some attributes contain special characters, so the value is obtained in square brackets
For example:

 <% 
 		Map<String,String> map= new HashMap<String,String>();
		map.put("my-name","map Value of");
		request.setAttribute("user",map);
	  %>
	${user["my-name"] }

3. Arithmetic operator: + - */
Write in the myjsp.jsp file

Start the Tomcat server and enter the address in the browser address bar“ http://localhost:10081/chapter8
/"MyServlet" to access the MyServlet page

4. Comparison operator: > < > = < = ==

Write in the myjsp.jsp file

Start the Tomcat server and enter in the browser address bar“ http://localhost:10081/chapter8
/Access the MyServlet page from the "MyServlet" address
effect

5. Logical operator: & & (and) | (or)! (not)
6.empty operator: used to judge whether the value in the domain object exists. If it does not exist, it returns true, otherwise the returned result is false
Write in the myjsp.jsp file

Start the Tomcat server and enter the address in the browser address bar“ http://localhost:10081/chapter8/myservlet ”Access my servlet page

EL implicit object
1.pageContext object: to obtain the implicit object in jsp.
For example:

Get the path of the project: ${pageContext.request.contextPath }<br/>
	 Get requested URL:${pageContext.request.requestURI }

Write a JSP file named pageContext.jsp in the WebContent directory,
The code is as follows:

<%@ 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>
	request URL by:${pageContext.request.requestURI}<br/>
	Content-Type Response header:${pageContext.response.contentType}<br/>
	The server information is: ${pageContext.servletContext.serverInfo}<br/>
</body>
</html>

Start the Tomcat server and enter the address in the browser address bar“ http://localhost:10081/chapter8/pageContext.jsp ”Access the pagecontext page, and the effect is shown in the following figure:

2.web domain related objects
Scope from small to large: pageContext - > request - > session - > Application (ServletContext)
el expression gets the value in the domain object: if the domain object has the same name, it gets the value with the smallest scope of the domain. The effect is the same as that of the findAttribute method of the pageContext object.

example
(1) Write a JSP file named scopes.jsp in the WebContent directory,
The code is shown in the figure below

<%@ 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>
	<% pageContext.setAttribute("page", "PAGE");
	request.setAttribute("request", "REQUEST");
	session.setAttribute("session", "SESSION");
	application.setAttribute("application", "APPLICATION");
	%>
	${pageScope.page}===${page}<br/>
	${requestScope.request}==${request}<br/>
	<% pageContext.setAttribute("aa1","PAGE");
	request.setAttribute("aa2", "REQUEST");
	session.setAttribute("aa","SESSION");
	application.setAttribute("aa", "APPLICATION");
	%>
	${pageScope.aa}===${aa }<br/>
	${requestScope.aa}===${aa }<br/>
	=====================================<br/>
	${aa}
</body>
</html>

(2) Start the Tomcat server and enter the address in the browser address bar“ http://localhost:10081/chapter8/scopes.jsp ”Visit the scopes page, and the effect is shown in the following figure:


3.param and paramValues objects
Get the data submitted by the form.
For example:

 num1:<input type="text" name="num1" /><br/>
	num2:<input type="text" name="num" /><br/>
	num3:<input type="text" name="num" /><br/>
	<input type="submit" value="Submit" /> &nbsp;&nbsp;<input type="reset" value="Refill" />
	<hr/>
	num1:${param.num1 }<br/>
	num2:${paramValues.num[0] }<br/>
	num3:${paramValues.num[1] }

example
(1) Write a JSP file named param.jsp in the WebContent directory. The code is as follows:

<%@ 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>
	<form action="${pageContext.request.contextPath }/parm.jsp">
		num1:<input type="text" name="num1"><br/>
		num2:<input type="text" name="num"><br/>
		num3:<input type="text" name="num"><br/><br/>
		<input type="submit" value="Submit" />&nbsp;&nbsp;
		<input type="submit" value="Reset" /><hr />
		num1:${param.num1}<br/>
		num2:${paramValues.num[0]}<br/>
		num3:${paramValues.num[1]}<br/>
	</form>
</body>
</html>

(2) Start the Tomcat server and enter the address in the browser address bar“ http://localhost:10081/chapter8/param.jsp ”Visit param page, and the effect is shown in the following figure:

4. Cookie object
Get the name of the cookie and get the value of the cookie
For example:

<% response.addCookie(new Cookie("userName","itcast")); %>
		obtain cookie Object: ${cookie.userName }<br/>
		obtain cookie Name of: ${cookie.userName.name }<br/>
		obtain cookie Value of: ${cookie.userName.value }<br/>

example
(1) Write a JSP file named cookie.jsp in the WebContent directory. The code is as follows:

<%@ 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>
<% response.addCookie(new Cookie("username","ZHANGRONGBO")); %>
obtain cookie Object: ${cookie.username} <br/>
obtain cookie Object name: $ {cookie.username.name} <br/>
 obtain cookie Object value: ${cookie.username.value} <br/>
</body>
</html>

(2) Start the Tomcat server and enter the address in the browser address bar“ http://localhost:10081/chapter8/cookie.jsp ”Visit param page, and the effect is shown in the following figure:

2020080603052

Posted by kday on Sat, 20 Nov 2021 19:52:46 -0800