學jsp這麼長時間,做的項目也有七八個了,可所有的項目都是用戶登入就直接跳到其擁有權限的頁面,或者顯示可訪問頁面的連結。使用這種方式來幼稚地控制存取權限。從來沒有想過如果我沒有登錄,直接輸入地址也可以直接訪問用戶的頁面的。
在jsp中權限的控制是透過Filter過濾器來實現的,所有的開發框架中都整合有Filter,如果不適用開發框架則有以下實作方法:
LoginFilter.java
複製代碼代碼如下:
public class LoginFilter implements Filter {
private String permitUrls[] = null;
private String gotoUrl = null;
public void destroy() {
// TODO Auto-generated method stub
permitUrls = null;
gotoUrl = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest res=(HttpServletRequest) request;
HttpServletResponse resp=(HttpServletResponse)response;
if(!isPermitUrl(request)){
if(filterCurrUrl(request)){
System.out.println("--->請登入");
resp.sendRedirect(res.getContextPath()+gotoUrl);
return;
}
}
System.out.println("--->允許存取");
chain.doFilter(request, response);
}
public boolean filterCurrUrl(ServletRequest request){
boolean filter=false;
HttpServletRequest res=(HttpServletRequest) request;
User user =(User) res.getSession().getAttribute("user");
if(null==user)
filter=true;
return filter;
}
public boolean isPermitUrl(ServletRequest request) {
boolean isPermit = false;
String currentUrl = currentUrl(request);
if (permitUrls != null && permitUrls.length > 0) {
for (int i = 0; i < permitUrls.length; i++) {
if (permitUrls[i].equals(currentUrl)) {
isPermit = true;
break;
}
}
}
return isPermit;
}
//請求位址
public String currentUrl(ServletRequest request) {
HttpServletRequest res = (HttpServletRequest) request;
String task = request.getParameter("task");
String path = res.getContextPath();
String uri = res.getRequestURI();
if (task != null) {// uri格式xx/ser
uri = uri.substring(path.length(), uri.length()) + "?" + "task="
+ task;
} else {
uri = uri.substring(path.length(), uri.length());
}
System.out.println("目前請求位址:" + uri);
return uri;
}
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
String permitUrls = filterConfig.getInitParameter("permitUrls");
String gotoUrl = filterConfig.getInitParameter("gotoUrl");
this.gotoUrl = gotoUrl;
if (permitUrls != null && permitUrls.length() > 0) {
this.permitUrls = permitUrls.split(",");
}
}
}
Web.xml
複製代碼代碼如下:
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>filter.LoginFilter</filter-class>
<init-param>
<param-name>ignore</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>permitUrls</param-name>
<param-value>/,/servlet/Loginservlet?task=login,/public.jsp,/login.jsp</param-value>
</init-param>
<init-param>
<param-name>gotoUrl</param-name>
<param-value>/login.jsp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
這短代碼主要實現了使用者登入的過濾,權限過濾原理相同。只要要把判斷使用者是否登入換成是否有權限就可以了!