欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

struts2与cookie 实现自动登录和验证码验证实现代码

程序员文章站 2024-03-12 09:43:20
主要介绍struts2与cookie结合实现自动登录 struts2与cookie结合时要注意采用.action 动作的方式实现cookie的读取 struts...

主要介绍struts2与cookie结合实现自动登录

struts2与cookie结合时要注意采用.action 动作的方式实现cookie的读取

struts2的jar包

struts2与cookie 实现自动登录和验证码验证实现代码

 链接数据库文件 db.properties

dbdriver = oracle.jdbc.driver.oracledriver
url = jdbc:oracle:thin:@localhost:1521:orcl
username=test
password=password

dao层类代码,通过登录名获取用户信息

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 user;
  }

  public void save(user user) {
    
  }
  
  public static void main(string[] args) {
    userdaoimpl daoimpl = new userdaoimpl();
    daoimpl.login("admin");
  }

}

工具类 cookieutils类

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";

  // 增加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;
  }

  // 得到cookie
  public boolean getcookie(httpservletrequest request, userservice userservice) {
    request = servletactioncontext.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.getvalue();
          // 判断字符是否为空
          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);// 添加用户到session中
              return true;
            }
          }
        }
      }
    }
    return false;
  }

  // 删除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层代码,验证用户名和密码是否正确,密码我本地用了加密算法,需要解密,友友们可以去掉

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("用户名不存在,请检查后重新登录!");

    }
    if (!desede.decryptit(user.getf_password()).equals(password)) {
      system.out.println("密码错误");
    }
    return user;
  }

  public static void main(string[] args) {
    userserviceimpl useimp = new userserviceimpl();
    system.out.println(useimp.login("admin", "1234"));
  }
  
}

 struts2的配置文件struts.xml,loginaction和validatecodeaction验证码的验证

<?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="struts.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="redirect">/login.jsp</result>
    </action>
    <!-- 验证码 -->
    <action name="validate" class="com.struts.action.validatecodeaction">
      <param name="width">60</param>
      <param name="height">20</param>
      <param name="fontsize">18</param>
      <param name="codelength">4</param>
      <result type="stream">
        <param name="contenttype">image/jpeg</param>
        <param name="inputname">inputstream</param>
      </result>
    </action>
  </package>
</struts>

 action文件类 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().getsession();
    try {
       string code = (string) session.getattribute("validatecode");
      if (validatecode == null || !validatecode.equals(code)) {
        system.out.println("验证码输入有误,请正确输入");
        return "error";
      }
      if (f_loginname != null && !"".equals(f_loginname)
          && !"".equals(f_password) && f_password != null) {
        user user = userservice.login(f_loginname, f_password);
        // 判断是否要添加到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";
        }
      }

    } catch (exception e) {
      e.printstacktrace();
    }
    return "login";
  }

  // 用户退出
  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> session) {
    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;
  }
}

验证码 validatacodeaction ,网上很多验证码的例子,可以选择自己的方式来写验证码

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;
  }

  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 < 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);
    }

    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(20 + random.nextint(110), 20 + random
          .nextint(110), 20 + random.nextint(110)));
      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);
  }

}

登录成功页面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">
<html>
  <head>
    <base href="<%=basepath%>">
    <title>success page</title>
  </head>

  <body>
    <%
      cookie[] cookies = request.getcookies();
      if (cookies != null) {
        for (cookie cookie : cookies) {
          if (cookieutils.user_cookie.equals(cookie.getname())) {
            string value = cookie.getvalue();
            // 判断字符是否为空
            if (stringutils.isnotblank(value)) {
              string[] spilt = value.split(",");
              string loginname = spilt[0];
              string password = spilt[1];
              out.println(loginname + "欢迎登陆");
            }
          }
        }
      }
    %>
    <s:a action="loginaction!logout.action" namespace="/"> 安全退出</s:a>
  </body>
</html>

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!