Struts2實現登陸功能(驗證碼校驗)
1.實驗名稱
熟悉Struts2核心文件
2.實驗目的
(1)熟悉Struts2的配置文件web.xml和struts.xml。
(2)熟悉如何書寫用戶定義的控制器。
3.實驗內容
實現如下頁面中登陸的功能。
要求:
管理員登錄後跳到管理員登陸成功的頁面
普通用戶登錄後跳到普通用戶登陸成功的頁面
登錄時用戶名密碼輸入錯跳到出錯頁
註冊和登錄時用戶名,密碼沒有輸入時跳到登陸頁,並在登陸頁上顯示校驗失敗的相關提示
4.文件描述:
ChrUser.java:類中封裝username,password,type,check等屬性及其getter(),setter()方法
CreateImageAction.java:隨機生成驗證碼的Action,其中包含圖片生成過程以及設置瀏覽器緩存的方法。將生成的隨機數放到session中,然後頁面提交驗證隨機數。
LoginAction.java:接收登陸表單頁提交的數據,以及將各類錯誤信息放入session
struts.xml:struts配置文件
login.jsp:登錄頁,包括用戶名,密碼,用戶類型以及驗證碼的顯示與刷新
welcome.jsp:登錄用戶歡迎頁,可顯示用戶類型與用戶名
5.實驗源代碼
- ChrUser.java
public class ChrUser {
private String username;
private String password;
private String type;
private String checkCode;
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 getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCheckCode() {
return checkCode;
}
public void setCheckCode(String check) {
this.checkCode = checkCode;
}
}
- CreateImageAction.java
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.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class CreateImageAction extends ActionSupport{
private ByteArrayInputStream inputStream;
private static int WIDTH = 60;
private static int HEIGHT = 20;
public ByteArrayInputStream getInputStream()
{
return inputStream;
}
public void setInputStream(ByteArrayInputStream inputStream)
{
this.inputStream = inputStream;
}
private static String createRandom()
{
String str = "0123456789qwertyuiopasdfghjklzxcvbnm";
char[] rands = new char[4];
Random random = new Random();
for (int i = 0; i < 4; i++)
{
rands[i] = str.charAt(random.nextInt(36));
}
return new String(rands);
}
private void drawBackground(Graphics g)
{
// 畫背景
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, WIDTH, HEIGHT);
// 隨機產生 120 個干擾點
for (int i = 0; i < 120; i++)
{ int x = (int) (Math.random() * WIDTH);
int y = (int) (Math.random() * HEIGHT);
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
g.setColor(new Color(red, green, blue));
g.drawOval(x, y, 1, 0);
}
}
private void drawRands(Graphics g, String rands)
{ g.setColor(Color.BLACK);
g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 18));
// 在不同的高度上輸出驗證碼的每個字符
g.drawString("" + rands.charAt(0), 1, 17);
g.drawString("" + rands.charAt(1), 16, 15);
g.drawString("" + rands.charAt(2), 31, 18);
g.drawString("" + rands.charAt(3), 46, 16);
System.out.println(rands);
}
public String execute() throws Exception
{ HttpServletResponse response = ServletActionContext.getResponse();
// 設置瀏覽器不要緩存此圖片
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
String rands = createRandom();
BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// 產生圖像
drawBackground(g);
drawRands(g, rands);
// 結束圖像 的繪製 過程, 完成圖像
g.dispose();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpeg", outputStream);
ByteArrayInputStream input = new ByteArrayInputStream(outputStream
.toByteArray());
this.setInputStream(input);
HttpSession session =ServletActionContext.getRequest().getSession();
session.setAttribute("checkCode", rands);
input.close();
outputStream.close();
return SUCCESS;
}
}
- LoginAction.java
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import nuc.sw.User.chrUser;
public class LoginAction extends ActionSupport{
private chrUser user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String execute() throws Exception
{
return SUCCESS;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
//接收登陸表單頁提交的數據
if(username.equals("程浩然")&&password.equals("123")) {
ActionContext.getContext().getSession().put("user",username);
ActionContext.getContext().getSession().put("type",type);
return SUCCESS;
}
else {
ActionContext.getContext().getSession().put("error","用戶名或密碼錯誤");
return ERROR;
}
}
@Override
public void validate()
{
HttpSession session = ServletActionContext.getRequest().getSession();
String checkCode2 = (String)session.getAttribute("checkCode"); if(!checkCode.equals(checkCode2)){
addFieldError(checkCode, "輸入的驗證碼不正確,請重新輸入");
}
if(user.getUsername()==null||user.getUsername().trim().equals("")){
this.addFieldError("usererror", "用戶名不能爲空");
}
if(user.getPassword()==null||user.getPassword().trim().equals("")){
this.addFieldError("passerror", "密碼不能爲空");
}
}
}
- struts.xml
<struts>
<package name="user" namespace="/" extends="struts-default">
<action name="LoginAction" class="nuc.sw.action.LoginAction">
<result name="success">
/welcome.jsp
</result>
<result name="error">
/login.jsp
</result>
<result name="input">
/login.jsp
</result>
</action>
<action name="createImageAction" class="nuc.sw.action.CreateImageAction">
<result name="success" type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">inputStream</param>
</result>
</action>
</package>
</struts>
- 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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function refresh() {
//IE存在緩存,需要new Date()實現更換路徑的作用
document.getElementById("image").src="createImageAction.action?+Math.random()"+new Date();
}
</script>
<title>登錄頁</title>
</head>
<body>
<font color="red">${sessionScope.error}</font>
<font color="red"><s:fielderror></s:fielderror></font>
<form action="LoginAction" method="post">
用戶名:<input type="text" name="username"><br>
密 碼:<input type="text" name="password"><br>
用戶類型:<select name="type">
<option>普通用戶</option>
<option>管理員</option>
</select><br>
驗證碼:<s:textfield name="checkCode"></s:textfield>
<img src="image" onclick="refresh" title="看不清?換一個"/><br>
<s:actionerror cssStyle="color:red"/>
<input type="submit" value="登陸">
</form>
</body>
</html>
- welcome.jsp
<%@ 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>
歡迎${session.type}${session.user}登陸!
</body>
</html>