过滤器[登录+编码]filter在程序中的使用
来源:互联网 发布:云计算产业园 编辑:程序博客网 时间:2024/05/19 18:14
虽然很久没有写WEB程序了,但依然怀念那些写WEB和日子。看了下以前的毕业设计,从中提取说一些小例子。写在这里。
这里讲解的是其中filter中使用。主要用于两个方面。一个是编码的设置和登录的拦截验证。
众所周知,java的乱码有时是个很头疼的问题。你不是不在每个页面定义一个编码,还得在每个servlet或action中定义编码。
通常见到这样的几行代码:
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
这对于一个庞大的系统来说,显得有点太多余。
我们要做一就是简化开发,提高效率。
<!--配置过滤器-->
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>com.tudou.projectmanage.filters.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<!--过滤处理访问/view/admin下所有资源的请求-->
<url-pattern>/view/admin/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>com.tudou.projectmanage.filters.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
上面定义两个过滤器,一个用于拦截登录[admin文件夹下为需要过滤的主界面,此处为管理后台页面,注:login.jsp等页面不在此列,如果你连login页面都过滤了,你还指望谁来登录你的网站呢。
<!--过滤处理访问/view/admin下所有资源的请求-->
<url-pattern>/view/admin/*</url-pattern>
一个用于处理编码
- <url-pattern>/*</url-pattern>
写一个过滤器,继承Filter即可。实现其中的doFilter方法。在其init方法初始化编码即可。这样一个编码的拦截器就实现了。
- package com.tudou.projectmanage.filters;
-
-
-
-
-
-
- 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.http.HttpServlet;
-
- @SuppressWarnings("serial")
- public class EncodingFilter extends HttpServlet implements Filter {
- FilterConfig config;
- private String encoding = null;
-
- public EncodingFilter() {
- }
-
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain filterChain) throws IOException, ServletException {
- if (encoding != null) {
- request.setCharacterEncoding(encoding);
- response.setContentType("text/html;charset="+encoding);
- }
- filterChain.doFilter(request, response);
- }
-
- public void init(FilterConfig config) throws ServletException {
- this.config = config;
- encoding = config.getInitParameter("encoding");
- }
-
- @Override
- public void destroy() {
- config = null;
- }
- }
同理登录拦截是一样的道理,只是处理方式略有不同。
package com.tudou.projectmanage.filters; 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.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.tudou.projectmanage.persist.Users; @SuppressWarnings("serial") public class LoginFilter extends HttpServlet implements Filter { FilterConfig config; public LoginFilter() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; HttpSession session = req.getSession(true); Users user = (Users) session.getAttribute("user"); if (user != null) { filterChain.doFilter(req, res); return; } else { req.setAttribute("title", "您还没有登录"); req.setAttribute("messages", "请先登录!"); req.setAttribute("page", "login.jsp"); ServletContext ctx = config.getServletContext(); ctx.getRequestDispatcher("/view/exceptions/error.jsp").forward(req, res); } } public void init(FilterConfig config) throws ServletException { this.config = config; } @Override public void destroy() { config = null; } }
如此一个登录拦截就完成了。
注:
此登录只过滤了../amdin文件夹下的资源。如果有人通过.do/.action/servlet的方式直接进行后台操作是拦截不到的。
此时,必须借助于拦截器进行URL拦截才能达到真正的完全拦截。一般用于权限控制。防止非法后台操作。
附上
error.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>提示</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <link rel="stylesheet" type="text/css" href="css/common.css"> <style type="text/css"> body { text-align: center; } #content { font-size: 15px; } </style> <script language="javascript"> var index = 5; var t; function timeStart() { document.getElementById("second").innerHTML = index; if (index <= 1) { var page = document.getElementById("page").value; if (page) { if (page == "login.jsp") { window.parent.location.href = "/projectManageSystem/login"; } else if (page == "index.jsp") { window.parent.location.href = "/projectManageSystem/index.jsp"; } else { if (page == "left.jsp") { parent.frames.leftFrame.location.reload(); window.location.href = "showmenu!showMenus.action?todo=0"; return; } window.location.href = page; } } else { history.go(-1); } clearTimeout(t); return; } index--; t = setTimeout("timeStart()", 1000); } function goTo() { var page = document.getElementById("page").value; if (page) { if (page == "login.jsp") { window.parent.location.href = "/projectManageSystem/login"; } else if (page == "index.jsp") { window.parent.location.href = "/projectManageSystem/index.jsp"; } else { if (page == "left.jsp") { parent.frames.leftFrame.location.reload(); window.location.href = "showmenu!showMenus.action?todo=0"; return; } window.location.href = page; } } else { history.go(-1); } } </script> </head> <body onload="timeStart()"> <script> history.go(1); </script> <DIV> <TABLE height="97%" cellSpacing=0 cellPadding=0 width="99%" border=0> <TBODY> <TR style="BACKGROUND-IMAGE: url(images/common/bg_header.gif); BACKGROUND-REPEAT: repeat-x" height=47> <TD width=10> <SPAN style="FLOAT: left; BACKGROUND-IMAGE: url(images/common/main_hl.gif); WIDTH: 15px; BACKGROUND-REPEAT: no-repeat; HEIGHT: 47px"></SPAN> </TD> <TD> <SPAN style="FLOAT: left; BACKGROUND-IMAGE: url(images/common/main_hl2.gif); WIDTH: 15px; BACKGROUND-REPEAT: no-repeat; HEIGHT: 47px"></SPAN><SPAN style="PADDING-RIGHT: 10px; PADDING-LEFT: 10px; FLOAT: left; BACKGROUND-IMAGE: url(images/common/main_hb.gif); PADDING-BOTTOM: 10px; COLOR: white; PADDING-TOP: 10px; BACKGROUND-REPEAT: repeat-x; HEIGHT: 47px; TEXT-ALIGN: center; 0 px: "> 提示界面 </SPAN> <SPAN style="FLOAT: left; BACKGROUND-IMAGE: url(images/common/main_hr.gif); WIDTH: 60px; BACKGROUND-REPEAT: no-repeat; HEIGHT: 47px"></SPAN> </TD> <TD style="BACKGROUND-POSITION: 50% bottom; BACKGROUND-IMAGE: url(images/common/main_rc.gif)" width=10></TD> </TR> <TR> <TD style="BACKGROUND-IMAGE: url(images/common/main_ls.gif)"> </TD> <TD style="COLOR: #566984; BACKGROUND-COLOR: white;" vAlign="middle" align="center"> <div id="content"> <div style="text-align: center; height: 12px;"> ${title} </div> <hr color="lightblue" size="1" /> <div align="center" style="height: 50px;"> <br /> ${messages} <span style="font-size: 15px; color: red;"><s:actionerror /> </span> <input type="hidden" id="page" value="${page}" /> <br /> <br /> <span style="font-size: 12px; color: gray;"> <label id="second" style="color: red;"></label> 秒后自动跳转,如果浏览器不支持跳转,请 <a href="javascript:void(0);" onclick="goTo();">点击这里</a> </span> </div> </div> </TD> <TD style="BACKGROUND-IMAGE: url(images/common/main_rs.gif)"></TD> </TR> <TR style="BACKGROUND-IMAGE: url(images/common/main_fs.gif); BACKGROUND-REPEAT: repeat-x" height=10> <TD style="BACKGROUND-IMAGE: url(images/common/main_lf.gif)"></TD> <TD style="BACKGROUND-IMAGE: url(images/common/main_fs.gif)"></TD> <TD style="BACKGROUND-IMAGE: url(images/common/main_rf.gif)"></TD> </TR> </TBODY> </TABLE> </DIV> </body> </html>