(七)Servlet過濾器

Servlet過濾器簡介javascript

過濾器經過Web部署描述符(web.xml)中XML標籤來聲明,這樣就能夠容許添加和刪除過濾器而無需改動如何應用代碼或JSP頁面。 它可以對Servlet容器的請求和響應對象進行檢查和修改,預防非法或 不合理的 請求和響應,即:css

  • 在客戶端的請求訪問後端資源以前,攔截這些請求。
  • 在服務器的響應發送回客戶端以前,處理這些響應。

Java中的Filter 並非一個標準的Servlet ,它不能處理用戶請求,也不能對客戶端生成響應。 主要用於對HttpServletRequest 進行預處理,也能夠對HttpServletResponse 進行後處理,是個典型的處理鏈。html

 

根據規範建議的各類類型的過濾器:java

  • 身份驗證過濾器(Authentication Filters)。
  • 數據壓縮過濾器(Data compression Filters)。
  • 加密過濾器(Encryption Filters)。
  • 觸發資源訪問事件過濾器。
  • 圖像轉換過濾器(Image Conversion Filters)。
  • 日誌記錄和審覈過濾器(Logging and Auditing Filters)。
  • MIME-TYPE 鏈過濾器(MIME-TYPE Chain Filters)。
  • 標記化過濾器(Tokenizing Filters)。
  • XSL/T 過濾器(XSL/T Filters),轉換 XML 內容。

 

Servlet 過濾器方法

一個執行過濾器的java類必須實現 javax.servlet.Filter 接口。javax.servlet.Filter 接口包含有三個方法:mysql

public void init(FilterConfig filterConfig)
初始化方法,web容器調用過濾器首先執行的方法。
public void doFilter (ServletRequest, ServletResponse, FilterChain)
該方法由 Web 容器調用,指示一個過濾器被放入服務。
public void destroy()
容器在銷燬過濾器實例前,doFilter()中全部活動都被該實例終止後,調用該方法

實例代碼:web

下面實現一個登陸過濾器sql

login.jsp後端

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>登陸頁面</title>
		<style>
			#form-groud{
				padding: 5px;
			}
			
			label{
				display:inline-block;
				padding: 5px;
				width: 5em;
				text-align: center;
			}
			
			input{
				padding: 5px;
			}
			
			#submit{
				display:inline-block;
				width: 10em;
				margin: 0 5em;
			}
		</style>
	</head>
	<body>
		<%
			//String loginerror = session.getAttribute("loginerror");
			if(session.getAttribute("loginerror") == "0"){
				out.println("<script type='text/javascript'>alert('登陸失敗!!!');</script>");
				session.removeAttribute("loginerror");
			} else if(session.getAttribute("loginerror") == "1"){
				out.println("<script type='text/javascript'>alert('您尚未登陸!!!');</script>");
			}
		%>
		<form action="login" method="post">
			<div id="form-groud">
				<label for="userName">用戶名:</label>
				<input type="text" name="userName" id="userName"/>
			</div>
			<div id="form-groud">
				<label for="password">密碼:</label>
				<input type="password" name="password" id="password"/>
			</div>
			<div id="form-groud">
				<input type="submit" name="submit" value="登陸" id="submit"/>
			</div>	
		</form>
	</body>
</html>

login.java服務器

package cn.iborder.admin;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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 javax.servlet.http.HttpSession;
import cn.iborder.util.Dbutil;
import cn.iborder.util.MD5Util;
/**
 * Servlet implementation class Login
 */
@WebServlet("/login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        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
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		String dbUrl = "jdbc:mysql://localhost:3306/test";
		String dbUser = "root";
		String dbPassword = "root";
		String userName = request.getParameter("userName");
		String password = null;
		try {
			password = MD5Util.md5Encode(request.getParameter("password"));
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		System.out.println("username : "+userName);
		System.out.println("password : "+password);
		System.out.println("=======================");
		
		Connection connection = new Dbutil(dbUrl, dbUser, dbPassword).getConn();
		PreparedStatement statement=null;
		ResultSet rs=null;
		HttpSession session = request.getSession();
		try {
			String sql = "select * from user where username=? and password=?";
			statement = connection.prepareStatement(sql);
			statement.setString(1, userName);
			statement.setString(2, password);
			
			rs = statement.executeQuery();
			if(!rs.next()){
				System.out.println("登陸失敗");
				System.out.println("=======================");
				session.setAttribute("loginerror", "0");
				response.sendRedirect("login.jsp");
			} else{
				System.out.println("登陸成功");
				rs.beforeFirst();
				while (rs.next()) {
					System.out.println(rs.getString("username"));
					System.out.println(rs.getString("password"));
				}
				System.out.println("=======================");
				session.setAttribute("username", userName);				
				response.sendRedirect("main.jsp");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("建立Statement對象失敗");
			System.out.println(e.getMessage());
			//System.out.println(e.getSQLState());
			System.out.println("=======================");
		} catch (NullPointerException e) {
			// TODO: handle exception
			System.out.println("空指針異常");
			System.out.println(e.getMessage());
			System.out.println("=======================");
		}finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (statement != null) {
					statement.close();
				}
				if (connection != null) {
					connection.close();
				}				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	/**
	 * @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);
	}
}

main.jspsession

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>用戶管理</title>
		<style type="text/css">
			input {
				padding: 5px;
			}
		</style>
	</head>
	<body>
		<p>歡迎回來 <%=session.getAttribute("username") %></p>
		<div>
			<form action="logout" method="post">
				<input type="submit" name="logout" id="logout" value="退出登陸"/>
			</form>			
		</div>
	</body>
</html>

logout.java

package cn.iborder.admin;
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;
import javax.servlet.http.HttpSession;
/**
 * Servlet implementation class Logout
 */
@WebServlet("/logout")
public class Logout extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Logout() {
        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
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();
		
		session.removeAttribute("username");
		out.println("退出登陸成功。。。<br/>");
		out.println("即將跳轉到登陸界面。。。<br/>");
		out.println("<script type='text/javascript'>setTimeout(window.location.href = '/prj8-3/login.jsp', 15000);</script>");
	}
	/**
	 * @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);
	}
}

loginfilter.java

package cn.iborder.filter;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * Servlet Filter implementation class loginfilter
 */
@WebFilter(filterName="loginfilter",urlPatterns="/main.jsp")
public class loginfilter implements Filter {
    /**
     * Default constructor. 
     */
    public loginfilter() {
        // TODO Auto-generated constructor stub
    }
	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}
	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		System.out.println("-----------------filter-----------------");
		HttpServletRequest newRequest = (HttpServletRequest) request;
		HttpServletResponse newResponse = (HttpServletResponse) response;
		HttpSession session = newRequest.getSession();
		System.out.println(session.getAttribute("username"));
		if(session.getAttribute("username") != null){
			chain.doFilter(request, response);
		} else {
			session.setAttribute("loginerror", "1");
			newResponse.sendRedirect("login.jsp");
		}
		// pass the request along the filter chain	
	}
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
}
相關文章
相關標籤/搜索