JavaWeb学习笔记--Servlet代码集

时间:2021-10-21 13:11:12

目录:

 

登录系统
提交表单数据
打开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);
	}

  

============================================================

 

打开PDF
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);
	}

  

============================================================

 

URL传递参数

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

 

============================================================

 

URL重写跟踪会话

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);
	}
}

  

============================================================

 

使用HttpSession对象跟踪会话

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);
	}
}
JavaWeb学习笔记--Servlet代码集

 

============================================================

 

Servlet间协作

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>

JavaWeb学习笔记--Servlet代码集

 

JavaWeb学习笔记--Servlet代码集

 

============================================================

 

过滤器Filter

在上一部分的程序基础上加上

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代码集