最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

struts2與cookie 實(shí)現(xiàn)自動(dòng)登錄和驗(yàn)證碼驗(yàn)證實(shí)現(xiàn)代碼

 更新時(shí)間:2016年10月19日 17:21:41   投稿:lqh  
這篇文章主要介紹了struts2與cookie 實(shí)現(xiàn)自動(dòng)登錄和驗(yàn)證碼驗(yàn)證實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下

主要介紹struts2與cookie結(jié)合實(shí)現(xiàn)自動(dòng)登錄

struts2與cookie結(jié)合時(shí)要注意采用.action 動(dòng)作的方式實(shí)現(xiàn)cookie的讀取

struts2的jar包

 鏈接數(shù)據(jù)庫(kù)文件 db.properties

dbDriver = oracle.jdbc.driver.OracleDriver
url = jdbc:oracle:thin:@localhost:1521:orcl
userName=test
password=password

dao層類(lèi)代碼,通過(guò)登錄名獲取用戶信息

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

}

工具類(lèi) CookieUtils類(lèi)

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層代碼,驗(yàn)證用戶名和密碼是否正確,密碼我本地用了加密算法,需要解密,友友們可以去掉

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("用戶名不存在,請(qǐng)檢查后重新登錄!");

    }
    if (!DESEDE.decryptIt(user.getF_password()).equals(password)) {
      System.out.println("密碼錯(cuò)誤");
    }
    return user;
  }

  public static void main(String[] args) {
    UserServiceImpl useimp = new UserServiceImpl();
    System.out.println(useimp.login("admin", "1234"));
  }
  
}

 struts2的配置文件struts.xml,loginAction和ValidateCodeAction驗(yàn)證碼的驗(yàn)證

<?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>
    <!-- 驗(yàn)證碼 -->
    <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文件類(lèi) 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("驗(yàn)證碼輸入有誤,請(qǐng)正確輸入");
        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;
  }
}

驗(yàn)證碼 ValidataCodeAction ,網(wǎng)上很多驗(yàn)證碼的例子,可以選擇自己的方式來(lái)寫(xiě)驗(yàn)證碼

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

}

登錄成功頁(yè)面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>

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

  • 手把手教你用Java給暗戀對(duì)象發(fā)送一份表白郵件

    手把手教你用Java給暗戀對(duì)象發(fā)送一份表白郵件

    隨著我們學(xué)習(xí)java的深入,也漸漸發(fā)現(xiàn)了它的一些樂(lè)趣,比如發(fā)送郵件,下面這篇文章主要給大家介紹了關(guān)于如何利用Java給暗戀對(duì)象發(fā)送一份表白郵件的相關(guān)資料,需要的朋友可以參考下
    2021-11-11
  • Java數(shù)據(jù)結(jié)構(gòu)之圖的基礎(chǔ)概念和數(shù)據(jù)模型詳解

    Java數(shù)據(jù)結(jié)構(gòu)之圖的基礎(chǔ)概念和數(shù)據(jù)模型詳解

    在現(xiàn)實(shí)生活中,有許多應(yīng)用場(chǎng)景會(huì)包含很多點(diǎn)以及點(diǎn)點(diǎn)之間的連接,而這些應(yīng)用場(chǎng)景我們都可以用即將要學(xué)習(xí)的圖這種數(shù)據(jù)結(jié)構(gòu)去解決。本文主要介紹了圖的基礎(chǔ)概念和數(shù)據(jù)模型,感興趣的可以了解一下
    2022-11-11
  • Spring?boot?自定義?Starter及自動(dòng)配置的方法

    Spring?boot?自定義?Starter及自動(dòng)配置的方法

    Starter?組件是?Spring?boot?的一個(gè)核心特性,Starter組件的出現(xiàn)極大的簡(jiǎn)化了項(xiàng)目開(kāi)發(fā),這篇文章主要介紹了Spring?boot?自定義?Starter?及?自動(dòng)配置,需要的朋友可以參考下
    2022-12-12
  • Java中常用緩存Cache機(jī)制的實(shí)現(xiàn)

    Java中常用緩存Cache機(jī)制的實(shí)現(xiàn)

    這篇文章主要介紹了Java中常用緩存Cache機(jī)制的實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-10-10
  • 列舉java語(yǔ)言中反射的常用方法及實(shí)例代碼

    列舉java語(yǔ)言中反射的常用方法及實(shí)例代碼

    反射機(jī)制指的是程序在運(yùn)行時(shí)能夠獲取自身的信息。這篇文章主要介紹了列舉java語(yǔ)言中反射的常用方法,需要的朋友可以參考下
    2019-07-07
  • MyBatis之foreach標(biāo)簽的用法及多種循環(huán)問(wèn)題

    MyBatis之foreach標(biāo)簽的用法及多種循環(huán)問(wèn)題

    這篇文章主要介紹了MyBatis之foreach標(biāo)簽的用法及多種循環(huán)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • Flowable執(zhí)行完畢的流程查找方法

    Flowable執(zhí)行完畢的流程查找方法

    這篇文章主要為大家介紹了Flowable執(zhí)行完畢的流程查找方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • JAVA字符串格式化-String.format()的使用

    JAVA字符串格式化-String.format()的使用

    本篇文章主要介紹了JAVA字符串格式化-String.format()的使用,具有一定的參考價(jià)值,有需要的可以了解一下。
    2016-11-11
  • Spring Boot 整合mybatis 與 swagger2

    Spring Boot 整合mybatis 與 swagger2

    之前使用springMVC+spring+mybatis,總是被一些繁瑣的xml配置,還經(jīng)常出錯(cuò),下面把以前的一些ssm項(xiàng)目改成了spring boot + mybatis,相對(duì)于來(lái)說(shuō)優(yōu)點(diǎn)太明顯了,具體內(nèi)容詳情大家通過(guò)本文學(xué)習(xí)吧
    2017-08-08
  • Spinrg WebFlux中Cookie的讀寫(xiě)的示例

    Spinrg WebFlux中Cookie的讀寫(xiě)的示例

    這篇文章主要介紹了Spinrg WebFlux中Cookie的讀寫(xiě)的示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2019-01-01

最新評(píng)論

历史| 祁连县| 金阳县| 广元市| 镇赉县| 宁陵县| 米易县| 安龙县| 湛江市| 钟山县| 海丰县| 闽清县| 余干县| 多伦县| 长阳| 乌鲁木齐县| 万盛区| 荆州市| 依兰县| 外汇| 乡宁县| 枞阳县| 蒙自县| 灵石县| 荥阳市| 文山县| 裕民县| 隆德县| 东阳市| 汤阴县| 咸宁市| 铁岭市| 海口市| 方山县| 岱山县| 昭通市| 铁岭县| 临邑县| 吉水县| 苏尼特左旗| 丹巴县|