Session的追踪技术
调用request.getSession()方法都会为client创建一个session空间。
不是说server端的Session空间丢失了,而是在server端找到打开相应Session空间的钥匙(JSESSIONID)丢失了。这时就须要使用Session的追踪技术。
不会导致session丢失(正常关闭server后,会在server中将session存储起来。再次启动server的时候 会被又一次载入到内存中)
<session-timeout>30</session-timeout>
</session-config>
public class SessionDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// session域对象
HttpSession session = request.getSession();
session.setAttribute("username", "小风");
// DD64756D56885AF87E883B887BF77E6C jsessionid=DD64756D56885AF87E883B887BF77E6C
System.out.println(session.getId()); response.sendRedirect("/day12/session2"); } public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }
SessionDemo2.java /session2
package cn.itcast.session; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; public class SessionDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 手动传入jsessionid=DD64756D56885AF87E883B887BF77E6C
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username"); response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("<h4>訪问到了..."+username+"</h4>"); } public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzA4NzUxMw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzA4NzUxMw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
JSP设置与页面的凝视
JSP指令元素
page指令标记
- language:声明使用脚本的种类,即JSP文件执行嵌入的语言。眼下仅仅支持Java一种语言(不须要改变)比如:language="java"
- extends:JSP翻译成Servlet的Java文件时。Servlet继承的类(不须要改变)比如:extends="src.class"
- session:比如session="true",指定一个Http会话是否使用session对象。默认值是true 能够直接使用session。
设置成false不能直接使用session(假设设置成false 要想获取session 仅仅能使用Java代码 <% HttpSession session2 = request.getSession() %>)
- import: 用于导入Java包或类的列表 (能够使用后多次 import="java.util.Date")
- buffer:指定JSP对client输出缓冲区的大小,默认是8kb (buffer="8k")
- autoFlush:设置默认自己主动刷新缓冲区(不须要改变),假设buffer溢出。设置成true时正常输出。设置成false时 出现异常 (autoFlush="true")
- errorPage: 处理异常事件时调用的JSP页面 ,指定错误页面 (errorPage="error.jsp")
- isErrorPage:设置此页能否够为其他页的errorPage目标 (设置值为true,能够是exception对象。设置成false不能使用exception对象)
- contentType:定义JSP页面响应的MIME类型(指定server端输出全部内容採用的编码 contentType="text/html,charset=utf-8")
- pageEncoding:JSP页面字符编码,其优先权高于contentType(JSP翻译成Servlet文件时採用的编码 pageEncoding="gb2312")
- isELIgnored:用于指定EL(表达式语言)是否被忽略。true则忽略,false则计算表达式的值 (isELIgnored="false")
配置全局的错误页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isErrorPage="true" %>
<!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> <h3>亲,server正在维护。!</h3> <%=exception.getMessage() %> </body>
</html>
404.jsp
<%@ 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> <h3>亲。您訪问的资源恋爱了,不在服务区!! </h3> </body>
</html>
500.jsp
<%@ 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> <h3>亲。server正在维护,这回是真的维护!! </h3> </body>
</html>
demo.jsp
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" session="true" buffer="8kb" autoFlush="true"
errorPage="/jsp/error.jsp" isELIgnored="false"%> <!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> <h4>欢迎</h4> <%
List list = new ArrayList();
// int a = 10 / 0;
request.setAttribute("username", "小风");
%> <!-- HTML的文本 -->
${ username } </body>
</html>
首先測试errorPage属性,屏蔽demo.jsp代码中除了 int a=10/0; 以外的代码 执行结果例如以下:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzA4NzUxMw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
include指令标记
nm=browser" %>
main.jsp
<%
String s = “abc”;
%>
<%include file=“part.jsp” %>
part.jsp
<%=s %> 未定义变量s
虽然part.jsp本身会有错误
可是执行main.jsp就能够正确引入part.jsp
測试include。在WebRoot中新建include目录,在include目录内新建body.jsp、head.jsp、foot.jsp、menu.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!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> <%@ include file="/include/head.jsp" %>
<%@ include file="/include/menu.jsp" %>
<h3>站点的新闻(数据变化)</h3>
<%@ include file="/include/foot.jsp" %> </body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <h3>站点的LOGO</h3>
<% int a = 100; %>
menu.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <h3>站点的超链接</h3>
<%= a %>
foot.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h3>站点的友情链接</h3>
执行结果:
打开Tomcatserver中的工作文件夹:
JSP九大内置对象
内置对象 | 真实的对象 | 方法 |
request | HttpServletRequest | setAttribute() getAttribute() |
response | HttpServletResponse | addCookie() getWriter() |
session | HttpSession | setAttribute() getAttribute() |
application | ServletContext | setAttribute() getAttribute() |
config | ServletConfig | getInitParameter() getInitParameterNames() |
exception | Throwable(全部的异常父类) | getMessage() |
page | Object | (当前的Servlet对象 this(HttpServlet)) |
out | JspWriter | write() print() |
pageContext | PageContext | setAttribute() getAttribute() |
详细能够查看 由JSP翻译成的Servlet对象 查看例如以下:
- "page" 对象代表了正在执行的由JSP文件产生的类对象(一般不建议使用)
- page对象是指向当前JSP程序本身的对象this
- page对象事实上是java.lang.Object类的实例对象
- 向client输出数据
- 管理server输出缓冲区
- 内部使用PrintWriter对象来输出文本级数据
- 通过page指令的buffer属性来调整缓冲区的大小。默认的缓冲区是8kb
<%@ 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> <!-- BBBB HELLO AAAA CCCC -->
<%= "HELLO" %>
<% out.print("AAAA"); %>
<% response.getWriter().print("BBBB"); %>
<% out.print("CCCC"); %> </body>
</html>
查看最后返回的页面源码例如以下:
<%@ 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> <%=request.getParameter("username") %> <h4>pageContext向其它域中存入值</h4>
<%
pageContext.setAttribute("name", "美美");
// 以下这句等价于上面
pageContext.setAttribute("name", "美美", pageContext.PAGE_SCOPE); request.setAttribute("name", "小凤");
// 向request域中存入值
pageContext.setAttribute("name", "小凤", pageContext.REQUEST_SCOPE); // 向session域存入值
pageContext.setAttribute("name", "小苍", pageContext.SESSION_SCOPE);
// 向ServletContext域存入值
pageContext.setAttribute("name", "小班长", pageContext.APPLICATION_SCOPE); %> <%= pageContext.getAttribute("name", pageContext.SESSION_SCOPE)%>
<%= session.getAttribute("name") %> ${ pageScope.name }
${ requestScope.name }
${ sessionScope.name }
${ applicationScope.name } </body>
</html>
JSP标签
<jsp:forward> 和 <jsp:param>
<jsp:forward page={"relativeURL" | "<%= expression %>"} >
<jsp:param name="PN" value="{PV | <%= expression %>"}/> *
</jsp:forward>
request.getRequestDispatcher.forward(“XXX”);
System.out.println(“It can execute…”);
可是JSP中<jsp:forward>后面的代码不会运行,由于翻译的时候,Serlvet容器自己主动为<jsp:forward>后面加入了return语句,比如:
<%
String s=request.getRemoteAddr();
if(s.startsWith("10.28.176.",0)){
%>
<jsp:forward page="index_inner.jsp"/>
<%}else{ %>
<jsp:forward page="index_outter.jsp"/>
<%
}
%>
<jsp:include>与include指令的比較
- <jsp:include>标签是动态引入,<jsp:include>标签涉及到的2个JSP页面会被翻译成2个servlet,这2个Servlet的内容在运行时进行合并。
- 而include指令是静态引入。涉及到的2个JSP页面会被翻译成一个Servlet。其内容是在源文件级别进行合并。
- 无论是<jsp:include>标签,还是include指令,它们都会把两个JSP页面内容合并输出,所以这两个页面不要出现反复的HTML全局架构标签,否则输出给client的内容将会是一个格式混乱的HTML文档。
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzA4NzUxMw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <%
int a = 10;
%> <%= a %>
<h3>站点的LOGO</h3>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <h3>站点的超链接</h3>
foot.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h3>站点的友情链接</h3>
body.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body> <jsp:include page="/action/head.jsp"></jsp:include>
<jsp:include page="/action/menu.jsp"></jsp:include> <h3>站点的新闻(数据变化)</h3>
<jsp:include page="/action/foot.jsp"></jsp:include> </body>
</html>
执行结果例如以下:
原理例如以下:
接着測试 <jsp:forward> 在action目录下新建forward.jsp
<%@ 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> <h4>JSP的动作标签</h4>
<jsp:forward page="/jsp/pageContext.jsp">
<jsp:param name="username" value="meimei"/>
</jsp:forward> </body>
</html>
执行结果:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzA4NzUxMw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
JavaBean及内省
- JavaBean的属性能够是随意类型,而且一个JavaBean能够有多个属性。每一个属性通常都须要具有setter、getter方法,setter方法称为属性的改动器,getter方法称为属性訪问器。
- 属性改动器必须以小写的set前缀開始,后跟属性名,且属性名的第一个字母要大写,比如,name属性的改动器名称为setName,password属性改动器名称为setPassword
- 属性訪问器通常以小写的get前缀開始。后跟属性名。且属性名的第一个字母也要改为大写,比如,name属性訪问器名称为getName,password属性訪问器是getPassword
- 一个JavaBean的某个属性也能够仅仅有set方法或get方法,这种属性通常也称之为仅仅写、仅仅读属性。(JavaBean的属性不是由对象中定义的变量决定的。是由get或者set方法决定的)
翻译成的Servlet源代码:
java.util.Date currentDate = null;
synchronized (_jspx_page_context) {
currentDate = (java.util.Date)
_jspx_page_context.getAttribute(
"currentDate", PageContext.PAGE_SCOPE);
if (currentDate == null){
currentDate = new java.util.Date();
_jspx_page_context.setAttribute("currentDate",
currentDate, PageContext.PAGE_SCOPE);
}
}
内省(Introspector)——JavaBean
public void populate(Map<String, String[]> map, User user) throws Exception {
BeanInfo info = Introspector.getBeanInfo(user.getClass());
PropertyDescriptor [] pds = info.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
String attrName = pd.getName();
if(map.containsKey(attrName)){
Method m = pd.getWriteMethod();
m.invoke(user, map.get(attrName)[0]);
}
}
}
在src下新建cn.itcast.test包,在包内新建InstrospectorTest.java測试类
package cn.itcast.test; import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method; import org.junit.Test; import cn.itcast.vo.User; /**
* 測试类
* @author Administrator
*
*/
public class IntrospectorTest { @Test
public void run() throws Exception{
User user = new User();
// 获取类的信息
BeanInfo info = Introspector.getBeanInfo(user.getClass());
// 获取属性的描写叙述
PropertyDescriptor [] pds = info.getPropertyDescriptors();
// 循环遍历,获取属性的名称
for (PropertyDescriptor pd : pds) {
// System.out.println(pd.getName());
if(!"class".equals(pd.getName())){
// 获取写的方法
Method m = pd.getWriteMethod();
m.invoke(user, "admin");
}
} System.out.println(user.getUsername());
System.out.println(user.getPassword());
}
}
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzA4NzUxMw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
执行结果:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzA4NzUxMw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
重写该方法。把字符串转换日期。
public class MyConvert implements Converter{ /**
* 实现转换的方法
* clazz:类型
* obj:输入的内容
*/
public Object convert(Class clazz, Object obj) {
String sDate = (String)obj;
// 把字符串转换成日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date;
try {
date = sdf.parse(sDate);
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException("日期转换错误");
}
return date;
}
} // 进行日期转换注冊
ConvertUtils.register(new MyConvert(), Date.class);
程序实比例如以下:
package cn.itcast.vo; import java.util.Date; /**
* User的JavaBean
* @author Administrator
*
*/
public class User { private String username;
private String password;
private double money;
private Date birthday; 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;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
} }
在src下新建cn.itcast.utils包(工具类) 在里面新建MyDateConverter.java 类(用于注冊其它类型的Bean)
package cn.itcast.utils; import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; import org.apache.commons.beanutils.Converter; /**
* 字符串转换日期类
* @author Administrator
*
*/
public class MyDateConverter implements Converter{ /**
* 字符串转换成日期
*/
public Object convert(Class clazz, Object obj) {
// 把输入的字符串,转换成日期类型。返回
String dDate = (String) obj;
// 把字符串转换成日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date;
try {
date = sdf.parse(dDate);
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException("转换日期错误");
}
return date;
} }
在src下新建cn.itcast.servlet包,在包内新建UserServlet.java类(实现内省)和UserBeanUtilServlet.java(实现日期属性为Bean赋值)
package cn.itcast.servlet; import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import cn.itcast.vo.User; /**
* 获取请求參数,封装数据
* @author Administrator
*
*/
public class UserServlet extends HttpServlet { private static final long serialVersionUID = 6390620317553505800L; public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { // 获取请求參数,创建User对象,设置值。
/**
*
* // 获取表单的内容
String username = request.getParameter("username");
String password = request.getParameter("password");
// 创建User对象,set设置值
User user = new User();
user.setUsername(username);
user.setPassword(password);
*/ // 获取输入的数据
Map<String, String []> map = request.getParameterMap();
// 创建User对象
User user = new User();
// 自己编写封装数据的方法
try {
populate(map,user);
} catch (Exception e) {
e.printStackTrace();
} // 完毕数据封装
System.out.println(user.getUsername());
System.out.println(user.getPassword());
} /**
* 完毕的数据
* @param map
* @param user
* @throws Exception
*/
private void populate(Map<String, String[]> map, User user) throws Exception {
BeanInfo info = Introspector.getBeanInfo(user.getClass());
// 获取属性的描写叙述
PropertyDescriptor [] pds = info.getPropertyDescriptors();
// 循环遍历
for (PropertyDescriptor pd : pds) {
// 获取到属性的名称
String name = pd.getName();
// map的key
if(map.containsKey(name)){
// 获取属性的写的方法
Method m = pd.getWriteMethod();
// 运行之
m.invoke(user, map.get(name)[0]);
}
}
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }
UserBeanUtilServlet.java /userBeanUtil
package cn.itcast.servlet; import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils; import cn.itcast.utils.MyDateConverter;
import cn.itcast.vo.User; /**
* 使用BeanUtils完毕数据的封装
* @author Administrator
*
*/
public class UserBeanUtilServlet extends HttpServlet { private static final long serialVersionUID = 3625882115495534032L; public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取数据
Map<String, String []> map = request.getParameterMap();
// 创建User对象
User user = new User(); // 完毕注冊
ConvertUtils.register(new MyDateConverter(), Date.class); // 完毕封装
try {
BeanUtils.populate(user, map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} // 打印
System.out.println(user.getUsername());
System.out.println(user.getPassword());
System.out.println(user.getMoney());
System.out.println(user.getBirthday());
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }
在WebRoot下新建目录bean目录,在目录下新建login.jsp 和success.jsp文件
<%@ 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> <h4>表单提交到JSP的页面</h4>
<form action="/day12/bean/success.jsp" method="POST">
姓名:<input type="text" name="username" /><br/>
密码:<input type="password" name="password" /><br/>
<input type="submit" value="登陆"/>
</form> <h4>表单提交到Servlet程序</h4>
<form action="/day12/user" method="POST">
姓名:<input type="text" name="username" /><br/>
密码:<input type="password" name="password" /><br/>
<input type="submit" value="登陆"/>
</form> <h4>表单提交到Servlet(BeanUtils)程序</h4>
<form action="/day12/userBeanUtil" method="POST">
姓名:<input type="text" name="username" /><br/>
密码:<input type="password" name="password" /><br/>
剩余金额:<input type="text" name="money" /><br/>
生日:<input type="text" name="birthday" /><br/>
<input type="submit" value="登陆"/>
</form> </body>
</html>
success.jsp ( <jsp:setProperty>等指令实现bean的赋值)
<%@page import="cn.itcast.vo.User"%>
<%@ 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> <h3>传统方式封装数据</h3>
<%
// 获取表单的内容
String username = request.getParameter("username");
String password = request.getParameter("password");
// 创建User对象。set设置值
User user = new User();
user.setUsername(username);
user.setPassword(password);
%> <!-- 使用jsp的标签封装数据 -->
<jsp:useBean id="u" class="cn.itcast.vo.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/> <jsp:getProperty property="username" name="u"/>
<jsp:getProperty property="password" name="u"/> </body>
</html>
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzA4NzUxMw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
EL表达式简单介绍(运算及获取数据和web开发经常使用对象)
EL全名为Expression Language。EL主要作用:
- 获取数据:EL表达式主要用于替换JSP页面中的脚本表达式,以从各种类型的web域中检索Java对象、获取数据(某个web域中的对象。訪问JavaBean的属性、訪问list集合、訪问map集合、訪问数组)
- 运行运算:利用EL表达式能够在JSP页面中运行一些主要的关系运算、逻辑运算和算术运算。以及在jsp页面中完毕一些简单的逻辑运算。${user==null}
- 获取web开发经常使用对象:EL表达式定义了一些隐式对象,利用这些隐式对象,web开发者能够非常轻松的获取对web经常使用对象的引用。从而获取这些对象中的数据。
- 调用Java方法:EL表达式同意用户开发自己定义EL函数,以在JSP页面中通过EL表达式调用Java类的方法。
- 使用EL表达式获取数据的语法:${标识符}
- EL表达式语句在运行时。会调用pageContext.findAttribute方法,用标识符为keyword,分别从page、request、session、application四个域中查找对应的对象,找到则返回对应的对象,找不到则返回 "" (注意:不是null而是空字符串)
- 演示样例:${user}
关系运算符 | 说明 | 范例 | 结果 |
== 或eq | 等于 | ${ 5 == 5 } 或${ 5 eq 5 } | true |
!= 或 ne | 不等于 | ${ 5 != 5 } 或 ${ 5 nq 5} | false |
< 或 lt | 小于 | ${ 3 < 5 } 或 ${ 3 lt 5 } | true |
> 或 gt | 大于 | ${ 3 > 5 } 或 ${ 3 gt 5 } | false |
<= 或 le | 小于等于 | ${ 3 <= 5 } 或 ${ 3 le 5 } | true |
>= 或 ge | 大于等于 | ${ 3 >= 5 } 或 ${ 3 ge 5 } | false |
逻辑运算符 | 说明 | 范例 | 结果 |
&& 或 and | 交集 | ${ A && B } 或 ${ A and B } | true/false |
|| 或 or | 并集 | ${ A || B } 或 ${ A or B } | true/false |
! 或 not | 非 | ${ !A } 或 ${ not A } | true/false |
<%
request.setAttribute("n1", 10);
request.setAttribute("n2", 20);
request.setAttribute("n3", 30);
request.setAttribute("n4", 40);
%> <h3>算术运算</h3>
${ n1 + n2 } <h3>关系运算</h3>
${n1 > n2 }${n1 gt n2 }<br/>
${n1 < n2 }${n1 ltn2 }<br/>
${n1 >= n2 }${n1 gen2 }<br/>
${n1 <= n2 }${n1 len2 }<br/>
${n1 == n2 }${n1 eqn2 }<br/>
${n1 != n2 }${n1 nen2 }<br/> <h3>逻辑运算</h3>
${n1>n2 && n3>n4 }${n1>n2 and n3>n4 }<br/>
${n1>n2 || n3>n4 }${n1>n2 or n3>n4 }<br/>
${ !(n1>n2) }${not (n1>n2)}<br/>
EL表达式保留keyword
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzA4NzUxMw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
隐含对象名称 | 描写叙述 |
pageContext | 相应于JSP页面中的pageContext对象(注意:取得是pageContext对象) |
pageScope | 代表page域中用于保存属性的Map对象 |
requestScope | 代表request域中用于保存属性的Map对象 |
sessionScope | 代表session域中用于保存属性的Map对象 |
applicationScope | 代表application域中用于保存属性的Map对象 |
param | 表示一个保存了全部请求參数的Map对象 |
paramValues | 表示一个保存了全部请求參数的Map对象。它对于某个请求參数。返回的是一个String[] |
header | 表示一个保存了全部http请求字段的Map对象 |
headerValues | 同上。返回String[] 数组。注意:假设头里面有"-" ,比如:Accept-Encoding,则 要使用headerValues["Accept-Encoding"] |
cookie | 表示一个保存了全部cookie的Map对象 |
initParam | 表示一个保存了全部web应用初始化參数的map对象 |
param相当于request.getParameter();
${cookie.name.name} ${cookie.name.value}
<%@page import="cn.itcast.vo.User2"%>
<%@page import="cn.itcast.vo.User"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ 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> <h4>获取域对象中的值</h4>
<%
pageContext.setAttribute("name", "黄海波");
request.setAttribute("name", "美美");
%> ${ pageScope.name }
${ requestScope.name } <h4>域中数组的值</h4>
<%
String [] arrs = {"美美","波波","东东","名名"};
request.setAttribute("arrs", arrs);
%>
${ arrs[2] } <h4>域中集合的值</h4>
<%
List<String> list = new ArrayList<String>();
list.add("美美");
list.add("小凤");
list.add("芙蓉");
request.setAttribute("list", list);
%>
${ list[1] } <h4>域中Map集合的值</h4>
<%
Map<String,String> map = new HashMap<String,String>();
map.put("aa", "美美");
map.put("bb", "小凤");
request.setAttribute("map", map);
%>
${ map.bb } <h4>域中集合中有对象的值</h4>
<%
List<User2> uList = new ArrayList<User2>();
uList.add(new User2("banzhang","123"));
uList.add(new User2("美美","abc"));
request.setAttribute("uList", uList);
%>
${ uList[1].username } </body>
</html>
执行结果:
<%@ 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> <h4>EL的运算</h4>
<%
request.setAttribute("n1", 10);
request.setAttribute("n2", 20);
request.setAttribute("n3", 30);
request.setAttribute("n4", 40);
%>
<h4>加法运算</h4>
${ n1 + n2 } <h3>关系运算</h3>
<h4>大于</h4>
${ n1 > n2 } ${ n1 gt n2 } <h4>小于</h4>
${ n1 < n2 } ${ n1 lt n2 } <h4>等于</h4>
${ n1 == n2 } ${ n1 eq n2 } <h4>不等于</h4>
${ n1 != n2 } ${ n1 ne n2 } <h4>大于等于</h4>
${ n1 >= n2 } ${ n1 ge n2 } <h4>小于等于</h4>
${ n1 <= n2 } ${ n1 le n2 } <h3>逻辑运算</h3>
<h4>与</h4>
${ n1 > n2 && n3 > n4 } ${ n1 > n2 and n3 > n4 } <h4>或</h4>
${ n1 > n2 || n3 > n4 } ${ n1 > n2 or n3 > n4 } <h4>非</h4>
${ !(n1 > n2) } ${ not (n1 > n2) } </body>
</html>
结果:
<%@ 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> <h4>EL的运算</h4>
<form action="/day12/el/elDemo4.jsp" method="POST">
姓名:<input type="text" name="username" /><br/>
<input type="submit" value="登陆"/>
</form> </body>
</html>
elDemo4.jsp
<%@ 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> <h4>EL的WEB对象</h4>
${ param.username } <h4>获取请求头</h4>
${ header.referer } <h4>获取全局初始化參数</h4>
${ initParam.username } <h4>pageContext对象</h4>
${ pageContext.request.contextPath } </body>
</html>
执行结果:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzA4NzUxMw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">