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

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

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

struts2的jar包

 链接数据库文件 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>

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

(0)

相关推荐

  • Struts2拦截器 关于解决登录的问题

    拦截器的工作原理如图 拦截器是由每一个action请求(request)都包装在一系列的拦截器的内部,通过redirectAction再一次发送请求. 拦截器可以在Action执行直线做相似的操作也可以在Action执行直后做回收操作. 我们可以让每一个Action既可以将操作转交给下面的拦截器,Action也可以直接退出操作返回客户既定的画面. 接下来我们该如何定义一个拦截器: 自定义一个拦截器如下: 1.实现Interceptor接口或者继承AbstractInterceptor抽象类. 2

  • JQuery+Ajax+Struts2+Hibernate框架整合实现完整的登录注册

    最近在仿造一个书城的网站: http://www.yousuu.com ,UI直接拿来用,前端后端自己写,目前大部分功能已经实现, 就把具体的 登录注册功能 拿来分享一下.PS:又写登录注册会不会被人喷啊=.= 一.开发环境的部署 程序结构: BootStrap+Ajax+Struts2+Hibernate+MySql 仅供参考:能实现相关功能即可 操作系统:ubuntu 14.10 前端框架:BootStrap   注:此框架只是为了实现用户界面,和具体功能无关 数据库:mysql-5.5 数

  • Java struts2 validate用户登录校验功能实现

    首先贴一下搭配的环境: 配置: Eclipse4.3.2 jdk1.7_45 Mysql 5.0+ 然后切入正题: 1.login.jsp 主要是使用OGNL 标签 也可使用html form表单,调用LoginAction.action,以post 方式传输. 在LoginaAction 经过判断,然后会有提示信息,需要用到 <s:fielderror/>来显示. <%@ taglib uri="/struts-tags" prefix="s"%

  • Struts2拦截器登录验证实例

    Struts2拦截器 Struts2拦截器的概念和Spring Mvc拦截器一样. 1.Struts2拦截器是在访问某个Action或Action的某个方法,字段之前或之后实施拦截,并且Struts2拦截器是可插拔的,拦截器是AOP的一种实现. 2.拦截器栈(Interceptor Stack).Struts2拦截器栈就是将拦截器按一定的顺序联结成一条链.在访问被拦截的方法或字段时,Struts2拦截器链中的拦截器就会按其之前定义的顺序被调用. 使用拦截器的第一步: 自定义我的权限拦截器Chec

  • 基于struts2和hibernate实现登录和注册功能

    本文实例为大家分享了struts2和hibernate实现登录和注册功能,供大家参考,具体内容如下 1.该项目使用MySQL数据库,数据库名为test,表名info,如图所示: 2.配置web.xml(Struts2使用) <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/jav

  • struts2+jquery组合验证注册用户是否存在

    注册界面 register.jsp 复制代码 代码如下: <%@ page language="java" contentType="text/html; charset=UTF-8"%> <html> <head> <title>注册界面</title> <script type="text/javascript" src="js/jquery-1.6.js"

  • 详解Struts2中对未登录jsp页面实现拦截功能

    Struts2中拦截器大家都很经常使用,但是拦截器只能拦截action不能拦截jsp页面.这个时候就有点尴尬了,按道理来说没登录的用户只能看login界面不能够通过输入URL进行界面跳转,这显然是不合理的.这里介绍Struts2中Filter实现jsp页面拦截的功能.(有兴趣的人可以去研究Filter过滤器的其它用法,因为利用过滤器也可以实现action拦截的功能) 下面直接上代码,边看边分析实现步骤和原理. 1.web.xml中的配置信息: <filter> <filter-name&

  • 防止未登录用户操作—基于struts2拦截器的简单实现

    一般,我们的web应用都是只有在用户登录之后才允许操作的,也就是说我们不允许非登录认证的用户直接访问某些页面或功能菜单项.我还记得很久以前我的做法:在某个jsp页面中查看session中是否有值(当然,在用户登录逻辑中会将用户名或者用户对象存入session中),如果session中用户信息为空,那么redirect 到登录页面.然后在除了登录页面外的其它所有需要验证用户已登录的页面引入这个jsp . 比如,我们将检查用户是否登录的代码放入一个jsp页面中,如 checkUser.jsp <%@

  • 使用MyEclipse 开发struts2框架实现登录功能(结构教程)

    1.首先建立Web Project,名称为:struts2 ,然后选择Java EE6.0,点击Finish. 2.右击"struts"选择MyEclipse->Add Struts Capabilities,然后弹出如下弹窗,再选择Struts 2.1.选择完成即可点击Finish. 3.建完后项目目录如下图所示: 4.建立一个Login类,继承ActionSupport类(点击Superclass的Browse,选择搜索ActionSupport) 5.定义username,

  • Struts2开发环境搭建 附简单登录功能实例

    首先是搭建Struts2环境. 第一步 下载Struts2 去Struts官网 http://struts.apache.org/ 下载Struts2组件. 截至目前,struts2最新版本为2.3.1.3,下载struts-2.3.16.3-all.zip,解压,放着. 第二步 新建Web Project并导入jar包 在MyEclispe中新建Web Project,然后找到解压的Struts2包,在里面apps文件夹下找到struts2-blank.war,解压这个WAR文件,将里面WEB

随机推荐