JavaWeb学习笔记--Servlet代码集
目录:
登录系统
提交表单数据
打开PDF
Cookie
URL传递参数
URL重写跟踪会话
使用HttpSession对象跟踪会话
Servlet间协作
过滤器Filter
<!DOCTYPE HTML PUBLIC "=//w3c//dtd html 4.0 transitional/cn">
<html>
<head>
<title>提交表单数据</title>
</head> <body bgcolor="#FFFFFF">
<h1 align="center"><b>欢迎登陆系统</b></h1>
<form action = "servlet/GetPostData" method = "post">
<p></p>
<table width = "52%"border="2" align ="center">
<tr bgcolor ="#FFFFCC">
<td align = "center" width="43%"><div align="center">用户名:</div></td>
<td width="57%">
<div align="left">
<input type ="text" name = "username">
</div>
</td>
</tr> <tr bgcolor = "#ccff99">
<td align = "center" width = "43%">
<div align= "center">密码:</div>
</td>
<td width = "57%">
<div align = left>
<input type="password" name= "password">
</div>
</td>
</tr>
</table> <p align="center">
<input type="reset" name= "Reset" value = "重置">
<input type="submit" name= "Submit2" value = "提交">
</form>
</body>
</html>
GetPostData.java
protected void processRequest(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException{
resp.setContentType("text/html;charset=gb2312"); //确保汉字信息正确编码方式显示
req.setCharacterEncoding("gb2312");//确保参数信息以汉字编码方式提取
PrintWriter myout = resp.getWriter();
myout.println(
"<html>"+
"<head></head>"+
"<body bgcolor=\"#FDF5E6\">\n"+
"<h1 align=center>"+"get post data" + "</h1>\n"+
"<ul>\n"+
"<li><b>username</b>:"+
req.getParameter("username")+"\n"+
"<li><b>password</b>:"+
req.getParameter("password")+"\n"+
"</ul>\n"+
"</body></html>"
);
myout.close();
} protected void doGet(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException{
processRequest(req,resp);
} protected void doPost(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException{
processRequest(req,resp); }
============================================================
<!DOCTYPE HTML PUBLIC "=//w3c//dtd html 4.0 transitional/cn">
<html>
<head>
<title>提交表单数据</title>
</head> <body bgcolor="#FFFFFF">
<h1 align="center"><b>选择你喜欢的蔬菜</b></h1>
<form action="servlet/GetPostData" method="post">
<input type="checkbox" name="vegatablebox" value="Cucumber">黄瓜
<input type="checkbox" name="vegatablebox" value="Tomato">西红柿
<input type="checkbox" name="vegatablebox" value="Potato">土豆
<ul></ul>
<input type="reset" name="Reset" value="重置">
<input type="submit" name="Submit" value="提交">
</form>
</body>
</html>
GetPostData.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html;charset=gb2312"); //确保汉字信息正确编码方式显示
request.setCharacterEncoding("gb2312");//确保参数信息以汉字编码方式提取
String[] paramValues = request.getParameterValues("vegatablebox");
PrintWriter out = response.getWriter();
out.print(
"<html>"+
"<head><title>喜欢的蔬菜</title></head>"+
"</body>"+
"你喜欢的蔬菜是:");
for(int vnum = 0 ; vnum < paramValues.length ; vnum++){
out.print(paramValues[vnum]+" ");
}
out.print(
"</body></html>"
);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
}
============================================================
public void pdfInfo(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("application/pdf");
ServletOutputStream out = response.getOutputStream();
//response.setHeader("Content-disposition", "attachment;filename=sample.pdf");
//不在网页中直接显示,而是下载
File pdf = null;
BufferedInputStream buf = null;
try{
pdf=new File("f:\\sample.pdf");
response.setContentLength((int)pdf.length());
FileInputStream input = new FileInputStream(pdf);
buf = new BufferedInputStream(input);
int readBytes=0;
while((readBytes=buf.read())!=-1)
out.write(readBytes);
}catch(IOException e){
out.println("File not found!");
}finally{
if(out!=null){
out.close();
}if(buf!=null)
buf.close();
}
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
pdfInfo( request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
pdfInfo( request, response);
}
============================================================
public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { Cookie cookie = null;
//获取请求相关的Cookie
Cookie[] cookies = request.getCookies();
//判断Cookie ServletStudy是否存在,若存在,数值+1
/*if(cookies!= null){
for(int i = 0 ; i <cookies.length ; i ++){
if(cookies[i].getName().equals("VisitTimes")){
String v = cookies[i].getValue();
int value = Integer.parseInt(v)+1;
cookies[i].setValue(Integer.toString(value));
//将值更新后的cookie重新写回响应
response.addCookie(cookies[i]);
cookie=cookies[i];
}
}
}//end if
*/
if(cookies!= null){
for(int i = 0 ; i <cookies.length ; i ++){
if(cookies[i].getName().equals("VisitTimes")){
cookie=cookies[i];
break;
}
}
}//end if if(cookie == null){
int maxAge=-1;
//创建Cookie对象
cookie=new Cookie("VisitTimes","1");
cookie.setPath(request.getContextPath());
cookie.setMaxAge(maxAge);
response.addCookie(cookie);
}//end if
else{
//定义一个存放次数的变量
int count = 0;
//通过getValue()方法得到从客户端myCookie的值,得到的值是一个String类型的要将转换成int类型的,才能进行计数操作
count = Integer.parseInt(cookie.getValue());
//累加访问的次数
count++;
//把count的值添加到定义的Cookie对象中
cookie.setValue(String.valueOf(count));
//设置Cookie的最大保存时间
//cookie.setMaxAge(60 * 60 * 24 * 30);
//把Cookie添加到客户端
response.addCookie(cookie); } //显示信息
response.setContentType("text/html;charset=gb2312"); //确保汉字信息正确编码方式显示
response.setCharacterEncoding("gb2312");//确保参数信息以汉字编码方式提取
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Cookie 跟踪会话</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>您好!</h2>");
out.println("欢迎您"+cookie.getValue()+"访问本页面<br>"); out.println("</body>");
out.println("</html>"); } public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
}
============================================================
URLRewrite.java
public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html,charset=GB2312");
response.setCharacterEncoding("gb2312");//确保参数信息以汉字编码方式提取
PrintWriter out = response.getWriter();
String contextPath = request.getContextPath();
String encodedUrl = response.encodeURL(contextPath+
"/servlet/URLRewriteServer?name=张三&age=27");
out.println("<html>");
out.println("<head>");
out.println("<title>URL Rewriter</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>URL重写演示:发送参数</h1>");
out.println("转到URL2<a href=\""+encodedUrl+"\">here</a>"); out.println("</body>");
out.println("</html>"); } public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
}
URLRewriteServer.java
public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html,charset=GB2312");
response.setCharacterEncoding("gb2312");//确保参数信息以汉字编码方式提取
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>URL Rewriter</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>URL重写演示:接收参数</h1>");
out.println("下面是接收的参数:<br>");
String paramname= request.getParameter("name");
String x = new String(paramname.getBytes("ISO-8859-1"), "GBK");
//直接显示汉字会导致乱码,所以先转换为GBK
//out.println("name="+request.getParameter("name"));
out.println(x);
out.println("age="+request.getParameter("age")); out.println("</body>");
out.println("</html>");
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
}
注意
String paramname= request.getParameter("name");
String x = new String(paramname.getBytes("ISO-8859-1"), "GBK");
//直接显示汉字会导致乱码,所以先转换为GBK
============================================================
URLRewrite.java
public class URLRewrite extends HttpServlet {
public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html,charset=GB2312");
response.setCharacterEncoding("gb2312");//确保参数信息以汉字编码方式提取
PrintWriter out = response.getWriter();
String contextPath = request.getContextPath();
String encodedUrl = response.encodeURL(contextPath+
"/servlet/URLRewriteServer?name=张三&age=27");
out.println("<html>");
out.println("<head>");
out.println("<title>URL Rewriter</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>URL重写演示:发送参数</h1>");
out.println("转到URL2<a href=\""+encodedUrl+"\">here</a>");
out.println("</body>");
out.println("</html>");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
}
}
URLRewriteServer.java
public class URLRewriteServer extends HttpServlet {
public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html,charset=GB2312");
response.setCharacterEncoding("gb2312");//确保参数信息以汉字编码方式提取
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>URL Rewriter</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>URL重写演示:接收参数</h1>");
out.println("下面是接收的参数:<br>");
String paramname= request.getParameter("name");
String x = new String(paramname.getBytes("ISO-8859-1"), "GBK");
//直接显示汉字会导致乱码,所以先转换为GBK
//out.println("name="+request.getParameter("name"));
out.println(x);
out.println("age="+request.getParameter("age"));
out.println("</body>");
out.println("</html>");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
}
}
============================================================
HitCounter.java
public class HitCounter extends HttpServlet {
static final String COUNTER_KEY="Counter";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取会话对象
HttpSession session = request.getSession(true);
response.setContentType("text/html;charset=GB2312");
response.setCharacterEncoding("gb2312");//确保参数信息以汉字编码方式提取
PrintWriter out = response.getWriter();
//从会话中获取属性
int count =1;
Integer i = (Integer)session.getAttribute(COUNTER_KEY);
//如果存在以前的数值
if(i!=null){
count=i.intValue()+1;
}
//将属性信息存入会话
session.setAttribute(COUNTER_KEY, new Integer(count));
Date lastAccessed = new Date(session.getLastAccessedTime());
Date sessionCreated = new Date(session.getCreationTime());
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM);
//输出对话信息
out.println("<html>");
out.println("<head>");
out.println("<title>会话计数器</title>");
out.println("</head>");
out.println("<body>");
out.println("你的会话ID:<b>"+session.getId()+"<br>");
out.println("会话创建时间:"+formatter.format(sessionCreated)+"<br>");
out.println("会话上次访问时间:"+formatter.format(lastAccessed)+"<br>");
out.println("</b>会话期间你向页面发起<b>"+count+"</b>次请求");
out.println("<form method=GET action=\""+request.getRequestURI()+"\">");
out.println("<input type='submit'"+"value=\"再次点击...\">");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
}
}
============================================================
Main.java
public class Main extends HttpServlet {
public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String m_userID = request.getParameter("userID");
if(m_userID==null) m_userID="";
String m_password = request.getParameter("password");
if(m_password==null) m_password="";
if(m_userID.equals("guest")&&m_password.equals("guest")){
RequestDispatcher dispatcher =request.getRequestDispatcher("/servlet/LoginSuccess");
dispatcher.forward(request,response);
//RequestDispatcher.forward()方法
//将当前的request和response重定向到该 RequestDispacher指定的资源。
}else{
RequestDispatcher dispatcher =request.getRequestDispatcher("/servlet/LoginFail");
dispatcher.forward(request,response);
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
}
}
LoginSuccess.java
public class LoginSuccess extends HttpServlet {
public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=GB2312");
response.setCharacterEncoding("gb2312");
PrintWriter out = response.getWriter();
String name = request.getParameter("userID");
out.println("<html>");
out.println("<head>");
out.println("<title>登录成功</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>欢迎!"+name+ "您已成功登录系统...</h1>");
out.println("</body>");
out.println("</html>");
out.close();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
}
}
LoginFail.java
代码和LoginSuccess.java类似,只改了汉字
dl.html
<!DOCTYPE HTML PUBLIC "=//w3c//dtd html 4.0 transitional/cn">
<html lang='zh'>
<head>
<title>登录</title>
</head>
<h1 align="center"><b>欢迎登陆系统</b></h1>
<form name="login" method = "post" action="servlet/Main">
<div align="center">用户名:</div>
<input type ="text" name = "userID" value="">
<div align= "center">密码:</div>
<input type="password" name= "password" value="">
<input type="reset" name= "reset" value = "重置">
<input type="submit" name= "tj" value = "提交">
</form>
</body>
</html>
============================================================
在上一部分的程序基础上加上
TimeTrackerFilter.java
public class TimeTrackFilter implements Filter {
private FilterConfig filterConfig=null;
public void destroy() {
this.filterConfig=null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
Date startTime , endTime;
double totalTime;
StringWriter sw = new StringWriter();
System.out.println("我在Filter中");
try{
Thread.sleep(2000);
}catch(InterruptedException e){
System.out.println(e.toString());
}
startTime = new Date();
chain.doFilter(request, response);
endTime = new Date();
totalTime = endTime.getTime()- startTime.getTime();
System.out.println("我在Filter中");
PrintWriter writer = new PrintWriter(sw);
writer.println("==============");
writer.println("耗时"+totalTime+"毫秒");
writer.println("==============");
filterConfig.getServletContext().log(sw.getBuffer().toString());
}
public void init(FilterConfig fConfig) throws ServletException {
this.filterConfig=fConfig;
} }
需要完成destory() init() doFilter() 三个函数
其余效果均与上一个程序相同,在服务器控制台会有如下显示
JavaWeb学习笔记--Servlet代码集的更多相关文章
- JavaWeb学习之Servlet(二)----Servlet的生命周期、继承结构、修改Servlet模板
[声明] 欢迎转载,但请保留文章原始出处→_→ 文章来源:http://www.cnblogs.com/smyhvae/p/4140466.html 一.http协议回顾: 在上一篇文章中:JavaW ...
- JavaWeb学习笔记总结 目录篇
JavaWeb学习笔记一: XML解析 JavaWeb学习笔记二 Http协议和Tomcat服务器 JavaWeb学习笔记三 Servlet JavaWeb学习笔记四 request&resp ...
- (转)JavaWeb学习之Servlet(二)----Servlet的生命周期、继承结构、修改Servlet模板
[声明] 欢迎转载,但请保留文章原始出处→_→ 文章来源:http://www.cnblogs.com/smyhvae/p/4140466.html 一.http协议回顾: 在上一篇文章中:JavaW ...
- JavaWeb学习——了解Servlet
JavaWeb学习——了解Servlet 摘要:本文主要学习了什么是Servlet,以及如何使用Servlet进行开发. 基础知识 背景 随着互联网技术的发展,基于HTTP和HTML的web应用急速增 ...
- javaweb学习笔记整理补课
javaweb学习笔记整理补课 * JavaWeb: * 使用Java语言开发基于互联网的项目 * 软件架构: 1. C/S: Client/Server 客户端/服务器端 * 在用户本地有一个客户端 ...
- Redis学习笔记八:集群模式
作者:Grey 原文地址:Redis学习笔记八:集群模式 前面提到的Redis学习笔记七:主从复制和哨兵只能解决Redis的单点压力大和单点故障问题,接下来要讲的Redis Cluster模式,主要是 ...
- ZooKeeper学习笔记一:集群搭建
作者:Grey 原文地址:ZooKeeper学习笔记一:集群搭建 说明 单机版的zk安装和运行参考:https://zookeeper.apache.org/doc/r3.6.3/zookeeperS ...
- javaweb学习之Servlet开发(二)
javaweb学习总结(六)--Servlet开发(二) 一.ServletConfig讲解 1.1.配置Servlet初始化参数 在Servlet的配置文件web.xml中,可以使用一个或多个< ...
- Javaweb学习笔记——(二十三)——————AJAX、XStream、JSON
AJAX概述 1.什么是AJAX ajax(Asynchronous JavaScript and xml) 翻译成中文就是"异步JavaScript和xml&quo ...
随机推荐
- iOS开发:UILabel无法响应点击事件的问题
UILabel 是默认关闭用户的交互的 即: _contentLabel.userInteractionEnabled = NO; 修改之后: _contentLabel.userInteractio ...
- 改变VC生成exe图标
默认 VC 生成的 EXE 文件的图标很大众,可以根据以下办法修改 exe 的图标. 以 Visual C++ 6.0 为例: 1. 创建项目,添加代码,并且保证项目可以正常编译. 2. 为项目增加资 ...
- 这样就算会了PHP么?-7
循环之类的例子 <script language="javascript"> function calculate(a, b) { return a * b; } do ...
- 从点击Button到弹出一个MessageBox, 背后发生了什么(每个UI线程都有一个ThreadInfo结构, 里面包含4个队列和一些标志位)
思考一个最简单的程序行为:我们的Dialog上有一个Button, 当用户用鼠标点击这个Button时, 我们弹出一个MessageBox. 这个看似简单的行为, 谁能说清楚它是如何运行起来的,背 ...
- Java中一些常用的代码
总结一下最近程序中用到的代码吧,大部分不是自己写的,放到这里,备份一下,以后忘记了来看一下: //正则表达式验证手机号 public static void phoneTest(String phon ...
- Delphi流的操作 转
一.流的概念 流简单说是建立在面向对象基础上的一种抽象的处理数据的工具,它定义了一些处理数据的基本操作,如读取数据,写入数据等,程序员只需掌握对流进行操作,而不用关心流的另一头数据的真正流向.其实,流 ...
- Windows 8.1下使用IE 64位
Internet Options -> Advanced -> Settings Security组 对Enable 64-bit processes for Enhanced Prote ...
- 什么是 docker?
关于 Docker 是什么,有个著名的隐喻:集装箱.但是它却起了个“码头工人”( docker 的英文翻译)的名字.这无疑给使用者很多暗示:“快来用吧!用了 Docker ,就像世界出现了集装箱,这样 ...
- 运行tomcat7w.exe tomcat7.exe ,提示 指定的服务未安装 unable to open the service 'tomcat7'
运行tomcat7w.exe tomcat7.exe ,提示 指定的服务未安装 unable to open the service 'tomcat7'(用的是绿色的Tomcat7) 解决方法: 打开 ...
- Object-c学习之路十二(OC的copy)
oc中的拷贝分为:copy(浅拷贝)和mutablecopy(深拷贝). 浅拷贝也为指针拷贝,拷贝后原来的对象计数器会+1: 深拷贝为对象拷贝,原来的对象计数器不变. 注意:自定义对象拷贝时要实现NS ...