这是一个struts学习的入门实例,用一个比较简单的猜数游戏来实现struts2的MVC三层结构的设计思想,对于学
习Struts2的初学者来说,是一个很不错的练习实例。
1、数据实体访问层DAO
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import util.DBConnection;
import entity.Players;
/**
* 数据访问类:主要实现对数据的访问换个操作
* @author niliang
*
*/
public class DaoGuess {
/**
* 该方法实现注册用户
* @param p Players对象
* @throws Exception
*/
public void add(Players p) throws Exception {
String sql = "insert into guess_user (name,password,times) values(?,?,?)";
Connection conn = DBConnection.getConnection();
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, p.getName());
pst.setString(2, p.getPwd());
pst.setInt(3, p.getScore());
pst.executeUpdate();
DBConnection.close(conn);
}
/**
* 该方法实现显示所有已注册的Players对象信息
* @return Players类型的List集合
* @throws Exception
*/
public List<Players> findAll() throws Exception {
String sql = "select * from guess_user order by times";
List<Players> persons = new ArrayList<Players>();
Connection cn = DBConnection.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = cn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
Players p = new Players();
p.setId(rs.getInt(1));
p.setName(rs.getString(2));
p.setPwd(rs.getString(3));
p.setScore(rs.getInt(4));
persons.add(p);
}
} catch (SQLException e) {
e.printStackTrace();
}
DBConnection.close(rs, ps, cn);
return persons;
}
/**
* 该方法根据指定name查询Players对象信息
* @param name 玩家帐号
* @return 返回一个Players对象
* @throws Exception
*/
public Players find(String name) throws Exception {
Players p = null;
String sql = "select * from guess_user where name=?";
Connection conn = DBConnection.getConnection();
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, name);
ResultSet rs = pst.executeQuery();
if(rs.next()){
p=new Players();
p.setId(rs.getInt(1));
p.setName(rs.getString(2));
p.setPwd(rs.getString(3));
p.setScore(rs.getInt(4));
}
DBConnection.close(conn);
return p;
}
/**
* 该方法实现更新数据
* @param times 玩家猜数完成的次数
* @param id 玩家编号
* @throws Exception
*/
public void update(int times,int id) throws Exception{
String sql = "update guess_user set times=? where id=?";
Connection conn = DBConnection.getConnection();
PreparedStatement pst = conn.prepareStatement(sql);
pst.setInt(1,times);
pst.setInt(2,id);
pst.executeUpdate();
DBConnection.close(conn);
}
}
2.实体类POJO
package entity;
/**
* 实体数据类:Players对象
* @author niliang
*
*/
public class Players {
/**
*Players对象的基本属性信息
*/
private int id;
private String name;
private String pwd;
private int score=100;//默认值为100
/**
* 属性Id的get()方法
* @return
*/
public int getId() {
return id;
}
/**
* 属性Id的set()方法
* @param id
*/
public void setId(int id) {
this.id = id;
}
/**
* 属性Name的get()方法
* @return
*/
public String getName() {
return name;
}
/**
* 属性Name的set()方法
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 属性Pwd的get()方法
* @return
*/
public String getPwd() {
return pwd;
}
/**
* 属性Pwd的set()方法
* @param pwd
*/
public void setPwd(String pwd) {
this.pwd = pwd;
}
/**
* 属性Score的get()方法
* @return
*/
public int getScore() {
return score;
}
/**
* 属性Score的set()方法
* @param score
*/
public void setScore(int score) {
this.score = score;
}
}
/******************游戏信息实体类*******************************/
package game;
/**
* 实体数据类:GameInfo游戏信息
* @author niliang
*
*/
public class GameInfo {
private int times;
private int answer;
private boolean success;
private String msg;
private String player;
/**
* 属性Player的get()方法
* @return
*/
public String getPlayer() {
return player;
}
/**
* 属性Player的set()方法
* @param player
*/
public void setPlayer(String player) {
this.player = player;
}
/**
* 属性Msg的get()方法
* @return
*/
public String getMsg() {
return msg;
}
/**
* 属性Msg的set()方法
* @param msg
*/
public void setMsg(String msg) {
this.msg = msg;
}
/**
* 属性Sucess的get()方法
* @return
*/
public boolean isSuccess() {
return success;
}
/**
* 属性Success的set()方法
* @param success
*/
public void setSuccess(boolean success) {
this.success = success;
}
/**
* 属性Times的get()方法
* @return
*/
public int getTimes() {
return times;
}
/**
* 属性Times的set()方法
* @param times
*/
public void setTimes(int times) {
this.times = times;
}
/**
* 属性Answer的get()方法
* @return
*/
public int getAnswer() {
return answer;
}
/**
* 属性Anwser的set()方法
* @param answer
*/
public void setAnswer(int answer) {
this.answer = answer;
}
}
3猜数游戏业务的实现
package game;
import java.util.Random;
/**
* 业务逻辑:实现猜数游戏的业务逻辑
* @author niliang
*
*/
public class GuessNumber {
/**
* 该方法实现猜数游戏
* @param guessNum 用户输入的数字
* @param info 输出的提示消息
*/
public void guess(int guessNum,GameInfo info){
info.setTimes(info.getTimes()+1);
if(guessNum == info.getAnswer()){
info.setSuccess(true);
info.setMsg("(O-^_^-O)恭喜你,你当前用了"+info.getTimes()+"次猜中!!!");
}else if(guessNum<info.getAnswer()){
info.setMsg("^_^你猜的数小了,再大点吧");
}else{
info.setMsg("^_^你猜的数大了,再小点吧");
}
}
/**
* 该方法实现重置游戏
* @param info
*/
public void reset(GameInfo info){
Random random=new Random();
int answer=random.nextInt()%100;
answer=Math.abs(answer)+1;
System.out.println("random:"+answer);
info.setAnswer(answer);
info.setTimes(0);
info.setSuccess(false);
info.setMsg("");
}
}
4.基本登陆注册的action
package game;
import java.util.Random;
/**
* 业务逻辑:实现猜数游戏的业务逻辑
* @author niliang
*
*/
public class GuessNumber {
/**
* 该方法实现猜数游戏
* @param guessNum 用户输入的数字
* @param info 输出的提示消息
*/
public void guess(int guessNum,GameInfo info){
info.setTimes(info.getTimes()+1);
if(guessNum == info.getAnswer()){
info.setSuccess(true);
info.setMsg("(O-^_^-O)恭喜你,你当前用了"+info.getTimes()+"次猜中!!!");
}else if(guessNum<info.getAnswer()){
info.setMsg("^_^你猜的数小了,再大点吧");
}else{
info.setMsg("^_^你猜的数大了,再小点吧");
}
}
/**
* 该方法实现重置游戏
* @param info
*/
public void reset(GameInfo info){
Random random=new Random();
int answer=random.nextInt()%100;
answer=Math.abs(answer)+1;
System.out.println("random:"+answer);
info.setAnswer(answer);
info.setTimes(0);
info.setSuccess(false);
info.setMsg("");
}
}
package action;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import entity.Players;
/**
* 拦截器:登录检查
* @author niliang
*
*/
public class LoginCheck extends AbstractInterceptor{
/**
*
*/
private static final long serialVersionUID = 2490404583704112520L;
@Override
/**
* 重写intercept方法,执行登录检查
*/
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext ac=invocation.getInvocationContext();
Map<String,Object> session=ac.getSession();
Players user=(Players)session.get("user");
if(user==null){
return "login";
}else{
return invocation.invoke();
}
}
}
//
package action;
import java.util.List;
import dao.DaoGuess;
import entity.Players;
public class Option {
/**
* 属性玩家列表集合
*/
List<Players> list;
/**
* 属性list的get()方法
* @return 返回Players类型的集合
*/
public List<Players> getList() {
return list;
}
/**
* 属性list的set()方法
* @param list
*/
public void setList(List<Players> list) {
this.list = list;
}
/**
* 该方法显示所有用户
* @return
*/
public String execute(){
DaoGuess dao=new DaoGuess();
try {
list=dao.findAll();
return "show";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
}
package action;
import org.apache.struts2.ServletActionContext;
import dao.DaoGuess;
import entity.Players;
/**
* 注册玩家的Action
* @author niliang
*
*/
public class RegistAction {
/**
* 属性Players对象
*/
private Players p;
/**
* 属性 p的get()方法
* @return 返回一个Players对象
*/
public Players getP() {
return p;
}
/**
* 属性 p的set()方法
* @param p
*/
public void setP(Players p) {
this.p = p;
}
DaoGuess dao=new DaoGuess();
/**
* 该方法执行注册Action
* @return
*/
public String execute(){
try {
Players player=dao.find(p.getName());
//判断玩家是否已经注册
if(player!=null){
ServletActionContext.getRequest().setAttribute("reg_error", "帐号已存在");
return "wrong";
}
//保存
dao.add(p);
return "add";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
}
5Struts2的配置文件struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<constant name="struts.action.extension" value="do"/>
<package name="guessGame" extends="struts-default">
<!-- 登录拦截 -->
<interceptors>
<interceptor name="logincheck" class="action.LoginCheck"/>
<interceptor-stack name="demoStack">
<interceptor-ref name="logincheck"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<!-- 定义全局的Result -->
<global-results>
<result name="error">/error.jsp</result>
<result name="login">/login.jsp</result>
</global-results>
<!-- 登录 -->
<action name="login" class="action.Login">
<result name="success" type="redirect">/menu.jsp</result>
<result name="exit" type="redirect">/login.jsp</result>
</action>
<!-- 注册 -->
<action name="regist" class="action.RegistAction">
<result name="add" type="redirect">/login.jsp</result>
<result name="wrong">/add_player.jsp</result>
</action>
<action name="guess" class="action.GuessAction">
<interceptor-ref name="demoStack"/>
<result name="success">/success.jsp</result>
<result name="wrong">/guess.jsp</result>
<result name="numerror">guess.jsp</result>
<result name="init" type="redirect">/guess.jsp</result>
</action>
<action name="option" class="action.Option">
<interceptor-ref name="demoStack"/>
<result name="show">/showInfo.jsp</result>
</action>
</package>
</struts>
当然这里还有一个连接数据库的连接池的类(DBConnection.java)就没有列出来,读者朋友们可以自己加上。
Struts2实现猜数小游戏
最新推荐文章于 2020-03-26 20:02:27 发布