Struts2 and cookies implement automatic login and verification code verification Code _java

Source: Internet
Author: User
Tags stringbuffer

The main introduction struts2 and cookies in conjunction with the implementation of automatic login

Struts2 and cookies should be combined with the use of the. Action action to implement cookies read

Struts2 Jar Pack

Linked database file db.properties

dbdriver = oracle.jdbc.driver.OracleDriver
url = jdbc:oracle:thin: @localhost: 1521:ORCL
username=test
Password=password

DAO layer Class code, obtaining user information by login name

Package Com.struts.dao.impl;
Import java.sql.Connection;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;

Import java.sql.SQLException;
Import Com.struts.dao.UserDao;
Import Com.struts.proj.User;

Import com.struts.util.BeanConnection;
  public class Userdaoimpl implements Userdao {private beanconnection dbconn = new Beanconnection ();
     Public User Login (String loginname) {Connection conn = dbconn.getconnection ();
     ResultSet rs = null;
     String selsql = "SELECT * from T_scoa_sys_user where f_loginname= '" +loginname+ "";
     System.out.println (Selsql);
     PreparedStatement pstmt = null;
    User user = null;
      try {pstmt = conn.preparestatement (Selsql);
      Pstmt.setstring (3, loginname);
      rs = Pstmt.executequery ();
        while (Rs.next ()) {user = new user ();
        User.setid (Rs.getlong (1));
        User.setf_username (rs.getstring (2));
        User.setf_loginname (Rs.getstring (3));
     User.setf_sex (Rs.getstring (4));   User.setf_state (Rs.getstring (5));
        User.setf_email (rs.getstring (6));
        User.setf_mobilephone (rs.getstring (7));
        User.setf_secretaryid (Rs.getlong (8));
        User.setf_password (rs.getstring (9));
        User.setf_order (Rs.getlong (10));
        User.setf_note (rs.getstring (11));
      User.setf_infomodifytemplateid (Rs.getlong (12));
    } catch (SQLException e) {e.printstacktrace ();
  return to user; public void Save (user user) {} public static void Main (string[] args) {Userdaoimpl Daoimpl = new Us
    Erdaoimpl ();
  Daoimpl.login ("admin");

 }

}

Tool Class Cookieutils class

Package com.struts.util;
Import Javax.servlet.http.Cookie;
Import Javax.servlet.http.HttpServletRequest;

Import javax.servlet.http.HttpSession;
Import Org.apache.commons.lang.xwork.StringUtils;

Import Org.apache.struts2.ServletActionContext;
Import com.struts.action.LoginAction;
Import Com.struts.proj.User;
Import Com.struts.service.UserService;

Import Com.struts.service.impl.UserServiceImpl;

  public class Cookieutils {public static final String User_cookie = "User.cookie"; 
        Add Cookie Public cookie Addcookie (user user) {Cookie cookie = new Cookie (User_cookie, user.getf_loginname () + ","
    + Desede.decryptit (User.getf_password ());
    Cookie.setmaxage (60 * 60 * 24 * 365);
  return cookie; //Get Cookie public boolean GetCookie (HttpServletRequest request, UserService userservice) {request = Servletac
    Tioncontext.getrequest ();
    cookie[] cookies = request.getcookies ();
    UserService = new Userserviceimpl (); if (cookies!= null) {for (CoOkie cookie:cookies) {if (CookieUtils.USER_COOKIE.equals (Cookie.getname ())) {String value = cookie.g
          Etvalue ();
            Determines whether the character is an empty if (Stringutils.isnotblank (value)) {string[] spilt = Value.split (",");
            String loginname = spilt[0];
            String password = spilt[1];
            User user = Userservice.login (loginname, password);
              if (user!= null) {HttpSession session = Request.getsession ();
              Session. setattribute (loginaction.user_session, user);//Add Users to session
            return true;
  }}} return false;
    //Delete Cookie public cookie Delcookie (HttpServletRequest request) {request = Servletactioncontext.getrequest ();
    cookie[] cookies = request.getcookies ();
          if (cookies!= null) {for (Cookie cookie:cookies) {if (User_cookie.equals (Cookie.getname ())) {Cookie.setvalue ("");
          Cookie.setmaxage (0);
        return cookie;
  }} return null;

 }
}

Service layer code, verify the user name and password is correct, password I used a local encryption algorithm, need to decrypt, friends can be removed

Package Com.struts.service.impl;

Import Com.struts.dao.UserDao;
Import Com.struts.dao.impl.UserDaoImpl;
Import Com.struts.proj.User;
Import Com.struts.service.UserService;
Import Com.struts.util.DESEDE;

public class Userserviceimpl implements UserService {
  Userdao Userdao = new Userdaoimpl ();

  Public User Login (string loginname, string password) {
    User user = Userdao.login (loginname);
    if (user = null) {
      System.out.println ("username does not exist, please check and login again!") ");

    }
    if (! Desede.decryptit (User.getf_password ()). Equals (password)) {
      System.out.println ("Password error");
    }
    return user;
  }

  public static void Main (string[] args) {
    Userserviceimpl useimp = new Userserviceimpl ();
    System.out.println (Useimp.login ("admin", "1234"));
  }
  

Struts2 configuration file struts.xml,loginaction and Validatecodeaction authentication code verification

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE struts Public "-//apache Software foundation//dtd struts Configuration 2.1//en" "Http://struts.apache.org/dtds /struts-2.1.dtd "> <struts> <constant name=" Struts.i18n.reload "value=" true ""/> <constant name= "Stru Ts.devmode "value=" true "/> <package name=" Loginresult "extends=" Struts-default "namespace="/"> <action Name= "Loginaction" class= "com.struts.action.LoginAction" > <result name= "Success" type= "redirect" >/success .jsp</result> <result name= "error" >/error.jsp</result> <result name= "Login" type= "Redirec" T ">/login.jsp</result> </action> <!--verification code--> <action name=" Validate "class=" Com.strut S.action.validatecodeaction "> <param name=" width ">60</param> <param name=" height ">20</ param> <param name= "fontsize" >18</param> <param name= "Codelength" &Gt;4</param> <result type= "Stream" > <param name= "ContentType" >image/jpeg</param> <param name= "InputName" >inputStream</param> </result> </action> </package> & Lt;/struts>

 action File class Loginaction

Package com.struts.action;

Import Java.util.Map;
Import Javax.servlet.http.Cookie;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import javax.servlet.http.HttpSession;


Import Org.apache.struts2.ServletActionContext;
Import Com.opensymphony.xwork2.ActionContext;
Import Com.opensymphony.xwork2.ActionSupport;
Import Com.struts.proj.User;
Import Com.struts.service.UserService;
Import Com.struts.service.impl.UserServiceImpl;
Import Com.struts.util.CookieUtils;

Import Com.struts.util.DESEDE;
  public class Loginaction extends Actionsupport {private static final long serialversionuid = 6650955874307814247L;
  Private String F_loginname;

  Private String F_password;
  Private HttpServletResponse response;
  private HttpServletRequest request;
  Private Map<string, object> session;
  Private Cookieutils cookieutils = new Cookieutils ();

  Private Boolean Usercookie;

  Private String Validatecode; public static final String User_seSsion = "User.session";

  UserService userservice = new Userserviceimpl ();
    Public String Autologin () throws Exception {request = Servletactioncontext.getrequest ();
    if (Cookieutils.getcookie (request, UserService)) {return "success";
  else return "login"; @Override public String Execute () throws Exception {HttpSession session = Servletactioncontext.getrequest (). GE
    TSession ();
      try {String code = (string) session.getattribute ("Validatecode");
        if (Validatecode = null | |!validatecode.equals (code)) {System.out.println ("Input is incorrect, please enter correctly");
      return "error"; } if (F_loginname!= null &&! "". Equals (f_loginname) &&! "".
        Equals (F_password) && f_password!= null) {User user = Userservice.login (f_loginname, F_password);
        Determine if you want to add to the cookie String psswd = Desede.decryptit (User.getf_password ());
if (user!= null && psswd.equals (F_password)) {          if (usercookie) {Cookie cookie = cookieutils.addcookie (user);
            Actioncontext.getcontext (). Get ("response");
          Servletactioncontext.getresponse (). Addcookie (cookie);
          } session.setattribute (User_session, USER);
        Return "Success";
    A catch (Exception e) {e.printstacktrace ());
  return "Login";
    }//user exits Public String logout () {request = Servletactioncontext.getrequest ();
    Response = Servletactioncontext.getresponse ();
    HttpSession session = Servletactioncontext.getrequest (). GetSession ();
    Session = Request.getsession (false);
    if (session!= null) Session.removeattribute (user_session);
    Cookie cookie = Cookieutils.delcookie (request);
    if (cookie!= null) Response.addcookie (cookie);
  return "Login";
    public static void Main (string[] args) {loginaction login = new Loginaction ();
    try {login.execute (); catch (ExceptiOn e) {e.printstacktrace ();
  } public map<string, Object> getsession () {return session;
  } public void Setsession (map<string, object> sessions) {this.session = session;
  Public HttpServletResponse GetResponse () {return response;
  public void Setresponse (HttpServletResponse response) {this.response = response;
  Public HttpServletRequest Getrequest () {return request;
  public void Setrequest (HttpServletRequest request) {this.request = Request;
  public Boolean Isusercookie () {return usercookie;
  } public void Setusercookie (Boolean usercookie) {This.usercookie = Usercookie;
  Public String Getf_loginname () {return f_loginname;
  } public void Setf_loginname (String floginname) {f_loginname = Floginname;
  Public String Getf_password () {return f_password;
  } public void Setf_password (String fpassword) {F_password = Fpassword; } public String GetvaLidatecode () {return validatecode;
  } public void Setvalidatecode (String validatecode) {this.validatecode = Validatecode; }
}

Verification Code Validatacodeaction, many examples of verification code on the Web, you can choose your own way to write the authentication code

Package com.struts.action;
Import Java.awt.Color;
Import Java.awt.Font;
Import Java.awt.Graphics;
Import Java.awt.image.BufferedImage;
Import Java.io.ByteArrayInputStream;
Import Java.io.ByteArrayOutputStream;

Import Java.util.Random;
Import Javax.imageio.ImageIO;

Import Javax.imageio.stream.ImageOutputStream;
Import Com.opensymphony.xwork2.ActionContext;

Import Com.opensymphony.xwork2.ActionSupport;
  public class Validatecodeaction extends Actionsupport {private static final long serialversionuid = 1L;
  Private Bytearrayinputstream InputStream;
  private int width;
  private int height;
  private int fontsize;

  private int codelength;
  Public validatecodeaction () {} public void setcodelength (int codelength) {this.codelength = Codelength;
  The public void setfontsize (int fontsize) {this.fontsize = FontSize;
  public void setheight (int height) {this.height = height;
  public void setwidth (int width) {this.width = width; } public BYtearrayinputstream getInputStream () {return inputstream;
  public void Setinputstream (Bytearrayinputstream inputstream) {this.inputstream = InputStream;
    Public String Execute () throws Exception {BufferedImage bimage = new BufferedImage (width, height, 1);
    Graphics g = bimage.getgraphics ();
    Random Random = new Random ();
    G.setcolor (Getrandomcolor (random, 200, 255));
    G.fillrect (0, 0, width, height);
    G.setfont (New Font ("Times New Roman", 0, FontSize));
    G.setcolor (Getrandomcolor (random, 160, 200));
      for (int i = 0; i < 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);
    } stringbuffer str = new StringBuffer ();
      for (int i = 0; i < codelength i++) {String randomstr = string.valueof (Random.nextint (10));
      Str.append (RANDOMSTR); G.setcolor (New Color (+ RANDOM.NExtint (random), + random.nextint (110)) (Nextint);
      int x = (width/codelength-1) * i + random.nextint (width/(codelength * 2));
      int y = random.nextint (height-fontsize) + fontsize;
    g.DrawString (Randomstr, x, y);
    Actioncontext.getcontext (). GetSession (). Put ("Validatecode", str.tostring ());
    G.dispose ();
    Bytearrayoutputstream output = new Bytearrayoutputstream ();
    Imageoutputstream iout = imageio.createimageoutputstream (output);
    Imageio.write (Bimage, "JPEG", iout);
    Iout.close ();
    Output.close ();
    Bytearrayinputstream in = new Bytearrayinputstream (Output.tobytearray ());
    Setinputstream (in);
  Return "Success";
    Private Color Getrandomcolor (Random Random, int FC, int BC) {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); }

}

Log on successful page success.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% @page import= " Com.struts.util.CookieUtils "%> <% @page import=" org.apache.commons.lang.xwork.StringUtils "%> <%@ taglib
  Uri= "/struts-tags" prefix= "s"%> <% String Path = Request.getcontextpath ();  String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path
+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

Thank you for reading, I hope to help you, thank you for your support for this site!

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.