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

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

<title>后台管理 | 登录</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<link href="assets/css/bootstrap.min.css" rel="stylesheet">

<style type="text/css">
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;
}
</style>
</head>

<body>

<div class="container">

<form class="form-horizontal login-form" action="login/loginController" method="post">

<div class="form-group">
<label class="control-label col-sm-3 text-right">用户名</label>
<div class="col-sm-9">
<input type="text" name="username" class="form-control" placeholder="用户名" value="${username }">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3 text-right">密 码</label>
<div class="col-sm-9">
<input type="password" name="password" class="form-control" placeholder="密码" value="${password }">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3 text-right">验证码</label>
<div class="col-sm-9">
<div class="input-group">
<input type="text" name="valicode" class="form-control" placeholder="验证码">
<div class="input-group-addon" style="padding:0 2px;">
<img src="views/image.jsp" class="valicode" alt="看不清?换一张!" title="看不清?换一张!" onclick="change(this)"/>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox" name="remember" value="remember" ${remember =='remember'?'checked="checked"':'' }> 记住密码
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button class="btn btn-default" type="submit">登 录</button>
</div>
</div>
<c:if test="${!empty msg }">
<div class="alert alert-danger alert-dismissible fade in">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
${msg }
</div>
</c:if>
</form>
</div>
</body>
<script type="text/javascript" src="assets/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="assets/js/bootstrap.min.js"></script>
<script type="text/javascript">
function change(_dom){
_dom.src="views/image.jsp?d="+new Date().getTime();
}
</script>
</html>

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(生成验证码)

<%@page import="java.net.URL" %>
<%@page import="java.io.InputStream" %>
<%@ page language="java" import="java.util.*" pageEncoding="gbk" %>
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
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();

}
%>

验证码及密码加密在java中使用的更多相关文章

  1. 凯撒密码加密解密--JAVA实现(基础)

    凯撒密码一种代换密码,据说凯撒是率先使用加密函的古代将领之一,因此这种加密方法被称为恺撒密码.凯撒密码的基本思想是:通过把字母移动一定的位数来实现加密和解密.明文中的所有字母都在字母表上向后(或向前) ...

  2. 如果你的application.properties中还存在明文密码----加密Spring Boot中的application.properties

    1 概述 什么?都2020年了还在Spring Boot的配置文件中写明文密码? 虽然是小项目,明文也没人看. 明文简单快捷方便啊!!! 你看直接用户名root密码123456多么简单!!! ... ...

  3. 三重DEC加密在java中的实现

    代码可以直接拷走使用,一些约定例如向量可以自行变动 引言      如今手机app五彩缤纷,确保手机用户的数据安全是开发人员必须掌握的技巧,下面通过实例介绍DES在android.ios.java平台 ...

  4. DES加密解密 Java中运用

    DES全称Data Encryption Standard,是一种使用密匙加密的块算法.现在认为是一种不安全的加密算法,因为现在已经有用穷举法攻破DES密码的报道了.尽管如此,该加密算法还是运用非常普 ...

  5. AES加密解密 Java中运用

    AES全称 Advanced Encryption Standard, 高级加密算法,更加安全,可取代DES. Aes: package com.blog.d201706.encrypt; impor ...

  6. glassfish配置中数据库密码加密方法

    glassfish配置中数据库密码加密方法 Glassfish中的数据库连接池需要使用密文保存数据库密码.如果不是,则可按如下方法可配置 通过Glassfish中的Alias实现,配置方法如下: 1. ...

  7. java工具类学习,系统中用户密码加密总结

    现在项目,用户注册登录部分很少有涉及到了,原因:现在热门开发框架都已经在底层帮我们做了一套用户注册,密码加密,登录认证,权限控制,缓存数据等基本功能. 这有利于项目的快速完成,只需要搬砖码畜们专注于业 ...

  8. Java中常用的加密方法(JDK)

    加密,是以某种特殊的算法改变原有的信息数据,使得未授权的用户即使获得了已加密的信息,但因不知解密的方法,仍然无法了解信息的内容.大体上分为双向加密和单向加密,而双向加密又分为对称加密和非对称加密(有些 ...

  9. [转载] Java中常用的加密方法

    转载自http://www.iteye.com/topic/1122076/ 加密,是以某种特殊的算法改变原有的信息数据,使得未授权的用户即使获得了已加密的信息,但因不知解密的方法,仍然无法了解信息的 ...

随机推荐

  1. Python学习-类

    类是对象的模板或蓝图,类是对象的抽象化,对象是类的实例化 在python中,一个对象的特征也称为属性(attribute),它所具有的的行为也称为方法(method) 对象 = 属性(特征)+方法(行 ...

  2. linux压缩打包等

    删除 rm -rf 目录 tar -zcvf /home/xahot.tar.gz /xahot tar -zcvf 打包后生成的文件名全路径 要打包的目录 例子:把/xahot文件夹打包后生成一个/ ...

  3. 重温CLR(十六) CLR寄宿和AppDomain

    寄宿(hosting)使任何应用程序都能利用clr的功能.特别要指出的是,它使现有应用程序至少能部分使用托管代码编写.另外,寄宿还为应用程序提供了通过编程来进行自定义和扩展的能力. 允许可扩展性意味着 ...

  4. spring--集合注入(常规方法)

    数据,list,set,map,Properties 集合注入 package Spring_collections; /** * Created by luozhitao on 2017/8/11. ...

  5. fabio 安装试用&&实际使用的几个问题

    备注:    因为fabio 依赖consul vault (不是强需),启动之前需要先安装consul,    本次为了简单consul 使用的是单机,使用的是dev 模式   1. conusl ...

  6. guaua学习,工具专题

    Preconditions 1,http://www.cnblogs.com/peida/p/Guava_Preconditions.html 1 .checkArgument(boolean) : ...

  7. BZOJ4974:[lydsy1708月赛]字符串大师

    浅谈\(KMP\):https://www.cnblogs.com/AKMer/p/10438148.html 题目传送门:https://lydsy.com/JudgeOnline/problem. ...

  8. xunsearch安装及环境检测(一)

    1.运行执行下载解压安装包wget http://www.xunsearch.com/download/xunsearch-full-latest.tar.bz2解压到指定目录 tar -xjf xu ...

  9. Socket客户端

    using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threa ...

  10. 安卓5.0宣告了ARM平台全面进入64位时代

    安卓5.0宣告了ARM平台全面进入64位时代 2014年10月份,安卓5.0正式版发布了,安卓5.0支持64位CPU,安卓5.0全面启用ART运行模式,在程序安装的时候,进行预编译,新的运行环境能够使 ...