目录结构:
首页:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% 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>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <a href="login.jsp">登录</a><br> </body> </html>
登录页面:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>用户登录</title> </head> <body> <div align="left"> <s:a href="register.jsp"> <font color="blue"> <h5>还未注册?点击注册</h5> </font> </s:a> </div> <div> <s:form action="login" method="post"> <s:textfield name="username" label="账号"></s:textfield> <s:password name="password" label="密码"></s:password> <s:submit value="登录"></s:submit> </s:form> </div> </body> </html>
LoginAction:(登录提交到的action)
package action; import java.util.Map; import biz.Users; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import dao.DbService; public class LoginAction extends ActionSupport { private static final long serialVersionUID = 1L; private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String execute() throws Exception { DbService dbService = new DbService(); Users user = new Users(); user = dbService.hasUser(username, password); if(user.getUsername() == null) { this.addFieldError(username, "用户或密码不正确!"); return INPUT; } else { ActionContext actionContext = ActionContext.getContext(); Map session = actionContext.getSession(); session.put("user", user.getUsername()); } return SUCCESS; } }
登录成功页面:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>我的主页</title> </head> <body> <h4 align="left"><font color="blue">欢迎您,${ user }</font></h4> </body> </html>
注册页面:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>用户注册</title> <script type="text/javascript"> function shuaxin(obj) { var shijian = new Date().getTime(); obj.src="imageAction.action?d="+shijian; } </script> </head> <body> <h1 align="center">用户注册</h1> <div align="center"> <s:fielderror cssStyle="color:red"></s:fielderror> <s:actionerror cssStyle="color:red"/> <br /> <s:form action="register" theme="simple" method="post"> <table width="50%" border="0" style="width: 50px;height: 342px;"> <tr> <td align="right">账号</td> <td width="20"> <s:textfield name="username"></s:textfield> </td> <td> <font color="red" align="left"> <h6>*必填</h6> </font> </td> </tr> <tr> <td align="right">密码</td> <td> <s:password name="password"></s:password> </td> <td> <font color="red" align="left"> <h6>*必填</h6> </font> </td> </tr> <tr> <td align="right">重复密码</td> <td> <s:password name="repassword"></s:password> </td> <td> <font color="red" align="left"> <h6>*必填</h6> </font> </td> </tr> <tr> <td align="right">性别</td> <td> <input type="radio" name="sex" value="0" checked="checked"/> 男 <input type="radio" name="sex" value="1"/> 女 </td> </tr> <tr> <td align="right">电子邮箱</td> <td> <s:textfield name="email"></s:textfield> </td> <td> <font color="red" align="left"> <h6>*必填</h6> </font> </td> </tr> <tr> <td align="right">验证码</td> <td> <s:textfield name="validate"></s:textfield> </td> <td> <img alt="点击图片" src="imageAction" align="left" onclick="shuaxin(this)" /> </td> </tr> <tr> <td> <s:submit value="提交"></s:submit> </td> <td> <s:reset value="重置"></s:reset> </td> </tr> </table> </s:form> </div> </body> </html>
注册提交到的action:
package action; import java.util.Map; import biz.Users; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import dao.DbService; public class RegisterAction extends ActionSupport { private static final long serialVersionUID = 1L; private String username; private String password; private String repassword; private String sex; private String email; private String validate; //证实 public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRepassword() { return repassword; } public void setRepassword(String repassword) { this.repassword = repassword; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getValidate() { return validate; } public void setValidate(String validate) { this.validate = validate; } @Override public String execute() throws Exception{ int sex1 = Integer.parseInt(sex); Users user = new Users(); user.setUsername(username); user.setPassword(password); user.setSex(sex1); user.setEmail(email); DbService dbService = new DbService(); if(dbService.hasSameName(username)) { this.addFieldError(username, "用户名已存在!"); return INPUT; } else { dbService.addUser(user); } return SUCCESS; } @Override public void validate() { ActionContext actionContext = ActionContext.getContext(); Map session = actionContext.getSession(); if(!repassword.equals(password)) { this.addFieldError(repassword, "重复密码不一致!"); } if(!session.get("random").equals(validate)) { this.addFieldError(validate, "验证码错误!"); } } }
获取验证码的action:
package 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.Map; import javax.imageio.ImageIO; import javax.imageio.stream.ImageOutputStream; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class ImageAction extends ActionSupport { private static final long serialVersionUID = 1L; private ByteArrayInputStream inputStream; public String creatRandomString() { String str = ""; for(int i = 0; i < 4 ; i++) { str += Integer.toString((new Double(Math.random() * 10)).intValue()); } return str; } public Color createsRandomColor() { int r = (new Double(Math.random() * 256)).intValue(); int g = (new Double(Math.random() * 256)).intValue(); int b = (new Double(Math.random() * 256)).intValue(); return new Color(r, g, b); } public BufferedImage createImage(String str) { int width = 60; int height = 22; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //获取图形上下文 Graphics g = image.getGraphics(); //设定背景色 g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); //画边框 g.setColor(Color.black); g.drawRect(0, 0, width - 1, height - 1); //将认证码显示到图像中 g.setFont(new Font("Atlantic Inline", Font.PLAIN, 18)); //使用随便颜色 g.setColor(this.createsRandomColor()); //将随机字符串的每个数字分别写到图片上 g.drawString(Character.toString(str.charAt(0)), 8, 17); g.drawString(Character.toString(str.charAt(1)), 20, 17); g.drawString(Character.toString(str.charAt(2)), 33, 17); g.drawString(Character.toString(str.charAt(3)), 45, 17); //图像生效 g.dispose(); return image; } //将图片以字节形式写到InputStream里 public ByteArrayInputStream createInuptStream() throws Exception { //获取随机字符串 String str = this.creatRandomString(); BufferedImage image = this.createImage(str); //将产生的字符串写入session,供校验时使用; ActionContext actionContext = ActionContext.getContext(); Map session = actionContext.getSession(); session.put("random", str); ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageOutputStream imageOut = ImageIO.createImageOutputStream(output); ImageIO.write(image, "JPEG", imageOut); imageOut.close(); ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray()); output.close(); return input; } @Override public String execute() throws Exception { setInputStream(createInuptStream()); return SUCCESS; } public ByteArrayInputStream getInputStream() { return inputStream; } public void setInputStream(ByteArrayInputStream inputStream) { this.inputStream = inputStream; } }
登录验证:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> <validators> <field name="username"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>账号不能为空</message> </field-validator> </field> <field name="password"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>密码不能为空</message> </field-validator> </field> </validators>
注册验证:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> <validators> <field name="username"> <field-validator type="requiredstring" short-circuit="true"> <param name="trim">true</param> <message>账号不能为空</message> </field-validator> <field-validator type="stringlength"> <param name="minLength">6</param> <param name="maxLength">20</param> <message>账号长度应该在${minLength} ~ ${maxLength}之间</message> </field-validator> </field> <field name="password"> <field-validator type="requiredstring" short-circuit="true"> <param name="trim">true</param> <message>密码不能为空</message> </field-validator> <field-validator type="stringlength"> <param name="minLength">6</param> <param name="maxLength">20</param> <message>密码长度应该在${minLength} ~ ${maxLength}之间</message> </field-validator> </field> <field name="repassword"> <field-validator type="requiredstring" short-circuit="true"> <param name="trim">true</param> <message>重复密码不能为空</message> </field-validator> </field> <field name="email"> <field-validator type="requiredstring" short-circuit="true"> <param name="trim">true</param> <message>邮箱不能为空</message> </field-validator> <field-validator type="email"> <message>邮箱不正确</message> </field-validator> </field> <field name="validate"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>验证码不能为空</message> </field-validator> </field> </validators>
注册成功:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>注册成功</title> <SCRIPT type="text/javascript"> var secs = 5;//倒计时的秒数 var URL; function Load(url) { URL = url; for(var i = secs; i >= 0; i--) { window.setTimeout('doUpdate(' +i+ ')',(secs - i)*1000); } } function doUpdate(num) { document.getElementById('ShowDiv').innerHTML = '将在' + num +'秒后自动跳转到登录页面'; if(num == 0) { windows.location = URL; } } </SCRIPT> </head> <body> <center> <h1> <font color="red" align="center">恭喜您,注册成功!</font> </h1> <br/> <div id="ShowDiv"> <script type="text/javascript"> Load("http://localhost:8080/Struts 2login/login.jsp"); </script> <s:a href="/login.jsp"> <font color="blue"> <h5>手动登录?</h5> </font> </s:a> </div> </center> </body> </html>
附上其余代码:
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>LoginDemo1</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.i18n.encoding" value="utf-8" /> <package name="Struts 2login" namespace="/" extends="struts-default"> <action name="register" class="action.RegisterAction"> <result name="success">/register_success.jsp</result> <result name="input">/register.jsp</result> </action> <action name="login" class="action.LoginAction"> <result name="success" type="redirect"> /login_success.jsp </result> <result name="input"> /login.jsp </result> </action> <action name="imageAction" class="action.ImageAction"> <result type="stream"> <param name="contentType">image/jpeg</param> <param name="inputName">inputStream</param> </result> </action> </package> </struts>
entity:
package biz; public class Users { private int userid; private String username; private String password; private int sex; private String email; public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
DbConnection
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DbConnection { static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() { Connection con = null; String url = "jdbc:mysql://127.0.0.1:3306/test"; String userName = "root"; String pwd = "root"; try { con = DriverManager.getConnection(url, userName, pwd); } catch (SQLException e) { e.printStackTrace(); } return con; } public static void closeConnection(ResultSet rs, PreparedStatement ps, Connection conn) { if(rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
DbService
package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import biz.Users; public class DbService { public void addUser(Users user) { Connection connection = DbConnection.getConnection(); PreparedStatement ps = null; String sql = "insert into users (username,password,sex,email) values(?,?,?,?)"; try { ps = connection.prepareStatement(sql); ps.setString(1, user.getUsername()); ps.setString(2, user.getPassword()); ps.setInt(3, user.getSex()); ps.setString(4, user.getEmail()); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public Users hasUser(String username, String password) { Users user = new Users(); Connection connection = DbConnection.getConnection(); PreparedStatement ps = null; ResultSet rs = null; String sql = "select * from users where username=? and password=?"; try { ps = connection.prepareStatement(sql); ps.setString(1, username); ps.setString(2, password); rs = ps.executeQuery(); if(rs.next()) { user.setPassword(rs.getString("password")); user.setUsername(rs.getString("username")); user.setSex(rs.getInt("sex")); user.setEmail(rs.getString("email")); user.setUserid(rs.getInt("user_id")); } } catch (SQLException e) { e.printStackTrace(); } finally { DbConnection.closeConnection(rs, ps, connection); } return user; } public boolean hasSameName(String username) { String name = null; Connection connection = DbConnection.getConnection(); PreparedStatement ps = null; ResultSet rs = null; String sql = "select * from users where username=?"; try { ps = connection.prepareStatement(sql); ps.setString(1, username); rs = ps.executeQuery(); if(rs.next()) { name = rs.getString("username"); if(name.equals(username)) { return true; } else { return false; } } else { return false; } } catch (SQLException e) { e.printStackTrace(); } finally { DbConnection.closeConnection(rs, ps, connection); } return false; } }