- <?xml version="1.0" encoding="GBK"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
- metadata-complete="true" version="3.0">
- <display-name>魔兽世界</display-name>
- <welcome-file-list>
- <welcome-file>index.html</welcome-file>
- </welcome-file-list>
- <servlet>
- <servlet-name>login</servlet-name>
- <servlet-class>servlet.LoginServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>login</servlet-name>
- <url-pattern>/login</url-pattern>
- </servlet-mapping>
- <!-- 定义Filter -->
- <filter>
- <filter-name>authority</filter-name>
- <filter-class>filter.AuthorityFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>GBK</param-value>
- </init-param>
- <init-param>
- <param-name>loginPage</param-name>
- <param-value>/login</param-value>
- </init-param>
- <init-param>
- <param-name>ignoreTypes</param-name>
- <param-value>css</param-value>
- </init-param>
- <init-param>
- <param-name>proLogin</param-name>
- <param-value>/proLogin</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>authority</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
- package filter;
- import java.io.IOException;
- import java.net.URLEncoder;
- 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.annotation.WebFilter;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- /**
- * Servlet Filter implementation class AuthorityFilter
- */
- @WebFilter("/AuthorityFilter")
- public class AuthorityFilter implements Filter
- {
- private FilterConfig config;
- private String encoding;
- private String loginPage;
- private String ignoreType;
- /**
- * Default constructor.
- */
- public AuthorityFilter()
- {
- // TODO Auto-generated constructor stub
- }
- /**
- * @see Filter#destroy()
- */
- public void destroy()
- {
- config = null;
- }
- /**
- * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
- */
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException
- {
- long before = System.currentTimeMillis();
- System.out.println("/*******************/\nAuthorityFilter开始过滤...");
- HttpServletRequest hrequest = (HttpServletRequest) request;
- String requestPath = hrequest.getServletPath(); // 这里是不包含?以及?后面的字符串的
- System.out.println("AuthorityFilter截获到用户请求的地址:"
- + hrequest.getServletPath());
- // 设定编码
- request.setCharacterEncoding(encoding);
- // 是否是要忽略的类型
- if (requestPath.endsWith(ignoreType))
- {
- chain.doFilter(request, response);
- } else
- {
- HttpSession session = hrequest.getSession();
- if (session.getAttribute("user") == null
- && !requestPath.endsWith(loginPage))
- {
- HttpServletResponse res = (HttpServletResponse) response;
- String ReturnUrl = URLEncoder.encode(config.getServletContext().getContextPath() + requestPath,"GBK");
- res.sendRedirect(config.getServletContext().getContextPath()
- + loginPage + "?ReturnUrl=" + ReturnUrl);
- //res.sendRedirect("http://www.baidu.com");
- System.out.println("AuthorityFilter已经把页面重定向到登录页面");
- } else
- {
- chain.doFilter(request, response);
- System.out.println("AuthorityFilter过滤结束");
- System.out.println("请求被AuthorityFilter定位到"
- + hrequest.getRequestURI());
- }
- }
- long after = System.currentTimeMillis();
- System.out.println("AuthorityFilter所花时间为:" + (after - before)
- + "\n/*******************/");
- }
- /**
- * @see Filter#init(FilterConfig)
- */
- public void init(FilterConfig fConfig) throws ServletException
- {
- this.config = fConfig;
- encoding = config.getInitParameter("encoding");
- loginPage = config.getInitParameter("loginPage");
- ignoreType = config.getInitParameter("ignoreTypes");
- }
- }
3 修改LoginServlet.java
- package servlet;
- import java.io.IOException;
- import java.net.URLDecoder;
- import java.sql.ResultSet;
- import javax.servlet.RequestDispatcher;
- 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 dao.DbDao;
- /**
- * Servlet implementation class LoginServlet
- */
- @WebServlet(description = "登录控制器", urlPatterns = { "/login" })
- // 如果在web.xml中配置了,在Annotation中的配置就不会有效果
- public class LoginServlet extends HttpServlet
- {
- private static final long serialVersionUID = 1L;
- /**
- * @see HttpServlet#HttpServlet()
- */
- public LoginServlet()
- {
- super();
- // TODO Auto-generated constructor stub
- }
- /**
- * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void service(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException
- {
- System.out.println("LoginServlet开始处理用户登录请求:" + request.getRequestURI());
- String errMsg = "";
- HttpSession session = request.getSession(true);
- RequestDispatcher rd;
- String username = request.getParameter("username");
- String pass = request.getParameter("pass");
- String returnUrl = null;
- String rawQueryString = request.getQueryString();
- if (rawQueryString != null)
- {
- System.out.println("带有参数" + rawQueryString);
- try
- {
- String queryString = URLDecoder.decode(rawQueryString, "GBK");
- String[] paramPairs = queryString.split("&");
- String[] nameValue = paramPairs[0].split("=");
- if (nameValue[0].equalsIgnoreCase("ReturnUrl"))
- {
- returnUrl = nameValue[1];
- }
- } catch (Exception e)
- {
- e.printStackTrace();
- returnUrl = null;
- }
- }
- if (returnUrl != null)
- {
- session.setAttribute("returnUrl", returnUrl);
- }
- if (username != null)
- {
- try
- {
- DbDao dd = new DbDao("oracle.jdbc.driver.OracleDriver",
- "jdbc:oracle:thin:localhost:1521:orcl", "system",
- "abc123");
- ResultSet rs = dd.query("select pass from user_table "
- + "where name=?", username);
- if (rs.next())
- {
- if (rs.getString("pass").equals(pass))
- {
- session.setAttribute("user", username);
- String reUrl = (String) session.getAttribute("returnUrl");
- if (session.getAttribute("returnUrl") == null)
- {
- System.out.println("登录成功,跳到欢迎页面");
- ((HttpServletResponse) response)
- .sendRedirect(getServletContext()
- .getContextPath() + "/welcome.jsp");
- } else
- {
- System.out.println("登录成功,返回之前的页面");
- ((HttpServletResponse) response)
- .sendRedirect(reUrl);
- }
- } else
- {
- errMsg += "您的用户名密码不符合,请重新输入";
- }
- } else
- {
- errMsg += "您的用户名不存在,请先注册";
- }
- } catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- if ((errMsg != null && !errMsg.equals("")) || username == null)
- {
- System.out.println("forward到login.jsp");
- rd = request.getRequestDispatcher("/login.jsp");
- request.setAttribute("err", errMsg);
- rd.forward(request, response);
- // (1)请求被redirect到/login?returnUrl...,让浏览器重新发送一个请求,这个请求为/login?returnUrl...
- // (2)浏览器发送这个请求,把地址刷新为/login?returnUrl...
- // (3)服务器记下returnUrl,把请求forword到login.jsp。login.jsp输出响应
- // (4)浏览器收到响应,渲染页面。地址栏还是login?returnUrl
- // (5)浏览器向服务器发送post请求,此时发的请求就是/login。
- // 浏览器的地址栏显示什么,是由浏览器根据它发送的请求决定的,此时它的请求是/login,所以它的地址栏就变成了/login
- }
- }
- }
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于