验证码及密码加密在java中使用
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">×</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中使用的更多相关文章
- 凯撒密码加密解密--JAVA实现(基础)
凯撒密码一种代换密码,据说凯撒是率先使用加密函的古代将领之一,因此这种加密方法被称为恺撒密码.凯撒密码的基本思想是:通过把字母移动一定的位数来实现加密和解密.明文中的所有字母都在字母表上向后(或向前) ...
- 如果你的application.properties中还存在明文密码----加密Spring Boot中的application.properties
1 概述 什么?都2020年了还在Spring Boot的配置文件中写明文密码? 虽然是小项目,明文也没人看. 明文简单快捷方便啊!!! 你看直接用户名root密码123456多么简单!!! ... ...
- 三重DEC加密在java中的实现
代码可以直接拷走使用,一些约定例如向量可以自行变动 引言 如今手机app五彩缤纷,确保手机用户的数据安全是开发人员必须掌握的技巧,下面通过实例介绍DES在android.ios.java平台 ...
- DES加密解密 Java中运用
DES全称Data Encryption Standard,是一种使用密匙加密的块算法.现在认为是一种不安全的加密算法,因为现在已经有用穷举法攻破DES密码的报道了.尽管如此,该加密算法还是运用非常普 ...
- AES加密解密 Java中运用
AES全称 Advanced Encryption Standard, 高级加密算法,更加安全,可取代DES. Aes: package com.blog.d201706.encrypt; impor ...
- glassfish配置中数据库密码加密方法
glassfish配置中数据库密码加密方法 Glassfish中的数据库连接池需要使用密文保存数据库密码.如果不是,则可按如下方法可配置 通过Glassfish中的Alias实现,配置方法如下: 1. ...
- java工具类学习,系统中用户密码加密总结
现在项目,用户注册登录部分很少有涉及到了,原因:现在热门开发框架都已经在底层帮我们做了一套用户注册,密码加密,登录认证,权限控制,缓存数据等基本功能. 这有利于项目的快速完成,只需要搬砖码畜们专注于业 ...
- Java中常用的加密方法(JDK)
加密,是以某种特殊的算法改变原有的信息数据,使得未授权的用户即使获得了已加密的信息,但因不知解密的方法,仍然无法了解信息的内容.大体上分为双向加密和单向加密,而双向加密又分为对称加密和非对称加密(有些 ...
- [转载] Java中常用的加密方法
转载自http://www.iteye.com/topic/1122076/ 加密,是以某种特殊的算法改变原有的信息数据,使得未授权的用户即使获得了已加密的信息,但因不知解密的方法,仍然无法了解信息的 ...
随机推荐
- idea Java spring 入门 demo
根据这个 来实现 理解 https://www.cnblogs.com/xing901022/p/3963962.html 这里没有说如何导入包,现在我们用 idea 来实现 新建项目结构后 RUN ...
- RabbitMQ介绍及windows下安装使用
RebbitMQ介绍 RabbitMQ是一个由 Erlang (一种通用的面向并发的编程语言)开发的AMQP(Advanced Message Queue )的开源实现,Rabbit MQ 是建立在E ...
- win32 去掉窗口边框
参考:http://www.blitzbasic.com/Community/posts.php?topic=67222 Strict Graphics 320, 200 SetClsColor 0, ...
- DataBinder.Eval的正确使用
本文介绍下,asp.net编程中有关DataBinder.Eval的用法,学习下asp.net DataBinder.Eval的用法,有需要的朋友参考下. 代码示例 :<%# Bind(&quo ...
- modsecurity3.0 nginx 安装
备注: 使用的是modsecurity 3.0 的版本,也是nginx 官方推荐使用的,同时使用的是nginx 的dynamic module 1. 环境准备 https://github.com/S ...
- openresty websocket 使用
openresty websocket 使用 1. 代码如下: local server =require"resty.websocket.server" local wb, ...
- chrome扩展程序开发之在目标页面执行自己的JS
大家都知道JS是执行在client的.所以,假设我们自己写一个浏览器的话.是一定能够往下载下来的网页源码中加入js的.可惜我们没有这个能力.只是幸运的是,chrome的扩展程序能够帮我们做到这件事. ...
- LuaJavaBridge
http://www.360doc.com/content/14/0117/13/9200790_345940368.shtml quick目录结构介绍 http://cn.cocos2d-x.org ...
- 分享百度文件上传组件webUploader的使用demo
先创建DOM节点:<head ng-app="myApp"> <meta charset="UTF-8"> <title>& ...
- mysql的partition分区
前言:当一个表里面存储的数据特别多的时候,比如单个.myd数据都已经达到10G了的话,必然导致读取的效率很低,这个时候我们可以采用把数据分到几张表里面来解决问题.方式一:通过业务逻辑根据数据的大小通过 ...