java web 学习 --第五天(Java三级考试)
第四天的学习内容:http://www.cnblogs.com/tobecrazy/p/3454860.html
Response对象
response对象主要是向客户端浏览器发送二进制数据,如输出Cookie、设置HTTP文件头信息等方面内容
response主要功能和方法
- getWrite() 获得PrintWrite类的对象实例,实现向浏览器输出信息
- addCookie() 在客户端计算机磁盘上创建出Cookie对象实例,在Cookie对象实例可以保存客户端信息特征,然后采用request对象的getCookies()方法获取客户机所有Cookie对象
- addHeader() 添加HTTP头文件信息,将信息传送到客户浏览器中
- containsHeader() 判断指定名字的文件头是否存在,返回布尔型true / false
- setHeader() 设置指定名字HTTP头文件的值,若该值存在则覆盖
- sendRedirect() 重定向到由参数targetURL所指示的目标JSP页面或Servlet程序,不能向客户端输出信息
- setContentType() 在相应中可以设置内容的文档数据类型和格式
- setBufferSize() 设置Web容器的缓冲区大小,配合getBufferSize()方法返回该缓冲器信息
利用response对象实现向客户机种写入Cookie信息
Cookie或称Cookies,是指Web应用系统为了辨别访问者身份而存储在客户机中的一个文本文件,其中包含特定数据,比如登陆邮箱:
可以把用户名和密码放在客户机Cookie中,下次访问不需要再输入用户名密码
读取Cookie文件信息,使用Cookie类中的getName()和getValue()返回客户端的某一个特定Cookie对象名所对应的值。而利用response对象addCookie(cookie data )方法可以写入Cookie对象中所包装的数据。
实例:在系统首页中添加读写Cookie信息
在index jsp页面中添加如下代码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="java.util.Date" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP add Cookie information </title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body>
<%! String lastAccessTime=null; //the last time view this web site
String nowAccessTime=null;
Cookie mycookie=null;
Cookie[] cookies=null;
Date now=null;
%>
<%
cookies=request.getCookies(); // use request class getCookie method to get cookies if there is no cookie info then add new
now=new Date();
if(cookies==null)
{
lastAccessTime=(now.getYear()+1900+"Year"+now.getMonth()+"Month"+now.getDay()+"Day"+now.getHours()+"Hour"+now.getMinutes()+"Minute"+now.getSeconds()+"Second");
mycookie=new Cookie("lastAccessTime",lastAccessTime);
mycookie.setMaxAge(30*24*60*60); // 30 days 24hours 60mins 60 seconds
response.addCookie(mycookie);
}
else
for(int index=0;index<cookies.length;index++)
{
if(cookies[index].getName().equals("lastAccessTime"))
{
lastAccessTime=cookies[index].getValue();
nowAccessTime=(now.getYear()+1900+"Year "+now.getMonth()+" Month "+now.getDay()+" Day "+now.getHours()+" Hour "+now.getMinutes()+" Minute "+now.getSeconds()+" Second");
mycookie=new Cookie("lastAccessTime",nowAccessTime);
mycookie.setMaxAge(30*24*60*60); // 30 days 24hours 60mins 60 seconds
response.addCookie(mycookie);
break;
}
}
out.print("the last time your visit this system is "+lastAccessTime); %>
</body>
</html>
首先用request的getCookie获取一下cookie,如果没有cookie信息,使用response的addCookie增加cookie信息
区分重定向与跳转方式的区别
- 请求转发过程中客户端浏览器只向server端产生一次请求,而重定向是两次;
- 请求转发时在浏览器的URL地址栏中的信息不会发生改变,仍然是原来的URL而重定向将会转向目标URL
使用HTTP请求转发:
使用转发由于只有一次请求,所以在一个页面的request.setAttribute 能够在跳转后的页面使用request.getAttribute获取其属性值
使用4个jsp页面和一个类文件
新建 login.jsp 设置登陆框,用户名密码。。。。。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page isErrorPage="true" errorPage="error.jsp" %> <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>This is my first JSP page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body> <form method="post" action="response.jsp" >
username:
<input type="text" name="user" >
<br>
password:
<input type="password" name="password">
<br>
userType:
<select name="userType">
<option value="user" >user</option>
<option value="master"> master</option>
</select> <input type="submit" name="submit" />
</form> </body>
</html>
新建response.jsp页面当用户名是:young并且密码是1234跳转到index.jsp否则跳转到error.jsp,引入userInfo类,使用其verifyID方法校验用户名密码
userinfo类代码:
package mypackage;
public class userInfo {
/**
* @param args
* two parameters add get/set methods
*/
String userName=null;
String passWord=null;
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 boolean verifyID( )
{
if(userName.equals("young") && passWord.equals("1234"))
{
System.out.print("login successful\n");
return true;
}
else
{
System.out.print("login failure\n");
return false;
}
}
}
代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<jsp:useBean id="user" class="mypackage.userInfo" scope="session" ></jsp:useBean> <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'response.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">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body>
<%!
String targetPage=null;
RequestDispatcher rd=null;
%>
<%
user.setUserName(request.getParameter("user"));
user.setPassWord(request.getParameter("password")); if(user.verifyID())
{
request.setAttribute("userNameString",user.getUserName());
targetPage="index.jsp";
System.out.print(user.getUserName());
}
else
{
request.setAttribute("errorMSG","sorry,Login FAILED.\n");
targetPage="error.jsp";
}
rd=request.getRequestDispatcher(targetPage);
rd.forward(request,response);
%>
</body>
</html>
新建error.jsp 这个页面会获取response.jsp传递过来的errorMSG
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <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">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body>
errorMSG<br>
<%=request.getAttribute("errorMSG") %>
</body>
</html>
新建index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="java.util.Date" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP add Cookie information </title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body>
welcome <%=request.getAttribute("userNameString") %>
<%! String lastAccessTime=null; //the last time view this web site
String nowAccessTime=null;
Cookie mycookie=null;
Cookie[] cookies=null;
Date now=null;
%>
<%
cookies=request.getCookies(); // use request class getCookie method to get cookies if there is no cookie info then add new
now=new Date();
if(cookies==null)
{
lastAccessTime=(now.getYear()+1900+"Year"+now.getMonth()+"Month"+now.getDay()+"Day"+now.getHours()+"Hour"+now.getMinutes()+"Minute"+now.getSeconds()+"Second");
mycookie=new Cookie("lastAccessTime",lastAccessTime);
mycookie.setMaxAge(30*24*60*60); // 30 days 24hours 60mins 60 seconds
response.addCookie(mycookie);
}
else
for(int index=0;index<cookies.length;index++)
{
if(cookies[index].getName().equals("lastAccessTime"))
{
lastAccessTime=cookies[index].getValue();
nowAccessTime=(now.getYear()+1900+"Year "+now.getMonth()+" Month "+now.getDay()+" Day "+now.getHours()+" Hour "+now.getMinutes()+" Minute "+now.getSeconds()+" Second");
mycookie=new Cookie("lastAccessTime",nowAccessTime);
mycookie.setMaxAge(30*24*60*60); // 30 days 24hours 60mins 60 seconds
response.addCookie(mycookie);
break;
}
}
out.print("the last time your visit this system is "+lastAccessTime); %>
</body>
</html>
登陆成功会显示: 可以看出,跳转后的页面URL仍然是跳转前的URL并未发生任何变化,由于只进行一次请求,所以request.setAttribute 和request.getAttribute能够正常工作

登陆失败:

而是用response.sendRedirect()会出现2次请求不能再是用request的对象包装和传递参数,可以使用session.setAttribute("NAME","VALUE")使用EL表达式语句${sesstionScope.userNameString}
从session会话对象中获取传递的参数,同时重定向后的URL为重定向页面的URL。
java web 学习 --第五天(Java三级考试)的更多相关文章
- java web学习总结(五) -------------------servlet开发(一)
一.Servlet简介 Servlet是sun公司提供的一门用于开发动态web资源的技术. Sun公司在其API中提供了一个servlet接口,用户若想用发一个动态web资源(即开发一个Java程序向 ...
- java web 学习 --第九天(Java三级考试)
第八天的学习内容如下:http://www.cnblogs.com/tobecrazy/p/3468458.html Java servlet 技术 Servlet是使用java servlet应用程 ...
- java web 学习 --第一天(Java三级考试)
1.Servlet servlet是运行在web server或 application server端的Java程序,主要用于在服务器端产生动态内容. servlet 在服务器端主要有以下作用 读取 ...
- Java Web学习(十一)Java过滤器
一.引言 上一篇文章学习了java三大器的拦截器,拦截器主要是针对于action请求进行拦截处理的,那么对于requst的一些信息如果在调用前,想先进行过滤和处理,那么就要使用到第二个神器,也就是本文 ...
- java web 学习 --第二天(Java三级考试)
第一天的学习在这http://www.cnblogs.com/tobecrazy/p/3444474.html 2.jsp 基础知识 Jsp页面中的Java脚本主要有3部分:声明(Declaratio ...
- java web 学习十五(jsp基础语法)
任何语言都有自己的语法,JAVA中有,JSP虽然是在JAVA上的一种应用,但是依然有其自己扩充的语法,而且在JSP中,所有的JAVA语句都可以使用. 一.JSP模版元素 JSP页面中的HTML内容称之 ...
- java web 学习 --第八天(Java三级考试)
第七天的学习内容:http://www.cnblogs.com/tobecrazy/p/3464231.html EL表达式 EL : Expression Language 使用EL表达式可以减少& ...
- Java Web学习(五)session、cookie、token
文章更新时间:2020/09/14 一.引言 动态网页兴起后,会话管理变成开发者需要考虑的一个问题,由于HTTP请求是无状态的,为了区分每个用户,此时引入了会话标识(sessionId)的概念,但是存 ...
- [原创]java WEB学习笔记36:Java Bean 概述,及在JSP 中的使用,原理
本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...
随机推荐
- 新浪微博客户端(35)-使用NSMutableAttributedString实现多行文本的效果
DJComposeViewController.m import "DJComposeViewController.h" #import "DJAccountTool.h ...
- nanosleep() -- 更精确的延迟 -----一个使用用例
[常规] nanosleep() -- 更精确的延迟 [复制链接] beyes 4220 主题 5152 帖子 3万 积分 GROAD 曲径通幽,安觅芳踪. 积分 30607 发消息 电梯直达 ...
- matlab求解相关系数
最近收到一项新任务,要求两个矩阵的相关系数,说白了就是转换成向量两两计算.本来这个工作我是想自己写个小程序搞定的,但是大家纷纷反映matlab自带了此项功能,本着活到老学到老的心态,我开始查找这个函数 ...
- 编译本地64位版本的hadoop-2.6.0
官方提供的hadoop-2.x版本貌似都是32位的,在64位机子下使用可能会报错,最好使用官方提供的源码进行本地编译,编译成适合本地硬件环境的64位软件包. 关于native Hadoop是使用J ...
- 只会CSS还不够,LESS、SASS、BootStrap、Foundation一网打尽!
有些人想学CSS,不知如何下手:有些人已经学会CSS的各种属性,却不知如何运用:有些人会平面设计,不知道如何与网页设计结合:有些人会HTML,就是学不会CSS.试问自己,图中的技术你都会了吗? 别总是 ...
- 【转】GATK使用方法详解(包含bwa使用)
一.使用GATK前须知事项: (1)对GATK的测试主要使用的是人类全基因组和外显子组的测序数据,而且全部是基于illumina数据格式,目前还没有提供其他格式文件(如Ion Torrent)或者实验 ...
- VC++6.0MFC运行的简单流程
背景: 由于下位机做的一些东西,总是需要通过上位机来验证,以及为了直观给客户展示下位机的功能,所以时常需要编写一些简单的APP.今天就以VC++6.0为例,简单的记录下该如何快速的创建一个APP. 正 ...
- 分分钟教会大家第一个Spring入门案例
1.下载Spring jar包,并添加到项目中. 官网地址http:springsource.org 2.在项目中新建一个类 package cn.test; public class He ...
- H5案例分享:html5重力感应事件
html5重力感应事件 一.手机重力感应图形分析 1.设备围绕z轴的旋转角度为α,α角度的取值范围在[0,360). 设备在初始位置,与地球(XYZ)和身体(XYZ)某个位置对齐. 设备围绕z轴的旋转 ...
- DOM之节点层次
1.1 Node类型 DOM1级定义了一个Node接口,该接口将由DOM中的所有节点类型实现.这个Node接口在JS中是作为Node类型实现的:除了IE之外,其他浏览器可访问这个类型.JS中的所有节点 ...