JSP页面由两部分组成:
1. 静态部分:标准的HTML标签、静态的页面内容,这些内容与静态HTML页面相同
2. 动态部分:受JAVA程序控制的内容,由JAVA程序动态生成。
JSP中的脚本
<%%> : 直接写java代码,出现在jsp的servlet中的service方法中.
<%!%>: 直接写java代码,出现在jsp生成的servlet的类中. 声明类中的变量, 方法.
<%=%>: 输出, 写在该脚本中的代码,最后会出现在service方法 中,并以 out.print(); 包裹.
JSP中的注释
<%– –%> : 被注释掉的内容,不会生成到java文件中.
<!-- -->
: html注释,将html代码发送给浏览器之后,给浏览器看的.
JSP指令
page指令
- import=”java.io.FileOutputStream” 该属性用来导包. 唯一一个可以出现多次的.
- pageEncoding=”UTF-8” 决定服务器读取jsp时 采用什么编码读
- contentType=”text/html; charset=UTF-8” 响应浏览器时 告诉浏览器用什么码表解码.
以上两个属性,只需要指定一个,另外一个会自动指定. - errorPage=”“(不常用) 当前jsp中出现了异常. 那么跳转到哪个页面.
- isErrorPage=”false”(不常用) 标识当前页面是否是处理错误的页面.
- session=”true”(不要修改) 页面中是否需要使用session对象.如果为false,那么session内置对象会消失. 默认为true.
- language: 描述当前页面使用的语言. 目前取值只有java.
- buffer=”8kb” (不常用) : 决定缓存的大小.
- autoFlush=”true”(不常用) : 如果缓存写满了.如果该属性为true,会将缓存中的自动输出到浏览器. 设置为false,将会报错.
- extends=”“(不用) 绝对 jsp生成的java文件 继承哪个类.默认继承:org.apache.jasper.runtime.HttpJspBase.通过该属性可以改变.也必须是HTTPServlet的子类.
- info=”fdsfsd”;设置jsp程序信息,使用getServletInfo()获取该值
设置错误页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" errorPage="error.jsp"%>
<!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>
<%
int a=6,b=0;
int c=a/b;//抛出异常
%>
</body>
<!--error.jsp-->
<%@ 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>系统出现异常</body>
include 页面包含指令(静态包含)
include可以将一个外部文件嵌入到当前JSP文件中,同时解析这个页面中的JSP语句,也会把目标页面的其他编译指令也包含进来。
静态包含还会将被包含页面的编译指令也包含进来,如果两个页面的编译指令冲突,那么页面会出错。
<!-- one.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>
<%@ include file="error.jsp" %>
</body>
</html>
<!--error.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>
系统出现异常
</body>
</html>
七个动作指令
forward
用于将页面响应转发到另外的页面,既可以转发到静态的HTML页面,也可以转发到动态JSP页面,或者Servlet
并不像新页面发送请求,只是完全采用新页面对用户生成响应。
<!--jsp-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>
<h3>jsp原始页</h3>
<jsp:forward page="forward-result.jsp">
<jsp:param value="29" name="age"/>
</jsp:forward>
</body>
</html>
<!--forward-result.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>
<%=request.getParameter("age") %>
</body>
</html>
include指令
include指令是一个动态include指令,用于包含某个页面,不会导入include页面的编译指令,仅仅将被导入页面的body内容插入本页面
<!--jsp-include.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>
<jsp:include page="forward-result.jsp">
<jsp:param value="32" name="age"/>
</jsp:include>
</body>
</html>
<!--forward-result.jsp同上一节-->
userBean、setProperty、getProperty指令
useBean用于在JSP页面中初始化一个JAVA实例
setProperty用于设置JavaBean实例属性的值
getProperty用于输出JavaBean实例的属性
public class Person {
private String name;
private int age;
public Person() {}
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;
}
}
<body>
<jsp:useBean id="p1" class="com.cai.Person" scope="page"></jsp:useBean>
<jsp:setProperty property="name" name="p1" value="wwww"/>
<jsp:setProperty property="age" name="p1" value="23"/>
<jsp:getProperty property="name" name="p1"/>
<jsp:getProperty property="age" name="p1"/>
</body>
plugin,param
plugin指令用于下载服务器端的JavaBean或Applet到客户端执行
param用于设置参数值,和include、forward和plugin指令结合使用。
<isp:param name="paramName" value="paramValue" />
九大内置对象
application
ServletContext的实例。
1. 让多个JSP、Servlet共享数据
application通过setAttribute方法将一个值设为application的属性,该属性的值对整个Web应用有效。
2. 获取Web应用配置参数
<context-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
String driver=application.getInitParameter("driver");
config
ServletConfig的实例
1. JSP页面无需配置,因此配置信息固定,但在Servlet中用处较大
2. 也可在web.xml中peizjsp信息,并可指定另一个URL
<!--所有JSP页面都有相同的名字jsp,因此下方代码输出jsp-->
<%=config.getServletName()%>
<servlet>
<!-- 指定Servlet名字 -->
<servlet-name>config</servlet-name>
<!-- 指定将哪个JSP页面配置成Servlet -->
<jsp-file>/one/beanTest.jsp</jsp-file>
<!-- 配置名为name的参数 -->
<init-param>
<param-name>name</param-name>
<param-value>fdsfdsf</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>config</servlet-name>
<url-pattern>/config</url-pattern>
</servlet-mapping>
<!--beanTest.jsp-->
<body>
<%=config.getInitParameter("name") %>
<%=config.getServletName() %>
</body>
exception
将异常处理页面中page指令的isErrorPage属性设置为true才可访问exception内置对象。
out
out对象代表一个页面输出流,通常用于在页面上输出变量值及常量,一般使用输出表达式的地方,都可以使用out对象达到同样效果。
<%= %>本质就是out.write()
pageContext
PageContext类的实例。
1. 访问不同范围的变量
2. 获取其他内置对象
findAttribute(name)//从最小的域开始匹配找到的属性
getAttribute(string name,int scope)//获取指定范围的name属性
setAttribute(name,value,scope)
//scope的值:
PageContext.PAGE_SCOPE:page范围
PageCntext.REQUESR_SCOPE:request范围
PageContext.SESSION_SCOPE:对应session范围
PageContext.APPLICATION_SCOPE:application范围
//获取其他内置对象
getRequest();
getResponse();
getServletConfig()
getSession()
request
response
session
内省
操作javabean提供的一套api
//User.java
public class User {
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
//Test.java
User u=new User();
//1. 获得javabean的描述信息
try {
BeanInfo info= Introspector.getBeanInfo(User.class);
//2. 获取User的属性信息
PropertyDescriptor[] pds= info.getPropertyDescriptors();
//3.遍历属性信息
for(PropertyDescriptor pd:pds) {
//判断当前遍历的属性是否是name属性
if(pd.getName().equals("name")) {
Method write=pd.getWriteMethod();
write.invoke(u, "tom");
}
}
System.out.println(u.getName());
} catch (IntrospectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//内省封装
private void populate(Map<String,String[]> map, User u) {
try {
Map<String,String[]> params = map;
BeanInfo info = Introspector.getBeanInfo(User.class);
PropertyDescriptor[] pds = info.getPropertyDescriptors();
for(PropertyDescriptor pd : pds){
//System.out.println(pd.getName());
String[] param = params.get(pd.getName());
if(param!=null && param.length>0){
pd.getWriteMethod().invoke(u, param[0]) ;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
beanUtils
提供一个populate方法,可以把表单提交的参数自动封装到Bean中.
并且可以自动进行类型转换.
转换范围是 8个基本数据类型.
我们也可以注册一个转换器,让BeanUtils可以转换其他类型.
//User2.java
public class User2 {
/*
* 1.所有作为属性保存的成员变量私有化
* 2.有空参构造
* 3.属性由对应get/set方法
*/
private String name;
private String password;
private int age;
private Date birthday;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public User2() {
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [name=" + name + ", password=" + password + ", age=" + age
+ ", birthday=" + birthday + "]";
}
}
//MyConverter.java
public class MyConverter implements Converter {
public Object convert(Class arg0, Object arg1) {
//xxx ==> OOO
String birthdayStr = arg1.toString();//1990-01-01 ==> date
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
return format.parse(birthdayStr);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
}
//AServlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
User u = new User();
/*u.setName(request.getParameter("name"));
u.setPassword(request.getParameter("password"));*/
//处理业务
//使用内省封装参数.
//populate(request.getParameterMap(), u);
//BeanUtils ==>
try {
//注册一个转换器,告诉BeanUtils如何进行转换
ConvertUtils.register(new MyConverter(), Date.class);
BeanUtils.populate(u,request.getParameterMap());
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(u);
}
EL表达式
封装内省操作,可以通过EL表达式操作JAVA BEAN
功能:替代页面上的代码
1. 使用EL内置对象,获得数据
2. 使用EL表达式可以获取JAVABEAN属性 集合项的值.
3. 使用EL可以进行逻辑运算
EL内置对象
- requestScope
- sessionScope
- applicationScope
- pageScope
以上四个 内置对象可以访问四个域
下面的内置对象用处不大 - param
- paramValues
以上两个对象封装了表单参数 - header
- headerValues
封装了Http请求头 - initParam
封装web.xml的配置 - pageContext
封装了pageContext - cookie
<!-- Demo01.jsp -->
<body>
<%-- EL表达式内置对象操作 ${} ==>el的格式 --%>
<%
request.setAttribute("name", "Tom");
session.setAttribute("name", "session");
application.setAttribute("name", "application");
pageContext.setAttribute("name", "pageContext");
%>
${requestScope.name}==><%=request.getAttribute("name") %><br/>
${sessionScope.name}==><%=session.getAttribute("name") %><br/>
${applicationScope.name}==><%=application.getAttribute("name") %><br/>
${pageScope.name}==><%=pageContext.getAttribute("name") %><br/>
${name}==><%=pageContext.findAttribute("name") %>
</body>
使用EL访问对象
<body>
<%--使用EL访问User对象--%>
<%
User u = new User();
u.setName("tom");
request.setAttribute("user", u);
%>
${requestScope.user.name}==><%=((User)request.getAttribute("user")).getName(); %><br>
${requestScope.user['name']}==><%=((User)request.getAttribute("user")).getName(); %><br>
<%
String[] array = new String[]{"tom","jerry","jack","rose"};
request.setAttribute("array", array);
%>
${requestScope.array[2]} <br>
<%
List<String> list = new ArrayList<String>();
list.add("jack");
list.add("rose");
request.setAttribute("list", list);
%>
${requestScope.list[1]}<br>
<%
Map<String,String> map = new HashMap<String,String>();
map.put("birthday", "now");
map.put("haha.heihei", "hiahia");
request.setAttribute("map", map);
%>
${requestScope.map.birthday}<br>
${requestScope.map['birthday']}<br>
${requestScope.map['haha.heihei']}<br>
</body>
EL运算符
<body>
<%
request.setAttribute("num1", 10);
request.setAttribute("num2", 20);
//EL表达式支持如下运算符.
%>
${num1 > num2} ==>${num1 gt num2}<br>
${num1 < num2} ==>${num1 lt num2}<br>
${num1 <= num2}==>${num1 le num2} <br>
${num1 >= num2}==>${num1 ge num2} <br>
${num1 == num2}==>${num1 eq num2} <br>
${num1 != num2}==>${num1 ne num2} <br>
${true && true}<br>
${true || true}<br>
${!true}<br>
${(num1 > num2)?"num1厉害":"num2厉害" }
</body>
EL函数库
- 创建方法
- 编写tld文件
- 使用EL函数
public class Tool {
public static String getTime() {
return new SimpleDateFormat("hh:mm:ss").format(new Date());
}
}
<?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">
<tlib-version>1.0</tlib-version>
<short-name>myFn</short-name>
<uri>http://www.cai.com/myFn</uri>
<function>
<name>getTime</name>
<function-class>com.cai.Tool</function-class>
<function-signature>java.lang.String getTime()</function-signature>
</function>
</taglib>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="myFn" uri="http://www.cai.com/myFn" %>
<!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>
${myFn:getTime()}
</body>
</html>