JavaWeb学习十(JavaBean和EL表达式)

时间:2022-06-08 19:03:20

一.JavaBean

1.JavaBean实例

public class Person {

//必须要为成员提供get/set方法(两者只提供一个也是可以的)
//必须要有默认构造器(无参的)
//一般对于具有get/set方法的成员变量称之为属性

//其实就算一个属性没有对应的成员变量,只有get/set方法也是可以的!
//属性的名称就是get/set方法去除get/set后,再把首字母小写了!

private String username;
private int age;
private String address;

public String getId() {
return "asdfghjkl";
}


public String getName() {
return username;
}


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


public int getAge() {
return age;
}


public void setAge(int age) {
this.age = age;
}


public String getAddress() {
return address;
}


public void setAddress(String address) {
this.address = address;
}

}

2.JavaBean的规范:

  • 必须要有一个默认构造器
  • 提供get/set方法,如果只有get方法,那么这个属性是只读属性!
  • 属性:有get/set方法的成员,还可以没有成员,只有get/set方法。属性名称由get/set方法来决定!而不是成员名称!(就像上面成员变量定义成username,但getName,setName,它的属性就是name,而不是username)
  • 方法名称满足一定的规范,那么它就是属性!boolean类型的属性,它的读方法可以是is开头,也可以是get开头
 private boolean bool;




public boolean isBool() {
return bool;
}

/*public boolean getBool(){
return bool;
}*/


public void setBool(boolean bool) {
this.bool = bool;
}

3.内省

JavaWeb学习十(JavaBean和EL表达式)

  • 内省类 –> Bean信息 –> 属性描述符 –> 属性的get/set对应的Method! –>可以反射
  • 导包
              commons-beanutils.jar
commons-logging.jar

我们这里提供了jar包的链接如下

内省所需jar包

 @Test
public void fun1() throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
String path="cn.st.domain.Person";
Class class1=Class.forName(path);
Object bean=class1.newInstance();

BeanUtils.setProperty(bean,"name","zhangsan");
BeanUtils.setProperty(bean,"age",12);
BeanUtils.setProperty(bean,"address","成都东软学院");

String name=BeanUtils.getProperty(bean,"name");
int age=Integer.parseInt(BeanUtils.getProperty(bean,"age"));
String address=BeanUtils.getProperty(bean,"address");

System.out.println("姓名:"+name+" 年龄:"+age+" 地址:"+address);
}

控制台打印

姓名:zhangsan 年龄:12 地址:成都东软学院

把一个Map对象封装到一个bean里面去

 @Test
public void fun2() throws IllegalAccessException, InvocationTargetException {
Map<String,String> map1=new HashMap<String,String>();
map1.put("username","zhangsan");
map1.put("password","123456789");

User user=new User();

BeanUtils.populate(user,map1);

System.out.println(user.getUsername());
System.out.println(user.getPassword());
}

User类

public class User {

private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}


}

我们可以来把map封装进一个javabean对象做成一个方法,如下所示

 public static <T> T toBean(Map map, Class<T> clazz){

try {
//创建javabean
T bean=clazz.newInstance();

//封装map到javabean对象中
BeanUtils.populate(bean,map);

//返回javabean对象
return bean;

}catch (Exception e) {
throw new RuntimeException();
}

}

我们来进行测试一下

public void fun3() {
Map<String,String> map=new HashMap<String,String>();
map.put("username","zhangsan");
map.put("password","123456789");
User user=CommonUtils.toBean(map,User.class);
System.out.println(user);

}

控制台打印

User [username=zhangsan, password=123456789]

4.jsp中与javaBean相关的标签

  • <jsp:useBean>:创建或查询bean

    • <jsp:useBean id="user1" class="cn.st.domain.User" scope="session"/> 在session域中查找名为user1的bean,如果不存在,创建之
    • <jsp:useBean id="user1" class="cn.st.domain.User" scope="session"/>
  • <jsp:setProperty>
    • <jsp:setProperty property="username" name="user1" value="admin"/> 设置名为user1的这个javabean的username属性值为admin
  • <jsp:getProperty>
    • <jsp:getProperty property="username" name="user1"> 获取名为user1的javabean的名为username属性值
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!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>
<jsp:useBean id="user1" class="cn.st.domain.User" scope="session"></jsp:useBean>
<jsp:setProperty property="username" name="user1" value="zhangsan"/>
<jsp:setProperty property="password" name="user1" value="123456789"/>
<%
out.print(session.getAttribute("user1"));

%>

</body>
</html>

页面运行效果

JavaWeb学习十(JavaBean和EL表达式)

二.EL表达式

1.EL表达式简介

(1).EL是JSP内置的表达式语言
  • jsp2.0开始不让再使用Java脚本,而是使用el表达式和动态标签来替代java脚本
  • EL替代的是<%=…%>,也就是说,EL只能做输出! JSTL标签才能设置
(2).EL表达式来读取四大域
  • ${xxx} 全域查找名为xxx的属性,如果不存在,输出空字符串,而不是null,查找范围是从小范围到大范围
  • ${pageScope.xxx},${requestScope.xxx},${sessionScope.xxx},${applicationScope.xxx}指定域获取属性!
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!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("xxx","page_xxx");
request.setAttribute("xxx","request_xxx");
session.setAttribute("xxx","session_xxx");
application.setAttribute("xxx","application_xxx");

%>


${xxx}<br/>
${pageScope.xxx} <br/>
${requestScope.xxx} <br/>
${sessionScope.xxx} <br/>
${applicationScope.xxx} <br/>
</body>
</html>

页面打印

page_xxx
page_xxx
request_xxx
session_xxx
application_xxx
(3).javaBean导航
public class Employee {
private String name;
private String salary;
private Address address;
@Override
public String toString() {
return "Employee [name=" + name + ", salary=" + salary + ", address=" + address + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}

public String getHehe() {//普通方法带get并且大写方法名中的第一个字符可以用EL表达式来获取
return "呵呵";
}
}

public class Address {

private String city;
private String stress;
@Override
public String toString() {
return "Address [city=" + city + ", stress=" + stress + "]";
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStress() {
return stress;
}
public void setStress(String stress) {
this.stress = stress;
}


}
<%@page import="cn.st.domain.Address"%>
<%@page import="cn.st.domain.Employee"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!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>
<%
Employee employee=new Employee();
employee.setName("zhangsan");
employee.setSalary("5000");

Address address=new Address();
address.setCity("chengdou");
address.setStress("京东街道");

employee.setAddress(address);

request.setAttribute("emp",employee);
%>


${emp.address.city}<br/>
${emp.hehe }
</body>
</html>

页面运行效果

chengdou
呵呵
(4).EL表达式运算符

JavaWeb学习十(JavaBean和EL表达式)

(5).EL可以输出的东西都在11个内置对象中!11个内置对象,其中10个是Map,pageContext不是map 它就是PageContext类型,1个顶9个
  • 参数的内置对象
    • param:Map<String,String>类型param对象可以用来获取参数,key是参数名,value是参数值,适用于单值的参数
    • paramValues:Map<String,String[]>类型,对应参数 key是参数名,value是多个参数值,适用于多值的参数
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!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>
<%--map.key这是el的语法!
map['key']也可以操作map
--%>

${param.username}<br/>
${paramValues.hobby[0] }<br/>
${paramValues.hobby[1] }<br/>
</body>
</html>

访问http://localhost:8080/javaweb8/el/c.jsp?username=123456789&hobby=123&hobby=321
页面打印

123456789
123
321
  • 请求头内置对象
    • header:对应请求头Map,key表示头名称,value是单个头值,适用于单值的参数,User-Agent
    • headerValues:对应请求头Map,key表示头名称,value是多个头值,适用于多值的参数
    • initParam:获取<context-param>内的参数
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!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>


${header['User-Agent'] }
</body>
</html>

页面打印效果
JavaWeb学习十(JavaBean和EL表达式)

web.xml中添加以下信息

 <context-param>
<param-name>xxx</param-name>
<param-value>XXX</param-value>
</context-param>

<context-param>
<param-name>yyy</param-name>
<param-value>YYY</param-value>
</context-param>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!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>


${initParam.xxx }<br/>
${initParam.yyy }
</body>
</html>

页面显示效果
JavaWeb学习十(JavaBean和EL表达式)

  • Cookie相关内置对象
    • cookie:Map<String,Cookie>类型,其中key是cookie的name,value是cookie对象

获取当前JSESSIONID的值

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!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>
${cookie.JSESSIONID.value }<!--这个cookie对象的值-->
${cookie.JSESSIONID.name}<!--这个cookie对象的名字-->
${cookie.JSESSIONID}<!--这个cookie对象的toString方法-->
</body>
</html>

页面显示效果

JavaWeb学习十(JavaBean和EL表达式)

  • pageContext对象
    • pageContext:他是PageContext类型
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!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.request.scheme }<!-- 协议 --><br/>
${pageContext.request.method }<!-- 请求方式 --><br/>
${pageContext.request.contextPath }<!-- 当前项目名,前面有斜线 --><br/>
${pageContext.session.id }<!-- 获取sessionid -->

</body>
</html>

页面显示效果

JavaWeb学习十(JavaBean和EL表达式)

2.EL函数库(由JSTL提供的)

注意:像Myeclipse就不需要进行导包,eclipse想使用则需要导入一个jstl的jar包

jstl-1.2.jar

  • 导入标签库: <%@ tablib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

  • String toUpperCase(String input):把参数转换成大写

  • String toLowerCase(String input):把参数转换成小写
  • int indexOf(String input,String substring):从大串 输出小串的位置
  • boolean contains(String input,String substring):查看大串中是否包含小串
  • boolean containsIgnoreCase(String input,String substring):忽略大小写的 是否包含
  • boolean startsWith(String input,String substring):是否以小串为前缀
  • boolean endsWith(String input,String substring):是否以小串为后缀
  • String substring(String input,int beginIndex,int endIndex):截取子串
  • String substringAfter(String input,String substring):获取大串中 小串所在位置后面的字符串
  • String substringBefore(String input,String substring):获取大串中 小串所在位置前面的字符串
  • String escapeXml(String input):把input中”<” “>” “&” “’” “”” 进行转义
  • String trim(String input):去除前后空格
  • String replace(String input,String substringBefore,String sustringAfter):替换
  • String [] split(String input,String delimiters):分割字符串 得到字符串数组
  • int length(Object obj):可以获取字符串 数组 各种集合的长度
  • String join(String array[],String separator):联合字符串数组
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!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>
<%
String[] strs={"a","b","c"};
List list = new ArrayList();
list.add("a");
pageContext.setAttribute("arr",strs);
pageContext.setAttribute("list",list);

%>

${fn:length(arr)}<br/>
${fn:length(list)}<br/>
${fn:toLowerCase("Hello")}<br/>
${fn:toUpperCase("Hello")}<br/>
${fn:contains("abc","a")}<br/>
${fn:containsIgnoreCase("abc","Ab")}<br/>
${fn:contains(arr,"a")}<br/>
${fn:containsIgnoreCase(list,"A")}<br/>
${fn:endsWith("Hello.java",".java")}<br/>
${fn:startsWith("Hello.java","Hell")}<br/>
${fn:indexOf("Hello-World","-")}<br/>
${fn:join(arr,";")}<br/>
${fn:replace("Hello-World","-","+")}<br/>
${fn:join(fn:split("a;b;c",";"),"-")}<br/>
${fn:substring("0123456789",6,9)}<br/>
${fn:substring("0123456789",5,-1)}<br/>
${fn:substringAfter("Hello-World","-")}<br/>
${fn:substringBefore("Hello-World","-")}<br/>
${fn:trim(" a b c ")}<br/>
${fn:escapeXml("<html></html>")}
</body>
</html>

打印效果

3
1
hello
HELLO
true
true
true
true
true
true
5
a;b;c
Hello+World
a-b-c
678
56789
World
Hello
a b c
<html></html>

3.自定义函数库

  • 写一个Java类,类中可以定义0-N个方法,必须是静态的,必须有返回值
public class ELUtils {
public static String fun() {
return "0123456789";
}
}
  • 在WEB-INF目录下创建一个tld文件
           <?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"

version="2.0">



<description>sstt</description>
<tlib-version>1.0</tlib-version><!--版本-->
<short-name>st</short-name><!--短名-->
<uri>http://www.harmel.cn/tag</uri><!--随便写地址-->

<function>
<name>fun</name><!--方法名-->
<function-class>cn.st.common.util.ELUtils</function-class><!--类所在包-->
<function-signature>java.lang.String fun()</function-signature><!--返回类型 以及方法()-->
</function>

</taglib>
  • 在web.xml设置路径
  <jsp-config>
<taglib>
<taglib-uri>http://www.harmel.cn/tag</taglib-uri>
<taglib-location>/WEB-INF/tag/harmel.tld</taglib-location><!--tld所在路径-->
</taglib>
</jsp-config>
  • 在jsp页面中导入标签库
<%@ taglib prefix="st" uri="http://www.harmel.cn/tag" %>//uri写上面web.xml配置的路径
  • 在jsp页面中使用自定义的函数
  ${st:fun() }

页面打印效果

0123456789

END!!!!!!!!!!!!!!!!!