文章分类

相关文章

Java 使用Filter实现登录限制

分类:Java     发布:2018-12-20     来源:本站     浏览:104 次
1.选中项目,右键添加Filter

2.输入代码
package com.rc.filter;
import java.io.IOException;
import java.io.PrintWriter;

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;

@WebFilter(filterName = "loginFilter", urlPatterns = { "/*" })
public class LoginFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpSession session = req.getSession(true);
		resp.setContentType("text/html;");
		resp.setCharacterEncoding("utf-8");
		String request_uri = req.getRequestURI();
		String ctxPath = req.getContextPath();
		String uri = request_uri.substring(ctxPath.length()).toLowerCase();
		if (uri.endsWith(".js") || uri.endsWith(".css") ||  uri.endsWith(".ico")) {
			chain.doFilter(request, response);
		} else {
			if (uri.contains("login.jsp") || uri.contains("test.jsp") ||uri.contains("loginservlet") || uri.contains("imageservlet")) {
				chain.doFilter(request, response);
			} else {

				if (session.getAttribute("user") != null) {
					chain.doFilter(request, response);
				} else {
					resp.sendRedirect(req.getContextPath() + "/login.jsp");
					return;
				}
			}
		}
	}
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
3.在WEB-INF下的web.xml注册Filter
	<filter>
		<filter-name>RequestFilter</filter-name>
		<filter-class>com.rc.filter.RequestFilter</filter-class>
	</filter>


上一篇:Java 配置文件读写辅助类

下一篇:Java 在普通类中获取Session以及request对象