【Java学习20170427】Servlet过滤器和监听器

JavaWeb

Servlet过滤器和监听器

【Java学习20170427】Servlet过滤器和监听器_第1张图片【Java学习20170427】Servlet过滤器和监听器_第2张图片【Java学习20170427】Servlet过滤器和监听器_第3张图片【Java学习20170427】Servlet过滤器和监听器_第4张图片【Java学习20170427】Servlet过滤器和监听器_第5张图片【Java学习20170427】Servlet过滤器和监听器_第6张图片
【Java学习20170427】Servlet过滤器和监听器_第7张图片

package com.tx.demo2;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 统计过滤器
 */
public class CountFilter implements Filter {
	// 来访数量
	private int count;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 获取初始化参数
		String param = filterConfig.getInitParameter("count");
		// 将字符串转换为int
		count = Integer.valueOf(param);
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 访问数量自增
		count++;
		// 将ServletRequest转换成HttpServletRequest
		HttpServletRequest req = (HttpServletRequest) request;
		// 获取ServletContext
		ServletContext context = req.getSession().getServletContext();
		// 将来访数量值放入到ServletContext中
		context.setAttribute("count", count);
		// 向下传递过滤器
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
	}
}

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




人数统计


	

欢迎光临,
您是本站的第【 <%=application.getAttribute("count") %> 】位访客!




	FilerTest
	
		index.html
		index.htm
		index.jsp
		default.html
		default.htm
		default.jsp
	
	
	
		
		CountFilter
		
		com.tx.demo2.CountFilter
		
		
			
			count
			
			5000
		
	
	
	
		
		CountFilter
		
		/index.jsp
	


	



【Java学习20170427】Servlet过滤器和监听器_第8张图片 【Java学习20170427】Servlet过滤器和监听器_第9张图片
package com.tx.demo3;

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;

/**
 * 添加图书信息的Servlet
 */
public class AddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	// 处理GET请求
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	// 处理POST请求
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取 PrintWriter
		PrintWriter out = response.getWriter();
		// 获取图书编号
		String id = request.getParameter("id");
		// 获取名称
		String name = request.getParameter("name");
		// 获取作者
		String author = request.getParameter("author");
		// 获取价格
		String price = request.getParameter("price");
		// 输出图书信息
		out.print("

图书信息添加成功


"); out.print("图书编号:" + id + "
"); out.print("图书名称:" + name + "
"); out.print("作者:" + author + "
"); out.print("价格:" + price + "
"); // 刷新流 out.flush(); // 关闭流 out.close(); } }

package com.tx.demo3;

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;
// 字符编码过滤器
public class CharactorFilter implements Filter {
	// 字符编码
	String encoding = null;
	@Override
	public void destroy() {
		encoding = null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// 判断字符编码是否为空
		if(encoding != null){
			// 设置request的编码格式
			request.setCharacterEncoding(encoding);
			// 设置response字符编码
     		response.setContentType("text/html; charset="+encoding);
		}
		// 传递给下一过滤器
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 获取初始化参数
		encoding = filterConfig.getInitParameter("encoding");
	}

}

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




添加图书信息


	

添加图书信息

图书编号:
图书名称:
作  者:
价  格:



	FilerTest2
	
		index.html
		index.htm
		index.jsp
		default.html
		default.htm
		default.jsp
	
	
	
		
		CharactorFilter
		
		com.tx.demo3.CharactorFilter
		
		
			
			encoding
			
			UTF-8
		
	
	
	
		
		CharactorFilter
		
		/*
	
	
	
		
		AddServlet
		
		com.tx.demo3.AddServlet
	
	
	
		
		AddServlet
		
		/AddServlet
	
【Java学习20170427】Servlet过滤器和监听器_第10张图片 【Java学习20170427】Servlet过滤器和监听器_第11张图片
package com.tx.listener;

import java.util.*;

public class LoginList {
	private static LoginList user = new LoginList();
	private Vector vector = null;

	// private调用构造函数,
	// 防止被外界类调用产生新的instance对象
	private LoginList() {
		this.vector = new Vector();
	}

	// 外界使用的instance对象
	public static LoginList getInstance() {
		return user;
	}

	// 用户登录
	public boolean addLoginList(String user) {
		if (user != null) {
			this.vector.add(user);
			return true;
		} else {
			return false;
		}
	}

	// 获取用户列表
	public Vector getList() {
		return vector;
	}

	// 删除用户
	public void removeLoginList(String user) {
		if (user != null) {
			vector.removeElement(user);
		}
	}
}

package com.tx.listener;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

public class LoginNote implements HttpSessionBindingListener {
	private String user;
	private LoginList container = LoginList.getInstance();

	public LoginNote() {
		user = "";
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getUser() {
		return this.user;
	}

	public void valueBound(HttpSessionBindingEvent arg0) {
		System.out.println(this.user + "该用户己经上线");
	}

	public void valueUnbound(HttpSessionBindingEvent arg0) {
		System.out.println(this.user + "该用户己经下线");
		if (user != "") {
			container.removeLoginList(user);
		}
	}
}

【Java学习20170427】Servlet过滤器和监听器_第12张图片 【Java学习20170427】Servlet过滤器和监听器_第13张图片 【Java学习20170427】Servlet过滤器和监听器_第14张图片 【Java学习20170427】Servlet过滤器和监听器_第15张图片

文件上传

package com.share.putfile;

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

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

import org.apache.catalina.core.ApplicationPart;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
@MultipartConfig()
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String path = this.getServletContext().getRealPath("/");	//获取服务器地址
		Part p = request.getPart("file1");							//获取用户选择的上传文件	
		if (p.getContentType().contains("image")) {					// 仅处理上传的图像文件
			ApplicationPart ap = (ApplicationPart) p;
			System.out.println(ap.getHeaderNames());
			System.out.println(ap.getHeader("content-disposition"));
//			String fname1 = ap.getFilename();						//获取上传文件名
//			int path_idx = fname1.lastIndexOf("\\") + 1;			//对上传文件名进行截取
//			String fname2 = fname1.substring(path_idx, fname1.length());	
			
			String content = ap.getHeader("content-disposition");
			String fname1 = content.substring(content.lastIndexOf("\\")+1);
			fname1 = fname1.substring(0, fname1.length()-1);
			File file = new File(path + "/upload/" + fname1);
			p.write(file.getPath());					// 写入 web 项目根路径下的upload文件夹中
			out.write("文件上传成功");							
		}
		else{
			  out.write("请选择图片文件!!!");
		}
	}
}

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


 
选择文件
Filter 和Servlet实现用户角色验证1

package com.tx.control;

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.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

@WebFilter(value="/tx")
public class MyFile_1 implements Filter {

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

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		String people = request.getParameter("user");
		if("teacher".equals(people)){
			chain.doFilter(request, response);//放行
		}else{
			((HttpServletResponse)response).sendRedirect("/FilerWebTest3/error.html");
		}
	}

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

}


package com.tx.control;

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.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

@WebFilter(value="/tx/test.do")
public class MyFile_2 implements Filter{

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

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		String username = request.getParameter("username");
		if("tx".equals(username)){
			chain.doFilter(request, response);
		}else{
			((HttpServletResponse)response).sendRedirect("/FilerWebTest3/error.html");
		}
		
		
	}

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

}

package com.tx.control;

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

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

@WebServlet(value="/tx/test.do")
public class MyServlet extends HttpServlet{

	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// 设置request的编码
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		PrintWriter pw = response.getWriter();
		pw.println("账号:"+username+"密码:"+password);
		pw.flush();
		pw.close();
		
	}
	
}




Insert title here


	

用户名:
密码:






Insert title here


	没有访问权限


Filter 和Servlet实现用户权限角色验证

package com.tx.util;

import java.util.Hashtable;


public class Jurisdiction {
	/** 管理员*/
	private Hashtable administrator;
	/** 开发人员*/
	private Hashtable engineer;
	/** 游客*/
	private Hashtable visitor;
	
	private Hashtable people;
	
	//初始化代码块
	{
		administrator = new Hashtable();
		engineer = new Hashtable();
		visitor = new Hashtable();
		people = new Hashtable();
		init();
	}
	
	private static Jurisdiction j;
	
	static {
		j = new Jurisdiction();
	}
	
	public static Jurisdiction getnewInstance(){
		return j;
	}
	
	private Jurisdiction(){}
	
	/**
	 * 初始化
	 */
	public void init(){
		administrator.put("王二狗", "123465");
		engineer.put("帅哥", "123");
		visitor.put("user", "112233");
		people.putAll(administrator);
		people.putAll(engineer);
		people.putAll(visitor);
	}
	
	/**
	 * 检查权限等级
	 * @param username
	 * @return
	 */
	public int examine(String username){
		if(administrator.containsKey(username)){
			return 1;
		}else if(engineer.containsKey(username)){
			return 2;
		}else if(visitor.containsKey(username)){
			return 3;
		}else {
			return 4;
		}
	}



	public Hashtable getAdministrator() {
		return administrator;
	}



	public Hashtable getEngineer() {
		return engineer;
	}



	public Hashtable getVisitor() {
		return visitor;
	}



	public Hashtable getPeople() {
		return people;
	}
	
	
	
}


package com.tx.action;

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.annotation.WebFilter;


@WebFilter(value = "/*")
public class CharactorFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("DoFilter");
		// 设置request的编码格式
		request.setCharacterEncoding("UTF-8");
		// 设置response字符编码
		response.setContentType("text/html; charset=UTF-8");
		// 传递给下一过滤器
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void destroy() {

	}

}

package com.tx.action;

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.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

import com.tx.util.Jurisdiction;

@WebFilter(value = "/show.do")
public class MyFilter implements Filter {

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

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		Jurisdiction j = Jurisdiction.getnewInstance();
		String username = request.getParameter("user");
		String password = request.getParameter("password");
		switch (j.examine(username)) {
		case 1:
			if (j.getAdministrator().containsValue(password)) {
				request.getRequestDispatcher("WEB-INF/jsp/admin.jsp").forward(request, response);
			} else {
				request.getRequestDispatcher("WEB-INF/jsp/error.html").forward(request, response);
			}
			break;
		case 2:
			if (j.getEngineer().containsValue(password)) {
				request.getRequestDispatcher("WEB-INF/jsp/engineer.jsp").forward(request, response);
			} else {
				request.getRequestDispatcher("WEB-INF/jsp/error.html").forward(request, response);
			}
			break;
		case 3:
			if (j.getVisitor().containsValue(password)) {
				request.getRequestDispatcher("WEB-INF/jsp/visitor.jsp").forward(request, response);
			} else {
				request.getRequestDispatcher("WEB-INF/jsp/error.html").forward(request, response);
			}
			break;

		default:
			request.getRequestDispatcher("WEB-INF/jsp/warning.html").forward(request, response);
			break;
		}

	}

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

	}

}

package com.tx.action;

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

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

@WebServlet(value="/show.do")
public class MyServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req,resp);
	
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter pw = resp.getWriter();
		pw.println("逻辑出错");
		pw.flush();
		pw.close();
	}
	
}





Insert title here


		
欢迎来到XXX后台系统
账号:
密码:

以下文件放在WebRoot---WEB-INF(为了防止用户根据链接拼接接入)





Insert title here


	

无访问权限,请联系管理员






Insert title here


	

账号或密码错误


<%@page import="java.util.Map"%>
<%@page import="java.util.Set"%>
<%@page import="java.util.Hashtable"%>
<%@page import="com.tx.util.Jurisdiction"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>




Insert title here


	
		<%
			Jurisdiction j = Jurisdiction.getnewInstance();
			Hashtable admin = j.getPeople();
			Set> s = admin.entrySet();
			for (Map.Entry e : s) {
				out.println("");
				out.println("");
				out.println("");
			}
		%>
		
账号:" + e.getKey() + "密码:" + e.getValue() + "

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


	<%
		String name = request.getParameter("user");
		String password = request.getParameter("password");
	%>
	
账号:<%=name %>
密码:<%=password %>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


	<%
		String name = request.getParameter("user");
		String password = request.getParameter("password");
	%>
	
账号:<%=name %>
密码:<%=password %>


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