package com.huawei.filter;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.huawei.po.Users;
public class LoginFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
/**
* 如果请求是登录过的 那就 直接通过 不然就跳转到登录页面
*/
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
//得到session 判断session中是否有用户
HttpSession session = req.getSession();
String uri = req.getRequestURI();
Object users = session.getAttribute("admin");
//登录过的
if(users!=null && users instanceof Users){
chain.doFilter(request, response);
}else{
if(uri.endsWith("login.jsp") || uri.endsWith("loginController") || uri.endsWith(".css") || uri.endsWith(".js") || uri.endsWith(".jpg") || uri.endsWith("image.jsp")){
chain.doFilter(request, response);
}else{
resp.sendRedirect(req.getContextPath()+"/views/login.jsp");
}
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
login.jsp
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
后台管理 | 登录body{
background-image: url('assets/images/bg1.jpg')
}
.login-form{
margin: 0 auto;
margin-top:200px;
max-width: 300px !important;
}
.login-form label{
color:#fff;
}
.valicode:hover{
cursor: pointer;
}
用户名
密 码
验证码
记住密码
登 录
×
${msg }
function change(_dom){
_dom.src="views/image.jsp?d="+new Date().getTime();
}
LoginController.java
package com.huawei.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.huawei.dao.UsersDAO;
import com.huawei.po.Users;
import com.huawei.service.UsersService;
import com.huawei.utils.EncoderUtil;
/**
* Servlet implementation class LoginController
*/
public class LoginController extends HttpServlet {
private static final long serialVersionUID = 1L;
//private Database database = Database.getDatabase();
//private UsersDAO usersDAO = new UsersDAO();
private UsersService usersService = new UsersService();
/**
* @see HttpServlet#HttpServlet()
*/
public LoginController() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//处理登录请求
//获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
String valicode = request.getParameter("valicode");
//得到状态
String remember = request.getParameter("remember");
if(request.getSession().getAttribute("rand").toString().equalsIgnoreCase(valicode)){
//用户名不能为空
if(username!=null && username.trim()!=""){
//得到一个用户
//User u = (User) this.database.get(username);
//User u = this.usersDAO.findByUsernameAndPassword(username, password);
Users u = this.usersService.findByUsername(username);
if(u!=null && u.getPassword().equals(EncoderUtil.MD5.encode(password))){
//if(u!=null){
//处理成功的情况
HttpSession session = request.getSession();
session.setAttribute("admin", u);
//操作cookie 设置cookie的时候 remember = username:password:state
Cookie []cookies = request.getCookies();
//只是为了找到我要的cookie
Cookie cookie = null;
if(cookies!=null && cookies.length>0){
for(Cookie c:cookies){
if(c.getName().equals("remember")){
cookie = c;
break;
}
}
}
if("remember".equals(remember)){
//处理有cookie和没有cookie的情况
/*if(cookie!=null){
}else{
}*/
cookie = new Cookie("remember", username+":"+password);
cookie.setMaxAge(60*60*24*7);
cookie.setPath(request.getContextPath());
response.addCookie(cookie);
}else{
if(cookie!=null){
cookie.setMaxAge(0);
cookie.setPath(request.getContextPath());
response.addCookie(cookie);
}
}
response.sendRedirect("../users/usersController?_method=findAll");
return ;
}
}
request.setAttribute("msg", "用户名或密码错误,请重试!");
}else{
request.setAttribute("msg", "验证码错误,请重试!");
}
request.setAttribute("username", username);
request.setAttribute("password", password);
request.setAttribute("remember", remember);
request.getRequestDispatcher("/views/login.jsp").forward(request, response);
return ;
}
}
image.jsp(生成验证码)
Color getRandColor(int fc, int bc) {//给定范围获得随机颜色
Random random = new Random();
if (fc > 255) fc = 255;
if (bc > 255) bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
%>
out.clear();
//设置页面不缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 在内存中创建图象
int width = 70, height = 30;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
//生成随机类
Random random = new Random();
// 设定背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
//设定字体
g.setFont(new Font("宋体", Font.PLAIN, 18));
//g.setFont(new Font("Tahoma",Font.PLAIN,18));
//URL url = new URL("http://127.0.0.1:8080/crm/resource/font/SIMSUN.TTC");
//InputStream is = url.openStream();
/* InputStream is = this.getClass().getClassLoader().getResourceAsStream("COURI.TTF");
System.out.println(is);
Font f = Font.createFont(Font.PLAIN, is); */
//f.deriveFont(30);
/* f.deriveFont(Font.PLAIN, 18);
is.close();
g.setFont(f); */
//画边框
g.setColor(Color.black);
g.drawRect(0, 0, width - 1, height - 1);
// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
char[] cs = new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'A', 'B', 'M'};
// 取随机产生的认证码(4位数字)
String sRand = "";
for (int i = 0; i < 4; i++) {
char c = cs[random.nextInt(cs.length)];//[0,4)
String rand = new Character(c).toString();
sRand += rand;
// 将认证码显示到图象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
//g.drawString(rand, 13 * i + 6, 16);
g.drawString(rand, 13 * i + 6, 20);
}
// 将认证码存入session
session.setAttribute("rand", sRand); //这行代码使我们关注的重点
// 图象生效
g.dispose();
// 输出图象到页面
try {
ImageIO.write(image, "JPEG", response.getOutputStream());
} catch (Exception e) {
e.getMessage();
} finally {
//解决以调用错误
out = pageContext.pushBody();
}
%>