Introduz principalmente os struts2 combinados com cookies para obter login automático
Ao combinar struts2 com cookies, você deve prestar atenção ao uso de ações de ação para realizar a leitura de biscoitos
pacote de jar struts2
LINK DATABASE FILE DB.PROPERTIES
dbdriver = oracle.jdbc.driver.oracledriverurl = jdbc: oracle: thin: @localhost: 1521: orclusername = testpassword = senha
Código da camada DAO para obter informações do usuário através do nome de login
pacote com.struts.dao.impl; importar java.sql.connection; importar java.sql.preparedStatement; importar java.sql.resultset; importar java.sql.sqLexception; import.struts.daoer.userdao; impor.mstuts.sql.sqlException; comm.struts.daoer.userdao; UserdaoImpl implementa o userdao {private beanconnection dbconn = new beanconnection (); Login público do usuário (string loginName) {conexão conn = dbconn.getConnection (); ResultSet rs = null; String selsql = "Selecione * de t_scoa_sys_user onde f_loginname = '"+loginname+"'"; //System.out.println(selsql); Preparado PSTMT de estatuto preparado = null; Usuário do usuário = nulo; tente {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 (); } retornar usuário; } public void save (usuário do usuário) {} public static void main (string [] args) {userdaoimpl daoimpl = new userdaoimpl (); Daoimpl.login ("admin"); }}Classe de cookieutils da ferramenta
pacote com.struts.util; importar javax.servlet.http.cookie; importar javax.servlet.http.httpServletRequest; importar javax.servlet.http.httpssession; import org.apache.commache.lanxwork.stractUtils; importando; com.struts.action.loginaction; importar com.struts.proj.user; importar com.struts.service.userService; importar com.struts.service.impl.userServiceImpl; public class Cookieutils {public Static Final String User_cookie = "User.cookie"; // Adicione cookie public Cookie addCookie (usuário do usuário) {cookie cookie = new Cookie (user_cookie, user.getf_loginname () + "," + desede.decryptit (user.getf_password ()); Cookie.setMaxage (60 * 60 * 24 * 365); Retornar Cookie; } // Obtenha cookie public boolean getcookie (solicitação httpServletRequest, usuários service service) {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 (); // Determine se o caractere está vazio se (stringUtils.isnotblank (value)) {string [] derramado = value.split (","); String loginName = derramado [0]; Senha da string = derramado [1]; Usuário do usuário = Userservice.Login (LoginName, senha); if (usuário! = null) {httpSession session = request.getSession (); Session .SetAttribute (loginaction.user_session, usuário); // Adicione o usuário à sessão retorna true; }}}}} retornar false; } // excluir 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); Retornar Cookie; }} retornar nulo; }}Código da camada de serviço para verificar se o nome do usuário e a senha estão corretos. Eu uso o algoritmo de criptografia localmente e preciso ser descriptografado. Amigos podem remover a senha
pacote com.struts.service.impl; import com.struts.dao.userdao; importar com.struts.dao.impl.userdaoimpl; import com.struts.proj.User; UserDaoImpl (); Public User Login (String LoginName, String senha) {Usuário User = Userdao.login (LoginName); if (user == null) {System.out.println ("O nome do usuário não existe, verifique e faça o login novamente!"); } if (! desede.decryptit (user.getf_password ()). igual (senha)) {System.out.println ("erro de senha"); } retornar usuário; } public static void main (string [] args) {userServiceImpl useIMP = new UserserviceImpl (); System.out.println (useImp.login ("admin", "1234")); }}Verificação do arquivo de arquivo de configuração STRUTS2.XML, LoginAction e ValidAtEcOdEction Código de verificação de Struts2
<? xml versão = "1.0" coding = "utf-8"?> <! Doctype suporta public "-// Apache Software Foundation // DTD Struts Configuration 2.1 // en" "http://struts.apache.org/dts/stuts-2.1.dt1" value = "true"/> <constante name = "struts.devmode" value = "true"/> <names package = "loginResult" estends = "struts-default" namespace = "/"> <action name = "loginaction"> <resultado name = "success" = "redirect">/scorda.jsp </result> <cultion> <sould "> <result name = succed" = "" TIPO = "Redirect">/login.jsp </resultado> </action> <!-Código de verificação-> <ação name = "validate"> <param name = "width"> 60 </am Param> <param name = "altura"> 20 </param> <param name = "fontsize"> 18 </idos> <param name = "codelngth"> 4 </param> </amul name = "fontsize"> 18 </param> <param name = "codelngth"> 4 name = "contentType"> image/jpeg </param> <param name = "inputName"> inputStream </param> </resultado> </action> </package> </stuts>
Classe de arquivo de ação LoginAction
pacote com.struts.action; importar java.util.map; importar javax.servlet.http.cookie; importar javax.servlet.http.httpServletReQuest; import javax.servlet.http.httpsletResponso; 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; a classe pública LoginAction estende o ACOCTOPPORT {private estático final serialversionuid = 6650955874307814247l; String privada f_loginname; String privada f_password; Resposta privada de HttpServletResponse; Solicitação privada de HttpServletRequest; mapa privado <string, objeto> sessão; Cookieutils Private Cookieutils = New Cookieutils (); private boolean usercookie; Private String validateCode; public static final string user_session = "user.session"; UserService UserService = new UserServiceImpl (); public string autologin () lança exceção {request = servletActionContext.getRequest (); if (cookieutils.getCookie (request, ususerVice)) {return "succcess"; } mais retornar "login"; } @Override public String Execute () lança Exceção {httpSession session = servletActionContext.getRequest (). GetSession (); tente {string code = (string) session.getAttribute ("validateCode"); if (validateCode == null ||! ValidAtecode.equals (code)) {System.out.println ("O código de verificação é inserido incorretamente, digite -o corretamente"); retornar "erro"; } if (f_loginname! = null &&! "". Equals (f_loginname) &&! "". Equals (f_password) && f_password! = null) {usuário user = userService.Login (f_loginname, f_password); // Determine se deve adicionar ao cookie string psswd = DESED.DECRYPTIT (user.getf_password ()); if (usuário! = null && pswd.equals (f_password)) {if (usercookie) {cookie cookie = cookieutils.addcookie (usuário); ActionContext.getContext (). Get ("resposta"); ServletActionContext.GetResponse (). AddCookie (Cookie); } session.setAttribute (user_session, usuário); retornar "sucesso"; }}} catch (Exceção e) {e.printStackTrace (); } retornar "login"; } // O usuário sai public String Logout () {request = servletActionContext.getRequest (); resposta = servletActionContext.getResponse (); HTTPSession Session = ServletActionContext.getRequest (). GetSession (); sessão = request.getSession (false); if (session! = null) session.removeattribute (user_session); Cookie Cookie = Cookieutils.delcookie (solicitação); if (cookie! = null) resposta.addcookie (cookie); retornar "login"; } public static void main (string [] args) {loginaction login = new LoginAction (); tente {login.execute (); } catch (Exceção e) {e.printStackTrace (); }} mapa público <string, object> getSession () {retorna sessão; } public void SetSession (map <string, object> session) {this.session = session; } public httpServletResponse getResponse () {return Response; } public void setResponse (httpServletResponse resposta) {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; }}ValidAcodeAction, muitos exemplos de códigos de verificação na Internet, você pode escolher sua própria maneira de escrever o código de verificação
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; importar com.opensymphony.xwork2.ActionContext; importar com.opensymphony.xwork2.actionupport; classe pública validateCodeAction estende o ACTIONSupport {private Static Final Long SerialVersionUid = 1l; byteArrayInputStream privado InputStream; Private int Warth; altura privada int; private int fontsize; comprimento de código privado int; public validateCodeAction () {} public void setCodElength (int codElength) {this.codElength = codElength; } public void setFontSize (int fontSize) {this.fontSize = fontSize; } public void sethight (int alting) {this.Height = altura; } public void setWidth (int width) {this.width = width; } public byteArrayInputStream getInputStream () {return inputStream; } public void setInputStream (byteArrayInputStream inputStream) {this.InputStream = inputStream; } public string Execute () lança Exceção {bufferImage bimage = new bufferImage (largura, altura, 1); Gráficos g = bimage.getgraphics (); Aleatório aleatório = novo aleatório (); g.setColor (getrandomcolor (Random, 200, 255)); G.FillRect (0, 0, largura, altura); G.SetFont (New Font ("Times New Roman", 0, Fontsize)); g.setColor (getrandomcolor (Random, 160, 200)); for (int i = 0; i <155; i ++) {int x = aleatom.nextInt (largura); int y = random.nextint (altura); 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 aleatomstr = string.valueof (aleatory.nextInt (10)); str.Append (Randomstr); g.setColor (nova cor (20 + Random.NextInt (110), 20 + Random .Nextint (110), 20 + Random.Nextint (110), 20 + Random.Nextint (110))); int x = (largura / comprimento do código - 1) * i + aleatoriamente.nextInt (largura / (comprimento do código * 2)); int y = random.nextInt (altura - fontsize) + fontsize; G.DrawString (Randomstr, X, Y); } ActionContext.getContext (). GetSession (). Put ("validatecode", str.toString ()); G.Dispose (); BytearrayOutputStream Output = new ByteArrayOutputStream (); ImageOutputStream iout = imageio.createImageOutputStream (saída); Imageio.write (bimage, "jpeg", iout); iout.close (); output.Close (); ByteArrayInputStream in = new ByteArrayInputStream (output.TobyTearray ()); setInputStream (in); retornar "sucesso"; } color privado getrandomcolor (aleatório aleatório, int fc, int bc) {if (fc> 255) fc = 255; if (bc> 255) bc = 255; int r = fc + aleatoriamente.nextInt (bc - fc); int g = fc + aleatoriamente.nextInt (bc - fc); int b = fc + aleatoriamente.nextInt (bc - fc); retornar nova cor (R, G, B); }}Login Success Page Success.jsp
<%@ Page Language = "java" import = "java.util. 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> Página de sucesso </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 (); // Determine se o caractere está vazio se (stringUtils.isnotblank (value)) {string [] derramado = value.split (","); String loginName = derramado [0]; Senha da string = derramado [1]; out.println (LoginName + "Welcome to Fogen"); }}}}} %> <s: A Action = "LoginAction! Logout.action" Namespace = "/"> Safe </s: a> </body> </html>Obrigado pela leitura, espero que isso possa ajudá -lo. Obrigado pelo seu apoio a este site!