login.jsp
<%@ 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript"><!--
function reloadValidate(image){
alert("hello");
image.src = "generateValidateCode.action?" + Math.random();
}
// -->
</script>
</head>
<body>
<s:form action="Login" method="post">
<table>
<tr>
<td><s:textfield name="userName" label="用户名:"></s:textfield></td>
</tr>
<tr>
<td><s:password name="password" label="密码:"></s:password></td>
</tr>
<tr>
<td>验证码(区分大小写):<input name="validateCode"><img onclick="reloadValidate(this);"
src="generateValidateCode.action?<%= Math.random() %>>"></td>
</tr>
<s:submit name="submit"/>
</table>
</s:form>
</body>
</html>
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>
<package name="default" namespace="/" extends="struts-default">
<!-- index页面的跳转到login.jsp
<action name="Start">
<result>/Login.jsp</result>
</action> -->
<!-- 登陆页面的action -->
<action name="Login" class="co.nttdatatj.liusk.LoginAction">
<result name="SUCCESS">/Display.jsp</result>
</action>
<!-- 验证码的action -->
<action name="generateValidateCode" class="co.nttdatatj.liusk.ValidateCodeAction">
<result type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">inputStream</param>
</result>
</action>
</package>
</struts>
ValidateCodeAction.java
package co.nttdatatj.liusk;
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.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import org.apache.struts2.ServletActionContext;
/**
* @author liusk
*
*/
public class ValidateCodeAction {
private ByteArrayInputStream inputStream;
/**
* @return inputStream
*/
public ByteArrayInputStream getInputStream() {
return inputStream;
}
/**
* @param inputStream 設定する inputStream
*/
public void setInputStream(ByteArrayInputStream inputStream) {
this.inputStream = inputStream;
}
public String execute() {
try {
//通过setInputStream获得图片
this.setInputStream(generateImage());
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
//得到图片
private ByteArrayInputStream generateImage() throws IOException{
BufferedImage image = new BufferedImage(100,20,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 100, 20);
//背景
drawbg(g);
//编码颜色
drawValidateCode(g);
ByteArrayInputStream input = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(image,"JPEG",bos);
byte [] buf = bos.toByteArray();
input = new ByteArrayInputStream(buf);
return input;
}
/**
* backGround Draw
*/
private void drawbg(Graphics g) {
Random rand = new Random();
int randx;
int randy;
for (int i = 0; i < rand.nextInt(100) + 500; i++) {
g.setColor(new Color(rand.nextInt(255), rand.nextInt(255), rand
.nextInt(255)));
randx = rand.nextInt(100);
randy = rand.nextInt(20);
g.drawLine(randx, randy, randx, randy);
}
}
/**
* code draw
*/
private void drawValidateCode(Graphics g) {
String code = generateCode();
Random rand = new Random();
int x = 0;
Font font = new Font("Times New Roman", Font.PLAIN, 18);
g.setFont(font);
for (int i = 0; i < code.length(); i++) {
int y = 20 - rand.nextInt(4);
g.setColor(new Color(rand.nextInt(150), rand.nextInt(150), rand
.nextInt(150)));
g.drawString(code.substring(i, i + 1), x, y);
x += 20;
}
}
/**
* code generate
*/
private String generateCode() {
Random rand = new Random();
StringBuffer sbr = new StringBuffer(
"ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789");
int codeLen = 3;
StringBuffer codeSbr = new StringBuffer();
for (int i = 0; i < codeLen; i++) {
int select = rand.nextInt(sbr.length());
codeSbr.append(sbr.charAt(select));
sbr.deleteCharAt(select);
}
ServletActionContext.getRequest().getSession().setAttribute("ValidateCode",codeSbr.toString());
return codeSbr.toString();
}
}
LoginAction.java
package co.nttdatatj.liusk;
import org.apache.struts2.ServletActionContext;
public class LoginAction {
private String userName;
private String password;
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getPassword() {
return password;
}
public String getUserName() {
return userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String execute() {
/*if ("liusk".equals(this.getUserName())) {
message = "Login success!";
} else {
message = "Invalid userName!";
} */
String inputValidateCode = ServletActionContext.getRequest().getParameter("validateCode");
String serverValidateCode = ServletActionContext.getRequest().getSession().getAttribute("ValidateCode").toString();
if (!serverValidateCode.equals(inputValidateCode)) {
message = "Validate Code error!";
}
return "SUCCESS";
}
}
Display.jsp
<%@ 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<s:property value="message"/><br>
welcome to me page:<s:property value="userName"/>
</body>
</html>
注意web。xml
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>