JSP简介

JSP(Java Server Pages)和Servlet一样,运行在服务器端

JSP的组成:HTML代码 + Java代码 + JSP标签

JSP是特殊的Servlet

JSP的执行原理:JSP编写完代码,第一次访问的时候,把JSP翻译为.java文件--->编译为.class文件--->执行

JSP的注释:

1、HTML的注释:<!-- -->

2、Java的注释:// /**/ /***/

3、JSP的注释:<%-- --%>

JSP的脚本元素

1、<%! java代码 %>  作为类的成员变量

2、<%= java代码 %>  输出的语句(输出到页面),不能使用分号;

3、<% java代码 %>  编写变量和语句(局部变量和语句)

JSP和Servlet的分工

JSP:

1、作为请求的发起页面,例如显示表单、超链接

2、作为请求结束页面,例如显示数据

Servlet:作为请求中处理数据的环节

JSP的指令

1、设置JSP文件的属性

2、指挥JSP文件如何执行

page指令

1、通过page指令设置JSP文件的属性

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

2、语法:<%@ page 属性名称=属性值 %> 一个页面可以出现多个page指令

3、page指令的属性

- language  默认是翻译为什么语言

- extends  继承(一个jsp文件会翻译为一个.java文件,默认继承一个类)

- session  限制能否直接使用session对象,默认是true,可以直接使用session对象

- import  导入包,import可以出现多次,其他的属性只能出现一次

- buffer  设置输出缓冲区的大小

- autoflush  如果缓冲区满了,是否自动刷新,如果满了不自动刷新,会抛出异常

- errorPage  程序抛出了异常,直接把异常抛到页面上,指定错误的处理页面

- isErrorPage  设置该页面是否为错误处理页面,决定直接可以使用对象exception

- isELIgnored  设置是否忽略EL表达式,默认false,不忽略,可以在页面中直接使用EL表达式

- pageEncoding  设置当前页面的默认编码。JSP文件最终翻译为.java文件

- ContentType  浏览器默认打开文件时的编码

注意:

在web.xml中配置全局的错误页面

 <!-- 配置全局错误页面 -->
  <error-page>
  	<error-code>404</error-code>
  	<location>/error/404.jsp</location>
  </error-page>
  <error-page>
  	<error-code>500</error-code>
  	<location>/error/500.jsp</location>
  </error-page>

include指令

1、可以用于页面的包含,可以把几个页面放在一起对外显示

2、include指令的语法:<%@ include file="包含文件的地址" %>

3、模拟一个门户网站

<%@ 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="/include/logo.jsp" %>
<%@ include file="/include/menu.jsp" %>
	<h3>真实数据</h3>
	
	<table border="1" width="50%">
		<tr>
			<td>体育</td>
			<td>新闻</td>
		</tr>
		<tr>
			<td>体育</td>
			<td>新闻</td>
		</tr>
	</table>
<%@ include file="/include/foot.jsp" %>
</body>
</html>

4、静态包含

原理:在翻译成一个java文件之前,把包含的页面中的所有内容全部都复制过来,一起翻译成一个java文件

JSP的内置对象

1、这些对象可以直接使用。exception对象,page有一个属性,isErrorPage设置成true才能使用exception对象

2、内置对象

request:  HttpServeltRequest

response:  HttpServletResponse

session:  HttpSession

application:  ServletContext

out:  JSPWriter

pageContext:PageContext

page:Object(代表当前对象)

config:ServletConfig

exception:Throwable

3、out实际是JSPWriter对象,可以向页面输出内容

JSPWriter out对象和PrintWriter response对象的联系:先把out对象缓冲区的内容输出到response对象的缓冲区中,然后使用response对象统一向外输出

pageContext对象

1、一个顶九个,可以获取另外的八个对象

2、域对象:代表当前页面的域

3、向其他的域对象中存取值 request,session,application

4、pageContext对象的API

setAttribute(String name,Object value)

setAttribute(String name,Object value,int scope)

Object getAttribute(String name)

Object getAttribute(String name,int scope)

Object findAttribute(String name)  全域查找

JSP标签

1、<jsp:forward>  转发的功能

- page属性:转发到哪个页面去

- 转发的路径:服务器绝对路径(不包含项目名称)

2、<jsp:param>  转发的时候可以传递参数

- 在转发标签中使用,设置name和value

3、<jsp:include>  动态包含(和静态包含效果一样,原理不一样)

- page属性:要包含的页面的路径

- 在源码的文件夹下,生成了四个java和class文件(和静态包含不同)

使用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:useBean id="u" class="com.entity.User" scope="page"></jsp:useBean>
	<jsp:setProperty property="username" name="u"/>
	<jsp:setProperty property="password" name="u"/>
	<h4>查看数据</h4>
	<jsp:getProperty property="username" name="u"/>
	<jsp:getProperty property="password" name="u"/>
</body>
</html>

内省的技术

1、通过内省的技术可以操作JavaBean的属性的读写方法

2、内省基于反射

3、使用Introspector来执行JavaBean的属性的读写方法

@Test
	public void run() throws Exception{
		//获取class对象
		User user = new User();
		//获取User JavaBean的信息
		BeanInfo info = Introspector.getBeanInfo(user.getClass());
		//获取属性的描述信息
		PropertyDescriptor[] pds = info.getPropertyDescriptors();
		//遍历
		for(PropertyDescriptor pd:pds){
			if(!"class".equals(pd.getName())){
				Method m = pd.getWriteMethod();
				//setUsername setPassword 对象执行
				m.invoke(user, "admin");	//user.setUsername("admin"); user.setPassword("admin");
			}
		}
		System.out.println(user.getUsername());
		System.out.println(user.getPassword());
	}

使用BeanUtils获取数据

1、导入jar包

2、代码

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取数据
		Map<String,String[]>map = request.getParameterMap();
		User user = new User();
		//使用BeanUtils工具类进行封装
		try {
			BeanUtils.populate(user, map);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		System.out.println(user.getUsername());
		System.out.println(user.getPassword());
	}

EL表达式

1、JSP内置的一种表达语言

2、作用:

- 从域对象中获取属性的值

- 执行运算

- 提供一些常用的Web对象(cookie)

- 调用Java方法

3、语法:¥{ 表达式内容 }

4、注意事项:

page指令:是否忽略EL表达式,如果忽略,JSP就不能使用EL表达式(isIgnored)

(1)获取域对象中的属性值

如果域对象中属性名称相同,EL默认从最小的域中取值

<%@page import="com.entity.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>
	<%
	pageContext.setAttribute("username", "zhangsan");
	request.setAttribute("username", "lisi");
	
	%>
	<h3>EL获取域对象中的值</h3>
	${ requestScope.username }
	
	<h3>从数组中取值(把数组存到域对象中)</h3>
	<%
		String[] arrs = new String[]{"张三","李四","王五"};
	//把数组存到域中
		pageContext.setAttribute("arrs", arrs);
	%>
	${ arrs[0] }
	
	<h3>从List集合中取值</h3>
	<%
		List<String> list = new ArrayList<String>();
		list.add("list1");
		list.add("list2");
		list.add("list3");
		pageContext.setAttribute("list", list);
		
	%>
	${ list[0] }
	
	<h3>从Map集合中取值</h3>
	<%
		Map<String,String>map = new HashMap<String,String>();
		map.put("aaa", "map1");
		map.put("bbb", "map2");
		map.put("111", "map4");
		pageContext.setAttribute("map", map);
	%>
	${ map["aaa"] }
	
	<h3>从List集合中存入对象,取值</h3>
	<%
		List<User> list2 = new ArrayList<User>();
		User user1 = new User();
		user1.setUsername("zhangsan");
		user1.setPassword("123");
		list2.add(user1);
		pageContext.setAttribute("list2", list2);
	
	%>
	${ list2[0].username }
</body>
</html>

EL中常用对象

pageScope  page域

requestScope request域

sessionScope session域

applicationScope applicaiton域

2、EL表达式支持运算

<%
	request.setAttribute("n1", 10);
	request.setAttribute("n2", 20);
	request.setAttribute("n3", 30);
	request.setAttribute("n4", 40);
%>
<h4>EL表达式支持运算</h4>
${ n1 + n2 }

<h4>是否相等</h4>
${ n1 == n2 }  ${ n1 eq n2 }

<h4>是否不等</h4>
${ n1 != n2 } ${ n1 ne n2 }

<h4>大于或者小于</h4>
${ n1 > n2 } ${ n1 gt n2 }  ${ n1 < n2 } ${ n1 lt n2 }

<h4>大于等于或者小于等于</h4>
${ n1 >= n2 } ${ n1 ge n2 }  ${ n1 <= n2 } ${ n1 le n2 }

<h4>与或非</h4>
${ n1 > n2 && n3 > n4 } ${ n1>n2 and n3>n4 }
${ n1 > n2 || n3 > n4 } ${ n1>n2 or n3>n4 }
${ !(n1>n2) }	${ not(n1>n2) }

EL表达式的内置对象

1.pageScope                获取page域对象的值
2.requestScope            获取request域对象的值
3.sessionScope            获取session域对象的值
4.applicationScope       获取application域对象的值
    
* 例子:向某个域中来存入值    request.setAttribute("xx",yy)
* 取值:${xx}    正规写法:${requestScope.xx}
    
5.param            获取表单提交过来的参数。(相当于 request.getParameter())
6.paramValues    获取表单提交过来的参数。(相当于 Map<String,String[]> map = request.getParameterMap())
7.header        获取请求头信息
8.headerValues    获取请求头信息
9.initParam        获取全局的初始化参数  
10.cookie        获取cookie对象的引用,可以使用cookie对象的引用获取cookie的名称和cookie的值。
        * 前提条件:是在Servlet程序中创建一个Cookie对象Cookie cookie = new Cookie("last","2015-01-27");
        * ${cookie.last }    -- 获取cookie的名称为last的对象
        * ${cookie.last.name}   -- 获取cookie对象的名称就是last
        * ${cookie.last.value}   -- 获取cookie对象的值就是2015-01-27

11.pageContext    
        * 获取项目的虚拟路径(项目名称)
        * ${ pageContext.request.contextPath }    获取项目的名称

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐