JSP基本语法

来源:互联网 发布:怎么用邮箱注册淘宝 编辑:程序博客网 时间:2024/06/08 06:31

Web服务器

1.1.RCP与TCP
我们经常使用的桌面程序叫做胖客户端程序(Rich Client Program,简称RCP),例如QQ、Excel、Word等软件。这类桌面软件需要安装到电脑上才能运行,并会导致占用电脑硬盘空间越来越大,因此我们称这类桌面程序为胖客户端程序。
与胖客户端程序相对的是瘦客户端程序。瘦客户端程序(Thin Client Program,简称TCP)一般都是Web程序,例如Web QQ、网上银行等。这类瘦客户端程序不需要在电脑安装,只需要打开浏览器就可以运行。
1.2.C/S与B/S
常见 的的软件系统结构分别为C/S结构和B/S结构,C/S结构意思是客户端/服务器端体系结构,B/S结构意思是浏览器/服务器端体系结构。
C/S(Client/Server)即客户端/服务器端:
优点:安全性比较好。
缺点:软件更新时同时更新服务器端和客户端,比较麻烦。
B/S(Browser/Server)即浏览器/服务器端:
优点:只需编写服务器端程序。
缺点:安全性比较差。
1.3.Web资源
在打开浏览器访问某个网站或打开某个程序时,都是访问Web程序的相关资源。而Web资源可以分为静态资源和动态资源。
所谓静态资源就是指访问的网页内容是始终不改变的,例如网页中显示的文本、图片、视频或视频等内容都属于静态资源。而动态资源就是指访问的网页内容是可以通过服务器端呈现动态变化的,例如显示用户信息的列表、显示本月消费记录等内容都属于动态资源。我们所学习的技术中例如HTML技术就属于静态资源内容,而例如Servlet或Filter就属于动态资源内容。当然,除了Java Web技术外,还有很多技术是属于动态资源的,例如ASP、PHP技术等。
无论是静态资源还是动态资源,我们在访问时都需要打开浏览器,在浏览器的地址栏中输入对应的地址(URL)。该地址是由“协议名://域名:端口号/路径”组成的,就像访问某个网站的页面,例如http://www.longestory.com:80/index.html。
1.4.Web服务器
对于静态资源或者动态资源,需要存储在Web服务器中,方便用户访问。Web服务器的作用是接收用户的请求信息,并为用户做出响应。
当然,对于Java Web程序而言,不仅需要Web服务器,还需要JSP/Servlet容器的。关于JSP/Servlet容器我们以后会学到。
我们常见使用的都是Web服务器和JSP/Servlet容器集成在一起的,下列就是比较流行的Web服务器:
Tomcat服务器:是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,由Apache、Sun 和其他一些公司及个人共同开发而成。也是目前应用最广泛的Web服务器。
JBoss服务器:是全世界开发者共同努力的成果,一个基于J2EE的开放源代码的应用服务器。
GlassFish服务器:是用于构建 Java EE 5应用服务器的开源开发项目,基于 Sun Microsystems 提供的 Sun Java System Application Server PE 9 的源代码以及 Oracle 贡献的 TopLink 持久性代码。
Weblogic服务器:是美国Oracle公司出品的一个application server确切的说是一个基于JAVAEE架构的中间件,BEA WebLogic是用于开发、集成、部署和管理大型分布式Web应用、网络应用和数据库应用的Java应用服务器。
Websphere服务器:是 IBM 的软件平台。它包含了编写、运行和监视全天候的工业强度的随需应变 Web 应用程序和跨平台、跨产品解决方案所需要的整个中间件基础设施,如服务器、服务和工具。
//jsp动态网页技术能够动态交互的和数据库交互修改


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:forward page="target.jsp">//服务器内部跳转客户端浏览器的地址没有变
<jsp:param value="java1234" name="userName"/>
<jsp:param value="123456" name="password"/>
</jsp:forward>
</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>
服务器内部跳转后的页面<br/>
userName:<%=request.getParameter("userName") %><br/>
password:<%=request.getParameter("password") %><br/>
</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>
<%-- <h1>静态包含</h1>//静态页面 把内容发在一起再一起编译容易出现变量冲突
<%@ include file="common/head.html" %>
<p>content</p>
<%@ include file="common/footer.jsp" %> --%>
<h1>动态包含</h1>//动态编译先自己编译运行好把结果放在这
<jsp:include page="common/head.html"/>
<p>content</p>
<jsp:include page="common/footer.jsp"/>
</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>
<h1>Jsp注释</h1>
<!-- html注释,客户端可见 -->
<%--Jsp注释,客户端不可见 --%>
<%
int a=1; // 单行注释
/* int b=2;
int c=3; */
%>
</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>


</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">
<%!
String str="全局变量";
%>
<%!
public void fun1(){
System.out.println("全局方法");
}
%>
<%!
class C{
private int a;
public void f(){
System.out.println("全局类");
}
}
%>
<%
int a=1234;
String b="java";
out.println(a+b+"局部变量");
%>
<title>Insert title here</title>
</head>
<body>
<%=b %>
</body>
</html>






<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>//JSP字符的编码和页面响应的MIME码 
<!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>
<%
// 设置两个application范围的数据 key-> value
application.setAttribute("name","application王二小");
application.setAttribute("age",12);
%>
<h1>application值设置完毕!</h1>
</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>
<%
// 取值
String name=(String)application.getAttribute("name");
int age=(Integer)application.getAttribute("age");
%>
<font>姓名:<%=name %></font>
<font>年龄:<%=age %></font>
</body>
</html>


<%! %>全局变量、方法、类
<% %>局部变量、编写语句 在方法里面的
<%=%>输出一个变量或具体内容
//jsp编译成色如servlet
11. jsp有哪些内置对象?作用分别是什么? 分别有什么方法? 
答:JSP共有以下9个内置的对象: 
request 用户端请求,此请求会包含来自GET/POST请求的参数 
response 网页传回用户端的回应 
pageContext 网页的属性是在这里管理 
session 与请求有关的会话期 
application servlet 正在执行的内容 
out 用来传送回应的输出 
config servlet的构架部件 
page JSP网页本身 
exception 针对错误网页,未捕捉的例外 
request表示HttpServletRequest对象。它包含了有关浏览器请求的信息,并且提供了几个用于获取cookie, header, 和session数据的有用的方法。 
response表示HttpServletResponse对象,并提供了几个用于设置送回 浏览器的响应的方法(如cookies,头信息等) 
out对象是javax.jsp.JspWriter的一个实例,并提供了几个方法使你能用于向浏览器回送输出结果。 
 pageContext表示一个javax.servlet.jsp.PageContext对象。它是用于方便存取各种范围的名字空间、servlet相关的对象的API,并且包装了通用的servlet相关功能的方法。 
session表示一个请求的javax.servlet.http.HttpSession对象。Session可以存贮用户的状态信息 
applicaton 表示一个javax.servle.ServletContext对象。这有助于查找有关servlet引擎和servlet环境的信息 
config表示一个javax.servlet.ServletConfig对象。该对象用于存取servlet实例的初始化参数。 
page表示从该页面产生的一个servlet实例


四大作用域用来保存数据范围
page 只在一个页面中保存数据 其他页面无效范围最小
request 只在一个请求中保存数据 
session 在一次会话范围内保存数据、
Application 整个服务器上保存数据,所有用户共享。整个应用所有用户共享其他浏览器也可以


<%@ 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>
<%
// 设置两个page范围的数据 key-> value//抽象类不能直接使用 
pageContext.setAttribute("name","page王二小");
pageContext.setAttribute("age",12);
%>
<%
// 取值
String name=(String)pageContext.getAttribute("name");
int age=(Integer)pageContext.getAttribute("age");
%>
<font>姓名:<%=name %></font>
<font>年龄:<%=age %></font>
</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范围的数据 key-> value 接口非常短暂的一次性的
request.setAttribute("name","request王二小");
request.setAttribute("age",12);
%>
<jsp:forward page="requestTarget.jsp"></jsp:forward>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.util.*" %>
<!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 name=(String)request.getAttribute("name");
int age=(Integer)request.getAttribute("age");
// 获取头信息包含发送发的信息
Enumeration enu=request.getHeaderNames();//获取所有头信息
while(enu.hasMoreElements()){
String headerName=(String)enu.nextElement();
String headerValue=request.getHeader(headerName);
%>
<h4><%=headerName %>&nbsp;<%=headerValue %></h4>
<%
}
%>
<font>姓名:<%=name %></font>
<font>年龄:<%=age %></font>
</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>
<%
// 设置两个session范围的数据 key-> value//数据保存在服务器不关闭浏览器默认半小时都能取到数据不需要转发
session.setAttribute("name","session王二小");
session.setAttribute("age",12);
%>
<h1>session值设置完毕!</h1>
</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>
<%
// 取值
String name=(String)session.getAttribute("name");
int age=(Integer)session.getAttribute("age");
%>
<font>姓名:<%=name %></font>
<font>年龄:<%=age %></font>
</body>
</html>




1、servlet的生命周期web容器加载servlet,生命周期开始。通过调用servlet的init()方法进行servlet的初始化。通过调用service()方法实现,根据请求的不同调用不同的do***()方法。结束服务,web容器调用servlet的destroy()方法。
2、如何现实servlet的单线程模式  <%@ page isThreadSafe=”false”%>
3、页面间对象传递的方法  request,session,application,cookie等
4、JSP和Servlet有哪些相同点和不同点,他们之间的联系是什么? 
JSP是Servlet技术的扩展,本质上是Servlet的简易方式,更强调应用的外表表达。JSP编译后是"类servlet"。Servlet和JSP最主要的不同点在于,Servlet的应用逻辑是在Java文件中,并且完全从表示层中的HTML里分离开来。而JSP的情况是Java和HTML可以组合成一个扩展名为.jsp的文件。JSP侧重于视图,Servlet主要用于控制逻辑。
5、四种会话跟踪技术 cookie,url重写,session,隐藏域
5,jsp的四种范围
page否是代表与一个页面相关的对象和属性。一个页面由一个编译好的 Java servlet 类(可以带有任何的 include 指令,但是没有 include 动作)表示。这既包括 servlet 又包括被编译成 servlet 的 JSP 页面
request是是代表与 Web 客户机发出的一个请求相关的对象和属性。一个请求可能跨越多个页面,涉及多个 Web 组件(由于 forward 指令和 include 动作的关系)
session是是代表与用于某个 Web 客户机的一个用户体验相关的对象和属性。一个 Web 会话可以也经常会跨越多个客户机请求
application是是代表与整个 Web 应用程序相关的对象和属性。这实质上是跨越整个 Web 应用程序,包括多个页面、请求和会话的一个全局作用域
1.1.page指令
page指令是JSP页面中最常用的指令,用来声明JSP页面的属性等信息。一个page指令允许定义多个属性;也可以一个page指令定义一个属性,定义多个page指令。
但是需要注意的是:
page指令设置的属性只能出现一次,除import属性以外。
属性名称区分大小写。
page指令允许的属性如下:
pageEncoding和contentType属性
pageEncoding属性:指明当前JSP页面使用的编码格式。pageEncoding属性的值要与JSP页面的真实编码保持一致,否则会出现乱码。
contentType属性:在JSP页面编译成Servlet文件时,对应response.setContentType()方法。
pageEncoding属性与contentType属性只设置其中一个属性时,另一个属性的默认与设置的相同。如果两个属性都不设置的话,两个属性的默认值都为“ISO-8859-1”。一般情况下,至少设置其中一个。
errorPage和isErrorPage属性
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'page.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="0">
  </head>
  <body>
    This is my JSP page. <br>
    <%
    if(true){
    throw new RuntimeException();
    }
    %>
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'error.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
  </head>
  <body>
    this is error page.<br>
  </body>
</html>
在第一个JSP页面中增加如下代码,设置如果当前页面出现错误,利用error.jsp页面进行错误信息的提示。
<%@ page language="java" pageEncoding="UTF-8" errorPage="error.jsp"%>
在error.jsp页面中增加如下代码,设置如果当前JSP页面错误,响应对应的状态码,以便之后处理。
<%@ page language="java" pageEncoding="UTF-8" isErrorPage="true"%>
<%@ page language="java" pageEncoding="UTF-8" isErrorPage="true"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'error.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
  </head>
  <body>
    this is error page.<br>
    <%=exception.getMessage() %>
  </body>
</html>
在JSP页面中指定错误页面虽然可以,但是操作繁琐(实际开发要为每一个JSP页面指定)。还可以使用web.xml文件配置错误页面信息。
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <!-- 配置对应状态码为404的错误页面 -->
  <error-page>
  <!-- 设置对应的状态码 -->
  <error-code>404</error-code>
  <!-- 配置错误页面路径 -->
  <location>/01_directive/error.jsp</location>
  </error-page>
  <!-- 配置对应异常的错误页面 -->
  <error-page>
  <!-- 设置对应的异常 -->
  <exception-type>java.lang.RuntimeException</exception-type>
  <!-- 配置错误页面路径 -->
  <location>/01_directive/error.jsp</location>
  </error-page>
</web-app>
1.2.include指令
include指令用于在JSP页面中静态包含另一个文件,该文件可以是JSP页面、HTML页面、文本文件或一段Java代码。include语法格式如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'include.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
  </head>
  <body>
  欢迎你,现在的时间是:
    <%@ include file="date.jsp" %>
  </body>
</html>
date.jsp页面
<%
out.println(new java.util.Date().toString());
%>
1.3.taglib指令
JSP页面支持标签,使用标签功能可以实现视图代码重用,很少量的代码可以实现很复杂的显示效果。要使用标签功能必须先声明标签库以及标签前缀。taglib指令用于指明JSP页面使用的JSP标签库。taglib指令的语法格式如下:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
2.1.<jsp:include>标签
这个动作标签用于在当前页面中包含静态和动态的资源,一旦被包含的页面执行完毕,请求处理将在调用页面中继续进行。这个动作标签与javax.servlet.RequestDispatcher类的include方法一致。
<jsp:include flush="boolean值" page="被包含页面的路径"></jsp:include>
flush属性:该属性是可选的。默认值为false,表示当前页面输出使用了缓冲区,在包含之前不刷新缓冲区。true表示刷新缓冲区。
page属性:指定被包含资源的相对路径,该路径是相对于当前JSP页面的URL。
下面通过一个案例来掌握include标签的使用:
创建一个JSP页面用于判断当前是否登录。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'include.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
  </head>
  <body>
    <%
    String flag = request.getParameter("flag");
    String p = "";
    if(flag.equals("true")){
    p = "login.jsp";
    }else{
    p = "logout.jsp";
    }
    %>
<jsp:include page="<%=p %>" />
  </body>
</html>
2.2.<jsp:forward>标签
这个动作标签运行在运行时将当前的请求转发给一个静态的资源、JSP页面或者Servlet,请求被转向到的资源必须位于同JSP发送请求相同的上下文环境中。这个动作标签与javax.servlet.RequestDispatcher类的forward()方法的作用相同。
这个动作标签的语法格式如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'forward.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
  </head>
  <body>
  <h1>forward.jsp</h1>
  <% System.out.println("forward jsp start..."); %>
    <jsp:forward page="include.jsp?flag=true"></jsp:forward>
    <% System.out.println("forward jsp end..."); %>
  </body>
</html>
2.3.<jsp:param>标签
这个动作标签与<jsp:include>标签、<jsp:forward>标签配合使用,以键值对形式为其他标签提供参数内容。这个动作标签的语法格式如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'forward.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
  </head>
  <body>
    <jsp:forward page="include.jsp">
    <jsp:param value="true" name="flag"/>
    </jsp:forward>
  </body>
</html>
3.JSP内置对象
3.1.out输出流对象
内置对象out是javax.servlet.jsp.JspWriter类的实例,与response.getWriter()方法的作用相同,都是服务器端向客户端输出的字符串内容。该对象的常用方法如下:
3.2.pageContext上下文对象
内置对象pageContext是javax.servlet.jsp.PageContext类的实例,该对象是JSP的四大作用域对象之一,pageContext对象代表当前JSP页面编译后的内容,多用于JSP页面之间共享数据内容。
3.3.request请求对象
内置对象request是javax.servlet.ServletRequest类的实例,代表着客户端的请求。具体用法请参考Request对象内容。
3.4.response响应对象
内置对象response是javax.servlet.ServletResponse类的实例,代表着服务器端的响应。具体用法请参考Response对象内容。
3.5.config配置对象
内置对象config是javax.servlet.ServletConfig类的实例,ServletConfig对象封装了配置在web.xml文件中初始化JSP的参数,JSP通过config对象获取这些参数值。具体用法请参考ServletConfig对象内容。
3.6.session会话对象
内置对象session是javax.servlet.http.HttpSession类的实例,session与cookie是解决Http协议的无状态问题的两种解决方案。如果在JSP页面中使用<%@ page session=”false”%>指令的话,则在当前JSP页面中不能使用session内置对象。但一般情况下,不会禁止使用session对象,具体用法请参考HttpSession对象内容。
3.7.application应用对象
内置对象application是javax.servlet.ServletContext类的实例,ServletContext封装了JSP所在的Web应用程序的信息,整个Web应用程序对应一个ServletContext对象。具体用法请参考ServletContext对象内容。
3.8.page页面对象
内置对象page是javax.servlet.jsp.HttpJspPage类的实例,page对象代表当前JSP页面,是当前JSP编译后的Servlet类的对象。page相当于普通Java类中的关键字this。
3.9.exception异常对象
内置对象exception是java.lang.Exception类的实例,该对象封装了JSP中抛出的异常信息。exception对象只能在使用<%@ page isErrorPage=”true”%>指令的JSP页面中。


6、SERVLET API中forward() 与redirect()的区别?
答:前者仅是容器中控制权的转向,在客户端浏览器地址栏中不会显示出转向后的地址;后者则是完全的跳转,浏览器将会得到跳转的地址,并重新发送请求链接。这样,从浏览器的地址栏中可以看到跳转后的链接地址。所以,前者更加高效,在前者可以满足需要时,尽量使用forward()方法,并且,这样也有助于隐藏实际的链接。在有些情况下,比如,需要跳转到一个其它服务器上的资源,则必须使用sendRedirect()方法。
15、两种跳转方式分别是什么?有什么区别? 
(下面的回答严重错误,应该是想问forward和sendRedirect 的区别,毕竟出题的人不是专业搞文字艺术的人,可能表达能力并不见得很强,用词不一定精准,加之其自身的技术面也可能存在一些问题,不一定真正将他的意思表达清楚了,严格意思上来讲,一些题目可能根本就无人能答,所以,答题时要掌握主动,只要把自己知道的表达清楚就够了,而不要去推敲原始题目的具体含义是什么,不要一味想着是在答题)
答:有两种,分别为: 
<jsp:include page=included.jsp flush=true> 
<jsp:forward page= nextpage.jsp/> 
前者页面不会转向include所指的页面,只是显示该页的结果,主页面还是原来的页面。执行完后还会回来,相当于函数调用。并且可以带参数.后者完全转向新页面,不会再回来。相当于go to 语句。


response

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>HeadFirstJspServletChap02</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
  <servlet-name>init</servlet-name>
  <jsp-file>/sysInit.jsp</jsp-file>
  <init-param>
  <param-name>jdbcName</param-name>
  <param-value>com.mysql.jdbc.Driver</param-value>
  </init-param>
  <init-param>
  <param-name>dbUrl</param-name>
  <param-value>jdbc:mysql://localhost:3306/db_xx</param-value>
  </init-param>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>init</servlet-name>
  <url-pattern>/init</url-pattern>//服务器请求init找到name之后找到name一样的servlet找到请求的处理
  </servlet-mapping>
</web-app>


<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.util.*"%>
<!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 jdbcName=config.getInitParameter("jdbcName");
String dbUrl=config.getInitParameter("dbUrl");
%>
<h1>驱动名称:<%=jdbcName %></h1>
<h1>连接地址:<%=dbUrl %></h1>
</body>
</html>


显示值在<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.util.*"%>
<%@ page 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>
<%
if(exception!=null){
out.println("程序错误信息:");
out.println(exception.getMessage());
}
%>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.util.*"%>
<%@ page 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=1;
int b=0;
out.println(a/b);
%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.util.*"%>
<%@ page 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>
<%
pageContext.setAttribute("name0", "pageInfo");
request.setAttribute("name1", "requestInfo");
session.setAttribute("name2", "sessionInfo");
application.setAttribute("name3", "applicationInfo");

out.println("使用pageContext<br/>");//pageContext可以获取很多内容上下文,标签
out.println("page中的属性值:"+pageContext.getAttribute("name0")+"<br/>");
out.println("request中的属性值:"+pageContext.getRequest().getAttribute("name1")+"<br/>");
out.println("session中的属性值:"+pageContext.getSession().getAttribute("name2")+"<br/>");
out.println("application中的属性值:"+pageContext.getServletContext().getAttribute("name3")+"<br/>");
%>
</body>
</html>




<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.util.*"%>
<!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>
<%
out.println("<h1>");
out.println("Hello Jsp Servlet");
out.println("</h1>");
%>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.util.*"%>
<!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 totalbuffer=out.getBufferSize();  // 获取总共缓冲区的大小
int available=out.getRemaining(); // 获取未使用的缓冲区的大小
int user=totalbuffer-available;  // 获取使用的缓冲区大小
out.println("总共缓冲区的大小:"+totalbuffer);
out.println("未使用的缓冲区的大小:"+available);
out.println("使用的缓冲区大小:"+user);
%>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.util.*"%>
<!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>
<%
// 每隔一秒刷新一次页面
response.setHeader("refresh","1");
// 获取当前时间
Date myDate=new Date();
%>
当前时间:<%= myDate.toLocaleString() %>//显示本地的时间
</body>
</html>


<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.util.*"%>
<!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>
<%
// 重定向,客户端跳转//不能带任何数据浏览器地址也会变
response.sendRedirect("index.html");
%>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.util.*"%>
<!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>
<script type="text/javascript">
function resetValue(){
document.getElementById("userName").value="";
document.getElementById("pwd").value="";
}
</script>
<%
String userName=null;
String pwd=null;
Cookie[] cookies=request.getCookies();//获取所有cookie,cookie信息记录在本地客户端,可以取cookie数据,减轻服务器端压力
for(int i=0;cookies!=null &&i<cookies.length;i++){
if(cookies[i].getName().equals("userNameAndPwd")){
userName=cookies[i].getValue().split("-")[0];//split返回一个数组
pwd=cookies[i].getValue().split("-")[1];
}
}

if(userName==null){
userName="";
}

if(pwd==null){
pwd="";
}
%>
</head>
<body>


<form action="userLogin.jsp" method="post">//form提交地址get跟在浏览器上urlpost放在数据包长度长
<table>
<tr>
<td>用户名:</td>
<td><input type="text" id="userName" name="userName" value="<%=userName%>"/></td>//显示显示值
</tr>
<tr>
<td>密码:</td>
<td><input type="password" id="pwd" name="pwd" value="<%=pwd %>" /></td>
</tr>
<tr>
<td>记住密码:</td>
<td><input type="checkbox" id="remember" name="remember" value="remember-me"/></td>
</tr>
<tr>
<td><input type="submit" value="登录"/></td>
<td><input type="button" value="重置" onclick="resetValue()"/></td>
</tr>
</table>
</form>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.util.*"%>
<!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 jdbcName=config.getInitParameter("jdbcName");
String dbUrl=config.getInitParameter("dbUrl");
%>
<h1>驱动名称:<%=jdbcName %></h1>
<h1>连接地址:<%=dbUrl %></h1>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="javax.servlet.http.*"%>//split


<!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 userName=request.getParameter("userName");  // 获取用户名
String pwd=request.getParameter("pwd");  // 获取密码
String remember=request.getParameter("remember");  // 获取记住密码

if("remember-me".equals(remember)){
Cookie userNameAndPwd=new Cookie("userNameAndPwd",userName+"-"+pwd);
userNameAndPwd.setMaxAge(1*60*60*24*7); // cookie记录一个星期
response.addCookie(userNameAndPwd);  // 保存cookie
System.out.println("设置Cookie成功");
}
response.sendRedirect("response03.jsp");
%>


</body>
</html>




通过上图的Web应用程序运行机制,我们可以知道关于Request与Response的信息:
Web应用程序接收一次请求,就创建一个Request对象和Response对象。
通过Request对象可以在服务器端获取客户端发送的请求数据内容。
通过Response对象可以生成服务器端向客户端响应的数据内容。
request对象和Response对象并不是Web应用程序所创建的,而是由Tomcat服务器创建(JavaEE并没有Request与Response的实现类)。
JavaEE提供了javax.servlet.http包中提供了HttpServletRequest和HttpServletResponse接口,这两个接口是继承于javax.servlet包中的ServletRequest和ServletResponse接口。
javax.servlet包中的ServletRequest和ServletResponse接口是与协议无关的,而javax.servlet.http包中的HttpServletRequest和HttpServletResponse接口是与Http协议有关的。
Request
Request这个对象不用事先声明,就可以在JSP网页中使用,在编译为Servlet之后,它会转换为javax.servlet.http.HttpServletRequest形态的对象,HttpServletRequest对象是有关于客户端所发出的请求的对象,只要是有关于客户端请求的信息,都可以藉由它来取得,例如请求标头、请求方法、请求参数、客户端IP,客户端浏览器等等信息。
Response
Response对象用于动态响应客户端请示,控制发送给用户的信息,并将动态生成响应。Response对象只提供了一个数据集合cookie,它用于在客户端写入cookie值。若指定的cookie不存在,则创建它。若存在,则将自动进行更新。结果返回给客户端浏览器。
2.1.Response概述
Response是Web应用程序用来封装向客户端响应信息的,是Servlet接口的service()方法的一个参数,类型为javax.servlet.http.HttpServletResponse。客户端每次发送请求时,服务器都会创建一个Response对象,并传递给Servlet接口的service()方法,来完成向客户端的响应工作。
2.2.Response重定向
在学习Http响应协议时,我们曾做过重定向案例,但那时我们并不清楚其原理,下面我们就讨论一下利用HttpServletResponse来完成重定向的功能。
创建一个Servlet来完成重定向功能。
public class ResponseServlet1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setStatus(302);
response.setHeader("Location", "/09_request&response/response/index.html");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
在Web工程的web.xml文件中注册Servlet。
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>ResponseServlet1</servlet-name>
    <servlet-class>app.java.response.ResponseServlet1</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ResponseServlet1</servlet-name>
    <url-pattern>/response1</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
通过上述案例,我们可以发现在重定向中,实际上客户端向服务器端发送了两次请求,具体步骤如下:
在浏览器地址输入URL,访问服务器端的Servlet,这是第一次发送的请求。
服务器端接收到客户端的请求后,由Servlet做出处理,重定向到index.html页面,并响应给客户端浏览器。
客户端浏览器接收到服务器端的响应后,再次发送第二次请求。
服务器端接收到客户端的第二次请求后,并响应index.html给客户端浏览器显示。
其实Response对象提供了sendRedirect(String location)方法,同样可以完成重定向的工作。
public class ResponseServlet1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("/09_request&response/response/index.html");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

2.3.登录错误案例
利用Response对象提供了sendRedirect(String location)方法可以完成重定向的功能,实现登录功能中如果错误的案例。具体实现步骤如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>login.html</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  </head>
  <body>
    <h1>登录案例:登录错误重定向回当前页面</h1>
<form id="form1" action="/09_request&response/response2" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
  </body>
</html>
public class ResponseServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取客户端浏览器提交的用户名与密码内容
String username = request.getParameter("username");
String password = request.getParameter("password");
//模拟查询数据库:admin/admin
if(username.equals("admin")&&password.equals("admin")){
// 登录成功
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<h1>登录成功</h1>");
}else{
// 登录错误
response.sendRedirect("/09_request&response/response/login.html");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>ResponseServlet2</servlet-name>
    <servlet-class>app.java.response.ResponseServlet2</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ResponseServlet2</servlet-name>
    <url-pattern>/response2</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
2.4.自动刷新案例
在学习Http响应协议时,我们曾做过自动刷新案例,但那时我们并不清楚其原理,下面我们就讨论一下利用HttpServletResponse来完成自动刷新的功能。
创建一个Servlet用于设置5秒钟后自动刷新页面的功能(自动跳转到登录页面)。
public class ResponseServlet3 extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("refresh", "5;url=/09_request&response/response/login.html");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("当前页面会在5秒钟后自动跳转到登录页面.");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>ResponseServlet3</servlet-name>
    <servlet-class>app.java.response.ResponseServlet3</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ResponseServlet3</servlet-name>
    <url-pattern>/response3</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>refresh.html</title>
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="refresh" content="5;url=/09_request&response/response/login.html">
  </head>
  <body>
    <h1>当前页面会在5秒钟后自动跳转到登录页面.</h1>
  </body>
</html>
使用Response对象的setHeader()方法与HTML页面的<meta>标签,同样可以完成页面自动刷新功能,但是两者是有区别的:
使用Response对象的setHeader()方法:refresh信息是显示在响应头信息中。
使用HTML页面的<meta>标签:refresh信息是显示在响应体信息中。
在上述基础上,完成动态效果的倒计时功能,需要使用javascript技术来完成。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>refresh.html</title>
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="refresh" content="5;url=/09_request&response/response/login.html">
  </head>
  <script type="text/javascript">
  var times = 5;
  function init(){
document.getElementById("times").innerHTML = times;
times--;
setTimeout("init()",1000);
}
  </script>
  <body onload="init();">
    <h1>当前页面会在<span id="times"></span>秒钟后自动跳转到登录页面</h1>
  </body>
</html>
2.5.禁止浏览器缓存案例
在学习Http响应协议时,我们知道响应协议中有三个头信息可以禁止浏览器本地缓存,分别是Cache-Control、Pragma和Expires。下面我们就通过一个案例来讨论一下。
public class ResponseServlet4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("当前时间是:"+new Date().toString());
System.out.println("已经成功地访问了当前Servlet...");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>ResponseServlet4</servlet-name>
    <servlet-class>app.java.response.ResponseServlet4</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ResponseServlet4</servlet-name>
    <url-pattern>/response4</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
于IE浏览器的本地缓存问题,第二次再次访问相同Servlet拦截路径时,不会再访问服务器端的Servlet,而是访问本地缓存内容。要想每次客户端访问都访问到服务器端的Servlet的话,我们需要禁止浏览器缓存机制。
我们可以通过响应头信息中的三个相关内容来设置禁止浏览器缓存。
public class ResponseServlet4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//设置响应头信息,禁止浏览器缓存.
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", -1);
PrintWriter out = response.getWriter();
out.println("<h1>已经成功地访问了当前Servlet...</h1>");
  }
  发现在响应内容的页面中,中文显示为乱码。利用Response对象响应前,需要设置响应编码的字符集。
  response.setCharacterEncoding("utf-8");
  需要注意的是,其实在调用Response对象的setContentType()方法时,设置的编码字符集是覆盖了Response对象的setCharacterEncoding()方法设置的编码字符集的。所以,实际上只调用setContentType()方法即可。
利用Response对象的getWriter()方法或getOutputStream()方法向客户端进行响应的时候,需要注意的问题是:
如果需要手动响应内容的时候,使用getWriter()方法,否则使用getOutputStream()方法。
getWriter()方法和getOutputStream()方法之间是互斥的,也就是说只能使用其中一个方法。
使用getWriter()方法或getOutputStream()方法只能向客户端响应体,而不能修改响应行和响应头信息。
getWriter()方法或getOutputStream()方法进行响应时,Tomcat服务器会自动关闭响应输出流,不必手动关闭响应输出流。


JavaBean

说说你所熟悉或听说过的j2ee中的几种常用模式?及对设计模式的一些看法
  Session Facade Pattern:使用SessionBean访问EntityBean;Message Facade Pattern:实现异步调用;EJB Command Pattern:使用Command JavaBeans取代SessionBean,实现轻量级访问;Data Transfer Object Factory:通过DTO Factory简化EntityBean数据提供特性;Generic Attribute Access:通过AttibuteAccess接口简化EntityBean数据提供特性;Business Interface:通过远程(本地)接口和Bean类实现相同接口规范业务逻辑一致性;EJB架构的设计好坏将直接影响系统的性能、可扩展性、可维护性、组件可重用性及开发效率。项目越复杂,项目队伍越庞大则越能体现良好设计的重要性。
30、说说在weblogic中开发消息Bean时的persistent与non-persisten的差别persistent方式的MDB可以保证消息传递的可靠性,也就是如果EJB容器出现问题而JMS服务器依然会将消息在此MDB可用的时候发送过来,而non-persistent方式的消息将被丢弃。
请对以下在J2EE中常用的名词进行解释(或简单描述)web容器:给处于其中的应用程序组件(JSP,SERVLET)提供一个环境,使JSP,SERVLET直接更容器中的环境变量接口交互,不必关注其它系统问题。主要有WEB服务器来实现。例如:TOMCAT,WEBLOGIC,WEBSPHERE等。该容器提供的接口严格遵守J2EE规范中的WEB APPLICATION 标准。我们把遵守以上标准的WEB服务器就叫做J2EE中的WEB容器。EJB容器:Enterprise java bean 容器。更具有行业领域特色。他提供给运行在其中的组件EJB各种管理功能。只要满足J2EE规范的EJB放入该容器,马上就会被容器进行高效率的管理。并且可以通过现成的接口来获得系统级别的服务。例如邮件服务、事务管理。JNDI:(Java Naming & Directory Interface)JAVA命名目录服务。主要提供的功能是:提供一个目录系统,让其它各地的应用程序在其上面留下自己的索引,从而满足快速查找和定位分布式应用程序的功能。JMS:(Java Message Service)JAVA消息服务。主要实现各个应用程序之间的通讯。包括点对点和广播。JTA:(Java Transaction API)JAVA事务服务。提供各种分布式事务服务。应用程序只需调用其提供的接口即可。JAF:(Java Action FrameWork)JAVA安全认证框架。提供一些安全控制方面的框架。让开发者通过各种部署和自定义实现自己的个性安全控制策略。RMI/IIOP:(Remote Method Invocation /internet对象请求中介协议)他们主要用于通过远程调用服务。例如,远程有一台计算机上运行一个程序,它提供股票分析服务,我们可以在本地计算机上实现对其直接调用。当然这是要通过一定的规范才能在异构的系统之间进行通信。RMI是JAVA特有的。
38、MVC的各个部分都有那些技术来实现?如何实现? MVC是Model-View-Controller的简写。"Model" 代表的是应用的业务逻辑(通过JavaBean,EJB组件实现), "View" 是应用的表示面(由JSP页面产生),"Controller" 是提供应用的处理过程控制(一般是一个Servlet),通过这种设计模型把应用逻辑,处理过程和显示逻辑分成不同的组件实现。这些组件可以进行交互和重用。
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="com.java1234.model.Student" %>
<!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>
<%
Student student=new Student();
student.setName("王二小");
student.setAge(12);
%>
<h1>姓名:<%=student.getName() %></h1>
<h1>年龄:<%=student.getAge() %></h1>
</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>
<jsp:useBean id="student" scope="page" class="com.java1234.model.Student"/>
<%
student.setName("王二小2");
student.setAge(12);
%>
<h1>姓名:<%=student.getName() %></h1>
<h1>年龄:<%=student.getAge() %></h1>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="com.java1234.model.Student" %>
<!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.setCharacterEncoding("utf-8");
String name=request.getParameter("name");
String age=request.getParameter("age");
Student student=new Student();
student.setName(name); //表单输入
student.setAge(Integer.parseInt(age));
%>
<h1>姓名:<%=student.getName() %></h1>
<h1>年龄:<%=student.getAge() %></h1>
</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.setCharacterEncoding("utf-8");
%>
<jsp:useBean id="student" scope="page" class="com.java1234.model.Student"/>//useBean默认属性 scope一共有 page,session,request,application组成
<jsp:setProperty property="*" name="student"/>
<h1>姓名:<%=student.getName() %></h1>
<h1>年龄:<%=student.getAge() %></h1>
</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.setCharacterEncoding("utf-8");
%>
<jsp:useBean id="student" scope="page" class="com.java1234.model.Student"/>
<jsp:setProperty property="name" name="student"/>//name实例化对象的名称property属性 javabean的name
<jsp:setProperty property="age" name="student" value="100"/>
<h1>姓名:<%=student.getName() %></h1>
<h1>年龄:<%=student.getAge() %></h1>
</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.setCharacterEncoding("utf-8");
%>
<jsp:useBean id="student" scope="page" class="com.java1234.model.Student"/>//name和属性匹配不上引入param
<jsp:setProperty property="name" name="student" param="userName"/>
<jsp:setProperty property="age" name="student" value="100"/>
<h1>姓名:<%=student.getName() %></h1>
<h1>年龄:<%=student.getAge() %></h1>
</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>
<jsp:useBean id="student" scope="page" class="com.java1234.model.Student"/>
<%
student.setName("王二小2");
student.setAge(12);
%>
<h1>姓名:<jsp:getProperty property="name" name="student"/></h1>
<h1>年龄:<jsp:getProperty property="age" name="student"/></h1>
</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>
<jsp:useBean id="student" scope="request" class="com.java1234.model.Student"/>
<jsp:setProperty property="name" name="student" value="王八蛋"/>
<jsp:setProperty property="age" name="student" value="12"/>
<jsp:forward page="target01.jsp"/>
</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>
<jsp:useBean id="student" scope="session" class="com.java1234.model.Student"/>
<jsp:setProperty property="name" name="student" value="王八蛋"/>
<jsp:setProperty property="age" name="student" value="12"/>
<h1>Session数据设置完毕!</h1>
</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>
<jsp:useBean id="student" scope="application" class="com.java1234.model.Student"/>
<jsp:setProperty property="name" name="student" value="李四"/>
<jsp:setProperty property="age" name="student" value="13"/>
<h1>Application数据设置完毕!</h1>
</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>
<%
session.removeAttribute("student");//删除session中的javabean
%>
<h1>javabean已删除!</h1>
</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>
<form action="javabean03-3.jsp" method="post">
<table>
<tr>
<td>姓名:</td> 
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="提交"/></td>
</tr>
</table>
</form>
</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>
<jsp:useBean id="student" scope="request" class="com.java1234.model.Student"/>//request可以forward
<h1>姓名:<jsp:getProperty property="name" name="student"/></h1>
<h1>年龄:<jsp:getProperty property="age" name="student"/></h1>
</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>
<h1>Session中取值</h1>
<jsp:useBean id="student" scope="session" class="com.java1234.model.Student"/>
<h1>姓名:<jsp:getProperty property="name" name="student"/></h1>
<h1>年龄:<jsp:getProperty property="age" name="student"/></h1>
</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>
<h1>Application中取值</h1>
<jsp:useBean id="student" scope="application" class="com.java1234.model.Student"/>//application全局服务器在其他浏览器也可以取到
<h1>姓名:<jsp:getProperty property="name" name="student"/></h1>
<h1>年龄:<jsp:getProperty property="age" name="student"/></h1>
</body>
</html>


转发与重定向

SERVLET API中forward() 与redirect()的区别? 
答:前者仅是容器中控制权的转向,在客户端浏览器地址栏中不会显示出转向后的地址;后者则是完全的跳转,浏览器将会得到跳转的地址,并重新发送请求链接。这样,从浏览器的地址栏中可以看到跳转后的链接地址。所以,前者更加高效,在前者可以满足需要时,尽量使用forward()方法,并且,这样也有助于隐藏实际的链接。在有些情况下,比如,需要跳转到一个其它服务器上的资源,则必须使用sendRedirect()方法。 
什么情况下调用doGet()和doPost()? 
Jsp页面中的FORM标签里的method属性为get时调用doGet(),为post时调用doPost()。 
forward 和redirec
forward是服务器请求资源,服务器直接访问目标地址的URL,把那个URL的响应内容读取过来,然后把这些内容再发给浏览器,浏览器根本不知道服务器发送的内容是从哪儿来的,所以它的地址栏中还是原来的地址。 redirect就是服务端根据逻辑,发送一个状态码,告诉浏览器重新去请求那个地址,一般来说浏览器会用刚才请求的所有参数重新请求,所以session,request参数都可以获取。
两种跳转方式分别是什么?有什么区别? 
(下面的回答严重错误,应该是想问forward和sendRedirect 的区别,毕竟出题的人不是专业搞文字艺术的人,可能表达能力并不见得很强,用词不一定精准,加之其自身的技术面也可能存在一些问题,不一定真正将他的意思表达清楚了,严格意思上来讲,一些题目可能根本就无人能答,所以,答题时要掌握主动,只要把自己知道的表达清楚就够了,而不要去推敲原始题目的具体含义是什么,不要一味想着是在答题)
答:有两种,分别为: 
<jsp:include page=included.jsp flush=true> 
<jsp:forward page= nextpage.jsp/> 
前者页面不会转向include所指的页面,只是显示该页的结果,主页面还是原来的页面。执行完后还会回来,相当于函数调用。并且可以带参数.后者完全转向新页面,不会再回来。相当于go to 语句。
3.1.Servlet的生命周期
一般情况下,自定义Servlet都是继承HttpServlet。但通过HttpServlet的继承链,我们知道HttpServlet是实现了Servlet接口,下面列表是Servlet接口提供的所有方法。
上述所有方法中,init()、service()和destroy()方法叫做Servlet的生命周期。下面我们分别讨论一下有关生命周期的三个方法:
init()方法
在Servlet实例化之后,Servlet容器会调用init()方法,主要是用来完成处理客户端请求之前的初始化工作。
init()方法在Servlet的生命周期中只被执行一次。
service()方法
Servlet容器调用service()方法来处理客户端发送的请求。在service()方法被调用之前,必须保证init()方法被正确执行。
service()方法在每次客户端发送请求之后,会被执行一次。
destroy()方法
当Servlet容器检测到当前Servlet实例被移除时,会调用destroy()方法,以便让Servlet实例可以释放所使用的所有资源。
destroy()方法在Servlet的生命周期中也只被执行一次。
下面我们通过实际操作来讨论关于Servlet的生命周期是怎么样的:
//四步:servlet类加载启动的时候类加载-->实例化第一次访问实例化init只执行一次--->服务请求doget dopost--->销毁销毁长时间不用自动销毁
public class LifeServlet implements Servlet {


public LifeServlet(){
System.out.println("这里创建了一个Servlet实例对象...");
}


public void init(ServletConfig config) throws ServletException {
System.out.println("这是init()方法...");
}


public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
System.out.println("这是service()方法...");
}


public void destroy() {
System.out.println("这是destroy()方法...");
}

public ServletConfig getServletConfig() {
return null;
}
public String getServletInfo() {
return null;
}
}


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>HeadFirstJspServletChap05</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
  <servlet-name>helloWorldServlet</servlet-name>
  <servlet-class>com.java1234.web.HelloWorldServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>helloWorldServlet</servlet-name>
  <url-pattern>/helloWorld</url-pattern>
  </servlet-mapping>
  
  <servlet>
  <servlet-name>lifeServlet</servlet-name>
  <servlet-class>com.java1234.web.LifeServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>lifeServlet</servlet-name>
  <url-pattern>/life</url-pattern>
  </servlet-mapping>
  
  <servlet>
  <servlet-name>redirectServlet</servlet-name>
  <servlet-class>com.java1234.web.RedirectServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>redirectServlet</servlet-name>
  <url-pattern>/redirect</url-pattern>
  </servlet-mapping>
  
  
  <servlet>
  <servlet-name>forwardServlet</servlet-name>
  <servlet-class>com.java1234.web.ForwardServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>forwardServlet</servlet-name>
  <url-pattern>/forward</url-pattern>
  </servlet-mapping>
</web-app>


<%@ 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>
<h1>目标地址</h1>
request值:<%=request.getAttribute("requestKey") %><br/>
session值:<%=session.getAttribute("sessionKey") %><br/>
application值:<%=application.getAttribute("applicationKey") %><br/>
</body>
</html>


package com.java1234.web;


import java.io.IOException;


import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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 ForwardServlet extends HttpServlet{


/**

*/
private static final long serialVersionUID = 1L;


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("requestKey", "request值");
HttpSession session=request.getSession();  // 获取sessionservlet中获取session
session.setAttribute("sessionKey", "session值");
ServletContext application=this.getServletContext(); // 获取application
application.setAttribute("applicationKey", "application值");
RequestDispatcher rd=request.getRequestDispatcher("target.jsp");
rd.forward(request, response); // 服务器调转/转发转发可以获取request值
}





}




package com.java1234.web;


import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class HelloWorldServlet extends HttpServlet{


/**

*/
private static final long serialVersionUID = 1L;


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("get");
this.doPost(request, response);
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("gbk");
PrintWriter out=response.getWriter();//向页面写东西
out.println("<html>");
out.println("<head><title>问候大爷</title></head>");
out.println("Servlet大爷你好!");
out.println("</html>");
out.close();
}





}




package com.java1234.web;


import java.io.IOException;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author caofeng
 *
 */
public class LifeServlet extends HttpServlet{


/**

*/
private static final long serialVersionUID = 1L;


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("service");
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("service");
}


@Override
public void destroy() {
System.out.println("servlet销毁");
}


@Override
public void init() throws ServletException {
System.out.println("servlet初始化");
}





}


package com.java1234.web;


import java.io.IOException;


import javax.servlet.ServletContext;
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 RedirectServlet extends HttpServlet{


/**

*/
private static final long serialVersionUID = 1L;


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("requestKey", "request值");
HttpSession session=request.getSession();  // 获取session
session.setAttribute("sessionKey", "session值");
ServletContext application=this.getServletContext(); // 获取application
application.setAttribute("applicationKey", "application值");
response.sendRedirect("target.jsp"); // 客户端跳转/重定向 request值取不到
}


}

过滤器与监听器

使用JSP技术开发Web应用程序,有两种架构模型可供选择,通常称为模型1(Model1)和模型2(Model2)。
JSP的开发模型1就是使用JSP+JavaBean技术将页面显示和业务逻辑处理分开。JSP实现页面的显示,JavaBean对象用来保存数据和实现商业逻辑。
JSP的开发模型1的工作流程就是JSP页面响应用户请求并将处理结果返回给用户,所有的数据处理通过JavaBean来处理。JSP的开发模型1工作流程可以参考如下图:
上述图表具体的工作流程如下:
用户通过客户端向服务器端发送请求,服务器端由JSP页面接收客户端的请求。
JSP页面将数据的处理和保存工作,分发给JavaBean来负责。
JavaBean调用并操作数据库,由数据库完成数据的操作工作。
JavaBean处理完数据相关工作之后,将结果返回给JSP页面。
JSP页面将最终的处理结果响应给客户端浏览器,显示给用户。
创建一个JSP页面用于显示计算在掌握JSP开发模型1的理论部分后,通过模型1来完成一个简单计算器的案例,具体完成步骤如下:
器页面效果和计算结果。


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>HeadFirstJspServletChap05</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
  <servlet-name>helloWorldServlet</servlet-name>
  <servlet-class>com.java1234.web.HelloWorldServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>helloWorldServlet</servlet-name>
  <url-pattern>/helloWorld</url-pattern>
  </servlet-mapping>
  
  <servlet>
  <servlet-name>lifeServlet</servlet-name>
  <servlet-class>com.java1234.web.LifeServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>lifeServlet</servlet-name>
  <url-pattern>/life</url-pattern>
  </servlet-mapping>
  
  <servlet>
  <servlet-name>redirectServlet</servlet-name>
  <servlet-class>com.java1234.web.RedirectServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>redirectServlet</servlet-name>
  <url-pattern>/redirect</url-pattern>
  </servlet-mapping>
  
  
  <servlet>
  <servlet-name>forwardServlet</servlet-name>
  <servlet-class>com.java1234.web.ForwardServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>forwardServlet</servlet-name>
  <url-pattern>/forward</url-pattern>
  </servlet-mapping>
  
  <servlet>
  <servlet-name>loginServlet</servlet-name>
  <servlet-class>com.java1234.web.LoginServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>loginServlet</servlet-name>
  <url-pattern>/login</url-pattern>
  </servlet-mapping>
  
  <servlet>
  <servlet-name>logoutServlet</servlet-name>
  <servlet-class>com.java1234.web.LogoutServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>logoutServlet</servlet-name>
  <url-pattern>/logout</url-pattern>
  </servlet-mapping>
  
  <filter>
  <filter-name>loginFilter</filter-name>
  <filter-class>com.java1234.filter.LoginFilter</filter-class>
  </filter>
  
  
  
  <filter-mapping>
  <filter-name>loginFilter</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <listener>
  <listener-class>
  com.java1234.listener.SessionAttributeListener
  </listener-class>
  </listener>
</web-app>


<%@ 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>
<form action="login" method="post">//web.xml
<table>
<tr>
<th colspan="2">用户登录</th>
</tr>
<tr>
<td>用户名:</td>
<td><input type="text" id="userName" name="userName" value="${userName }"/></td>//EL获取request四大作用域的值
</tr>
<tr>
<td>密码:</td>
<td><input type="password" id="password" name="password" value="${password }"/></td>
</tr>
<tr>
<td><input type="submit" value="登录"/></td>
<td><font color="red">${error }</font></td>//给用户提示


</tr>
</table>
</form>
</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>
主页!当前登录用户:${currentUser.userName } &nbsp;&nbsp;<a href="logout">注销</a>//web.xml配置
</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>
<h1>目标地址</h1>
request值:<%=request.getAttribute("requestKey") %><br/>
session值:<%=session.getAttribute("sessionKey") %><br/>
application值:<%=application.getAttribute("applicationKey") %><br/>
</body>
</html>


package com.java1234.dao;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


import com.java1234.model.User;


public class UserDao {//处理数据库操作


public User login(Connection con,User user)throws Exception{
User resultUser=null;
String sql="select * from t_user where userName=? and password=?";
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1, user.getUserName());
pstmt.setString(2, user.getPassword());
ResultSet rs=pstmt.executeQuery();
if(rs.next()){
resultUser=new User();
resultUser.setUserName(rs.getString("userName"));
resultUser.setPassword(rs.getString("password"));
}
return resultUser;
}

}


package com.java1234.filter;


import java.io.IOException;


import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


public class LoginFilter implements Filter{//实现过滤器实现Filter接口


public void destroy() {
// TODO Auto-generated method stub

}


public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)servletRequest;//不是servlet的request
HttpSession session=request.getSession();//每次过滤判断session是否有内容,session没有转发到登录中去
Object o=session.getAttribute("currentUser");//返回的是对象
String path=request.getServletPath();
if(o==null&&path.indexOf("login")<0){//排除登录的可能,没有到后台,不是login才这样是往后请求
request.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse);
}else{//用户已经登录了 
filterChain.doFilter(servletRequest, servletResponse);
}
}


public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}


}


package com.java1234.listener;


import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;


public class SessionAttributeListener implements HttpSessionAttributeListener{


public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {//传递过来的是绑定的事件


// TODO Auto-generated method stub
System.out.println("添加的属性名:"+httpSessionBindingEvent.getName()+",属性值:"+httpSessionBindingEvent.getValue());
}


public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
// TODO Auto-generated method stub
System.out.println("删除的属性名:"+httpSessionBindingEvent.getName()+",属性值:"+httpSessionBindingEvent.getValue());
}


public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
// TODO Auto-generated method stub

}


}


package com.java1234.model;


public class User {


private int id;
private String userName;
private String password;



public User() {
super();
// TODO Auto-generated constructor stub
}


public User(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}




public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}


}


package com.java1234.util;


import java.sql.Connection;
import java.sql.DriverManager;


public class DbUtil {


private String dbUrl="jdbc:mysql://localhost:3306/db_jsp";//连接的数据库db_jsp
private String dbUserName="root";
private String dbPassword="123456";
private String jdbcName="com.mysql.jdbc.Driver";

public Connection getCon()throws Exception{
Class.forName(jdbcName);//反射把驱动包实例化一下
Connection con=DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
return con;
}

public void closeCon(Connection con)throws Exception{
if(con!=null){
con.close();
}
}

public static void main(String[] args) {
DbUtil dbUtil=new DbUtil();
try {
dbUtil.getCon();
System.out.println("连接成功");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


package com.java1234.web;


import java.io.IOException;
import java.sql.Connection;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import com.java1234.dao.UserDao;
import com.java1234.model.User;
import com.java1234.util.DbUtil;


public class LoginServlet extends HttpServlet{//处理逻辑


/**

*/
private static final long serialVersionUID = 1L;

DbUtil dbUtil=new DbUtil();
UserDao userDao=new UserDao();


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName=request.getParameter("userName");
String password=request.getParameter("password");

Connection con=null;
try {
User user=new User(userName,password);//把user对象封装起来传到dao中
con=dbUtil.getCon();
User currentUser=userDao.login(con, user);
if(currentUser==null){
request.setAttribute("error", "用户名或密码错误");
request.setAttribute("userName", userName);//把原来传的返回去提高用户体验
request.setAttribute("password", password);
request.getRequestDispatcher("login.jsp").forward(request, response);
}else{
HttpSession session=request.getSession();//登陆成功把当前用户存到session中
session.setAttribute("currentUser", currentUser);
response.sendRedirect("main.jsp");//重定向不需要用转发


}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}


package com.java1234.web;


import java.io.IOException;
import java.sql.Connection;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import com.java1234.dao.UserDao;
import com.java1234.model.User;
import com.java1234.util.DbUtil;


public class LogoutServlet extends HttpServlet{





/**

*/
private static final long serialVersionUID = 1L;


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getSession().invalidate();//清除session
response.sendRedirect("login.jsp");
}


}






















原创粉丝点击