web.xml配置文件
告知Tomcat当浏览器访问任意一个网站时,通过Protect过滤器进行过滤。
<filter>
<filter-name>Protect</filter-name>
<filter-class>com.filter.Protect</filter-class>
</filter>
<filter-mapping>
<filter-name>Protect</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
过滤器
通过request获取uri,判断资源文件是否与登录有关,与登录有关则放行;再判断用户是否拥有Session令牌,有则放行,无则显示登录失败。
package com.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class Protect implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
request.setCharacterEncoding("utf-8");
HttpSession session = request.getSession(false);
String uri = request.getRequestURI();
if (uri.contains("Login")||"/UserSystem/".equals(uri)||uri.contains("login")){
filterChain.doFilter(servletRequest,servletResponse);
return;
}
if (session!=null){
filterChain.doFilter(servletRequest,servletResponse);
}else {
request.getRequestDispatcher("/UserSystem/Login_error.html").forward(servletRequest,servletResponse);
}
}
}
用于登录的Servlet
通过调用UserDo类进行登录验证,当用户合法,给予用户一个Session令牌用于访问除登录界面外的其它资源文件。
package com.controller;
import com.Do.UserDo;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
String userName;
String passWord;
userName = request.getParameter("userName");
passWord = request.getParameter("passWord");
UserDo userDo = new UserDo();
int result = userDo.login(userName,passWord);
if (result==1){
request.getSession();
response.sendRedirect("/UserSystem/index.html");
}else {
response.sendRedirect("/UserSystem/Login_error.html");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
访问数据库判断用户名是否合法
public int login(String userName,String passWord){
int result = 0;
Jdbc jdbc = new Jdbc();
jdbc.GetConnection();
String sql = "select count(*) from user where UserName=? and Passwd=?";
PreparedStatement preparedStatement;
preparedStatement = jdbc.prepareStatement(sql);
try {
preparedStatement.setString(1,userName);
preparedStatement.setString(2,passWord);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
result = resultSet.getInt("count(*)");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
jdbc.Close();
}
return result;
}