Servlet学习(个人笔记)

问:简述Servlet的生命周期?

在Servlet产生到消亡的过程中,有三个生命周期函数,初始化方法init(),处理客户请求的方法service(),终止方法destroy()。

另外,具体是以下过程

(1)加载和实例化

当Servlet容器启动或客户端发送一个请求时,Servlet容器会查找内存中是否存在该Servlet实例,若存在,则直接读取该实例响应请求;如果不存在,就创建一个Servlet实例。

(2) 初始化

实例化后,Servlet容器将调用Servlet的init()方法进行初始化(一些准备工作或资源预加载工作)。

(3)服务

初始化后,Servlet处于能响应请求的就绪状态。当接收到客户端请求时,调用service()的方法处理客户端请求,HttpServlet的service()方法会根据不同的请求 转调不同的doXxx()方法。

(4)销毁

当Servlet容器关闭时,Servlet实例也随时销毁。其间,Servlet容器会调用Servlet 的destroy()方法去判断该Servlet是否应当被释放(或回收资源)。
 

servlet文件下载

package com.mine;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

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

/**
 * Servlet implementation class Test
 * 实现文件下载
 */
@WebServlet("/Test")
public class Test extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public Test() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//得到文件路径
		String path = this.getServletContext().getRealPath("/pictures/中文文件.jpeg");
		//得到文件名(最后一个\之后的都是文件名)
		String filename = path.substring( path.lastIndexOf("\\")+1 );
		
		//英文文件名用这个
		//response.setHeader("content-disposition", "attachment;filename="+filename);
		
		//如果下载文件是中文文件名,则麻烦一点,需要url编码
		response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename, "UTF-8") );
		
		InputStream in = null;
		OutputStream out = null;
		
		in = new FileInputStream(path);
		int len = 0;
		byte buffer[] = new byte[1024];
		out = response.getOutputStream();
		while( (len = in.read(buffer) ) > 0 )
		{
			out.write(buffer,0,len);
		}
		in.close();
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 

3s刷新页面,并随机输出一个数

package com.mine;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Random;

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

/**
 * Servlet implementation class Test
 * 每隔3s刷新页面,随机输出一个数
 */
@WebServlet("/Test")
public class Test extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public Test() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setHeader("refresh", "3");
		String data = new Random().nextInt(100)+"";
		response.getOutputStream().write(data.getBytes());
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

实现跳转

package com.mine;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Random;

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

/**
 * Servlet implementation class Test
 * 实现页面跳转
 */
@WebServlet("/Test")
public class Test extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public Test() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//response.getOutputStream().write("你好".getBytes());
		deal(request, response);
		
	}

	private void deal(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//这里的编码问题没有解决,还是乱码,不知道为啥
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		//包含html语句的message
		String message ="clickhere跳转";
		this.getServletContext().setAttribute("message", message);
		this.getServletContext().getRequestDispatcher("/WEB-INF/message.jsp").forward(request, response);
	}
//其实还可以用request实现转发,代码如下
    private void test5(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String data = "yyeee";
		request.setAttribute("data", data);
		request.getRequestDispatcher("/message.jsp").forward(request, response);
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 

request学习代码

 

package com.mine;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

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

import org.apache.commons.beanutils.BeanUtils;

/**
 * 
 */
@WebServlet("/Test2")
public class Test2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Test2() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		 test3(request,response);
	}
	
	//通过HTML页面传递数据,HTML页面是test.html
	private void test3(HttpServletRequest request, HttpServletResponse response) {
		
		
		Enumeration names = request.getParameterNames();
		 while( names.hasMoreElements() )
		 {
			 String s = names.nextElement();
			 String value = request.getParameter(s);
			 System.out.println(s+" = "+value);
		 }
		 
		 System.out.println("-------获取数据的另一种方式---------------");
		
		 Map map = request.getParameterMap();
		 
	
		 User user = new User();
		 try {
			//从map中取出符合user属性的值,也就是,用户输入的用户名和密码可以很方便的存在ueser对象中
			BeanUtils.populate(user, map);
			
		} catch ( Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("name: "+user.getUsername()+" pass: "+user.getPassword() );
	
		
	}
	
	//获取头的相关方法
	private void test2(HttpServletRequest request, HttpServletResponse response) {
		//获取单个头
		String headValue = request.getHeader("Accept-Encoding");
		System.out.println(headValue);
		
		//获取所有叫这个名字的头
		Enumeration e = request.getHeaders("Accept-Encoding");
		while( e.hasMoreElements() )
		{
			String s = e.nextElement();
			System.out.println(s);
		}
		
		System.out.println("---------get all headers---------");
		//获取所有头
		Enumeration names = request.getHeaderNames();
		while( names.hasMoreElements() )
		{
			String name = names.nextElement();
			String s = request.getHeader(name);
			System.out.println(s);
		}
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
/*******************
其中,html文件如下


	
		
		带数据给Test2
	
	
		
		
用户名:
密码:
******************************/

 

Cookie实现浏览记录(最简陋版本)

主界面代码:

package com.mine;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Test
 */
@WebServlet("/NewTest")
public class NewTest extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public NewTest() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		Cookie t[] = request.getCookies();
//		for(  int i = 0 ; i < t.length ;i++ )
//			t[i].setMaxAge(0);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		//网站已有的商品
		List l = MyList.getAll();
		out.println("共有"+l.size()+"本书: "+"
"); for( Book book:l ) { //out.println(book.name+"
"); String name = book.getName(); out.println(" "+name +""+"
"); } //浏览过的商品 out.println("浏览过的:"); Cookie cookie[] = request.getCookies(); if( cookie == null ) { System.out.println("kong"); return; } out.println("cookie num: "+cookie.length+"
"); for( Cookie c:cookie ) { if( c.getName().equals("history") ) { if( c.getValue().equals("") ) { c.setMaxAge(0); System.out.println("remove"); break; } //System.out.println("history value: "+c.getValue() ); String names[] = c.getValue().split(","); for( String s:names ) out.print(s+"
"); break; } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } class MyList { static List l; static { l = new ArrayList(); l.add( new Book("Java","123") ); l.add( new Book("C","33") ); l.add( new Book("WEB","93") ); } static List getAll() { return l; } } class Book { String name,price; public Book() { super(); } public Book(String name, String price) { super(); this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } }

显示书籍界面,以及更新cookie

package com.mine;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Process
 */
@WebServlet("/Process")
public class Process extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Process() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		out.println("您要的书籍如下:
"); String name = request.getParameter("name"); Book b=null; for( Book book:MyList.l ) { if( book.name.equals(name) ) { b = book; break; } } out.println(b.getName()); out.println(b.getPrice()); //更新cookie Cookie cookie[] = request.getCookies(); boolean haveHistory = false; if( cookie != null ) for( Cookie c:cookie ) { if( c.getName().equals("history") ) { System.out.println("终于找到一个,值 "+c.getValue() ); haveHistory = true; ArrayList s = mySplit( c.getValue() ); //将split的数组装到ArrayList中 //List s = Arrays.asList(c.getValue().split(",")); //呜呜,其实可以这样写 if( s==null ) break; boolean in = false; for( String ss:s ) if( ss.equals(name) ) //浏览记录有这本书 { in = true; s.remove(name); break; } if( in ) //如果在记录里,加到最前面,表示最近浏览 s.add(0, name); else s.add(name); String value=""; for( String ss:s ) value = value.concat(ss+","); value = value.substring(0, value.length()-1); Cookie newCookie = new Cookie("history",value); newCookie.setMaxAge(30*24*60*60); //设置cookie时限为30天 newCookie.setPath("/CookieSession"); response.addCookie(newCookie); break; } } else //没有历史记录,就没有这个cookie { Cookie newCookie = new Cookie("history", name); newCookie.setMaxAge(30*24*60*60); newCookie.setPath("/CookieSession"); response.addCookie(newCookie); } } static ArrayList mySplit( String s ) { String temp[] = s.split(","); ArrayList ans = new ArrayList(); for( String ss:temp ) ans.add(ss); return ans; } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

 

 

 

 

你可能感兴趣的:(Java学习,Servlet)