Verification code and password encryption are used in Java

Source: Internet
Author: User
Tags button type rand set background

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 {
/**
* If the request is logged in, then go directly or jump to the login page
*/
HttpServletRequest req = (httpservletrequest) request;
HttpServletResponse resp = (httpservletresponse) response;
Get the session to determine if there are users in the session
HttpSession session = Req.getsession ();

String uri = Req.getrequesturi ();

Object users = Session.getattribute ("admin");
Logged-On
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" >
<base href= "<%=basePath%>" >
<meta http-equiv= "Content-type" content= "Text/html;charset=utf-8" >

<title> Background Management | Login </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>

<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" > Username </label>
<div class= "Col-sm-9" >
<input type= "text" name= "username" class= "Form-control" placeholder= "User name" value= "${username}" >
</div>
</div>
<div class= "Form-group" >
<label class= "Control-label col-sm-3 text-right" > Password </label>
<div class= "Col-sm-9" >
<input type= "password" name= "password" class= "Form-control" placeholder= "password" value= "${password}" >
</div>
</div>
<div class= "Form-group" >
<label class= "Control-label col-sm-3 text-right" > Verification Code </label>
<div class= "Col-sm-9" >
<div class= "Input-group" >
<input type= "text" name= "Valicode" class= "Form-control" placeholder= "Captcha" >
<div class= "Input-group-addon" style= "padding:0 2px; " >
</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" ': '}> remember password
</label>
</div>
</div>
</div>
<div class= "Form-group" >
<div class= "Col-sm-9 col-sm-offset-3" >
<button class= "btn Btn-default" type= "submit" > Login </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>

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.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 {
Handling Logon Requests
Get User name and password
String username = request.getparameter ("username");
String Password = request.getparameter ("password");
String Valicode = Request.getparameter ("Valicode");
Get status
String remember = Request.getparameter ("Remember");

if (Request.getsession (). getattribute ("Rand"). ToString (). Equalsignorecase (Valicode)) {
User name cannot be empty
if (Username!=null && username.trim ()! = "") {
Get a user
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) {
Deal with the success of the situation
HttpSession session = Request.getsession ();
Session.setattribute ("admin", u);
Action cookie when setting a cookie remember = Username:password:state


Cookie []cookies = Request.getcookies ();
Just to find the cookie I want.
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)) {
Handling of cookies and cookies
/*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", "Username or password error, please try again!") ");
}else{
Request.setattribute ("msg", "Captcha error, please try again!") ");
}
Request.setattribute ("username", username);
Request.setattribute ("password", password);
Request.setattribute ("Remember", remember);
Request.getrequestdispatcher ("/views/login.jsp"). Forward (request, response);
return;
}

}

IMAGE.JSP (generate verification code)

<% @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) {//given range get random color
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 ();
Settings page does not cache
Response.setheader ("Pragma", "No-cache");
Response.setheader ("Cache-control", "No-cache");
Response.setdateheader ("Expires", 0);

Create an image in memory
int width = N, height = 30;
BufferedImage image = new BufferedImage (width, height, bufferedimage.type_int_rgb);

Get the graphics context
Graphics g = image.getgraphics ();

Generating random classes
Random random = new random ();

Set Background color
G.setcolor (Getrandcolor (200, 250));
G.fillrect (0, 0, width, height);

Set font
G.setfont (New Font ("Arial", 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); */

Draw Border
G.setcolor (Color.Black);
G.drawrect (0, 0, width-1, height-1);

Randomly generates 155 lines of interference so that the authentication code in the image is not easily detected by other programs
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 '};

Randomly generated authentication code (4 digits)
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;
Display the authentication code to the image
G.setcolor (New Color (+ random.nextint), + random.nextint (+), + random.nextint (110));
The call function comes out with the same color, possibly because the seed is too close, so it can only be generated directly
g.DrawString (Rand, * i + 6, 16);
g.DrawString (Rand, * i + 6, 20);
}

Save authentication Code to session
Session.setattribute ("Rand", SRand); This line of code gives us a focus on
Image effective
G.dispose ();

Output image to Page
try {
Imageio.write (Image, "JPEG", Response.getoutputstream ());
} catch (Exception e) {
E.getmessage ();
} finally {

Resolve to invoke error
out = Pagecontext.pushbody ();

}
%>

Verification code and password encryption are used in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.