我們經常會碰到這樣的情況,當我們有事情離開了一會,等再回來繼續我們在網頁中的操作時,會出現session超時的錯誤,然後跟上一堆的錯誤,讓用戶感覺很不爽,像這種情況如果能在一個錯誤頁面給個Session超時的提示就會比較友好些,再一種情況,當一個系統中的用戶角色有多個,有些頁面對於一些級別低的用戶來說是沒有權限觀看的,可能在頁面上能根據不同的權限屏蔽了一些鏈接讓低級別的用戶無法進入,但是這隻能讓低級別的用戶看不見高級操作的鏈接,假如用戶知道鏈接的地址直接在地址欄中輸入鏈接,豈不是也可以進入系統啊,要解決這兩個問題就得在頁面中做判斷了。
If(session == null) {
//如果是超時則跳轉到登陸頁面重新登陸
}
If(checkAuthority() == false) {
//如果權限不足則跳轉到錯誤頁面給個提示
}
每個.jsp頁面中加上以上的判斷貌似能夠解決問題,然而一個系統往往有成百上千的jsp頁面,倘若每個頁面都這樣加豈不是很費事,而且如果將來的權限判斷髮生變化,將要維護所有的jsp這樣的工作量是很大的,靈活性很差,要是在進入這些jsp之前必須統一經過一個地方,在這個地方來做判斷貌似要好一下,我們使用了過濾器來解決了這個問題
新建一個過濾器命名爲:FilterDemo,該類繼承自:javax.servlet.Filter
public class FilterDemo implements Filter{
publicvoid destroy() {}
publicvoid doFilter(ServletRequest sreq, ServletResponse response,
FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)sreq;
HttpSession session = request.getSession(false);
if(session == null) {
//如果是session超時,在此處做處理
}
if(request.getRequestURI().endsWith("download.do")) {
//此處可以針對不同的請求根據用戶是否具有權限來做處理
}
request.getRequestDispatcher("/Error.jsp").
forward(request,response);
}
publicvoid init(FilterConfig filterConfig)
throws ServletException {}
}
然後將新建的Filter添加到web.xml中,部署Filter需要添加兩部分:
1.filter元素
filter元素位於部署描述符文件(web.xml)的前部,所有filter-mapping、servlet或servlet-mapping元素之前。
<filter>
<filter-name>SessionFilter</filter-name>
<filter-class>myPackage.FilterDemo</filter-class>
</filter>
2.filter-mapping元素
filter-mapping元素位於web.xml文件中filter元素之後serlvet元素之前
<filter-mapping>
<filter-name>SessionFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
以上內容表示所以的請求中以.do結尾的都有首先通過我們這裏指定的過濾器:
新建一個Servlet來測試:
publicclass DownLoadDemo extends HttpServlet {
privatestaticfinallongserialVersionUID = 1L;
public DownLoadDemo() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/DownLoadExcel.jsp").
forward(request, response);
}
}
在web.xml中部署好該servlet
<servlet>
<servlet-name>DownLoadDemo</servlet-name>
<servlet-class>com.sinosoft.base.sessiondemo.DownLoadDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownLoadDemo</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
新建jsp來測試
Index.jsp
<body>
<form action="download.do">
<h1>This is a Demo Application</h1>
<a href = 'DownLoadExcel.jsp'>導出Excel</a>
<input type='submit'>
</form>
</body>
爲了便於對比我們使用了一個是超鏈接的形式,一個是通過servlet來跳轉,當點擊提交按鈕時會被攔截,而直接點擊超鏈接就不會被攔截,因爲我們的Filter中配置的是攔截.do形式的,如果要攔截jsp也可以使用<url-pattern>DownLoadExcel.jsp </url-pattern>
再添加一個錯誤頁面Error.jsp
<body>
<h1>對不起,你沒有權限</h1>
</body>