struts2框架,action完整增删改查,easyui实现管理模块,视频和个人笔记【诗书画唱】
CTRL+F:例子,视频和个人笔记
加载下拉框
修改

例子 START
加载下拉框,增删改查的完整例子 START
SQL部分:
select* from game
create table game(
id int primary key auto_increment,
gname varchar(100),
gtype varchar(100),
Gcomp varchar(100),
gyear varchar(100)
);
drop table game
insert into game(gname,
gtype,
Gcomp,
gyear ) values("游戏名1","游戏类型1","游戏公司1","游戏发行时间1");
insert into game(gname,
gtype,
Gcomp,
gyear ) values("游戏名2","游戏类型2","游戏公司2","游戏发行时间2");
insert into game(gname,
gtype,
Gcomp,
gyear ) values("游戏名3","游戏类型3","游戏公司3","游戏发行时间3");
insert into game(gname,
gtype,
Gcomp,
gyear ) values("游戏名4","游戏类型4","游戏公司4","游戏发行时间4");


package com.SSHC.action;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.SSHC.bean.Game;
import com.SSHC.dao.GameDao;
public class GameAction {
private Map<String,Object>map = new HashMap<String,Object>();
private GameDao gameDao = new GameDao();
private Game g;
private InputStream ins;
//添加分页属性
private Integer rows;//每页记录条数
private Integer page;//页码数
public Map<String, Object> getMap() {
return map;
}
public void setMap(Map<String, Object> map) {
this.map = map;
}
public GameDao getGameDao() {
return gameDao;
}
public void setGameDao(GameDao gameDao) {
this.gameDao = gameDao;
}
public Integer getRows() {
return rows;
}
public void setRows(Integer rows) {
this.rows = rows;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Game getG() {
return g;
}
public void setG(Game g) {
this.g = g;
}
public InputStream getIns() {
return ins;
}
public void setIns(InputStream ins) {
this.ins = ins;
}
public String loadAll(){
System.out.println("每页显示" + rows + "条数据");
System.out.println("当前显示第" + page + "页的数据");
g = new Game();
g.setPage(page);
g.setRows(rows);
List<Game>list = gameDao.selectByPage(g);
Integer total = gameDao.total();
map.put("rows", list);
map.put("total", total);
return "success";
}
public String addGame(){
try {
Integer count = gameDao.add(g);
//{ct:1}
ServletActionContext.getResponse()
.getWriter().write("{\"ct\":" + count + "}");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String deleteGame(){
try {
Integer count = gameDao.delete(g.getId());
//{ct:1}
ServletActionContext.getResponse()
.getWriter().write("{\"ct\":" + count + "}");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//加载游戏类型下拉框中的数据
public String loadSel() throws UnsupportedEncodingException{
//String jsonStr = "[{\"id\":\"1\",\"gtype\":\"RPG\"}]";
StringBuilder jsonStr = new StringBuilder("[");
List<String>list = gameDao.getAllType();
String dot = "";
for(String s : list) {
jsonStr.append(dot);
jsonStr.append("{\"id\":\"" + s + "\",\"gtype\":\""
+ s + "\"}");
dot = ",";
}
jsonStr.append("]");
ins = new ByteArrayInputStream(jsonStr.toString().getBytes("utf-8"));
return "success";
}
public String toEdit(){
g = gameDao.selectById(g.getId());
return "success";
}
public String editGame(){
try {
Integer count = gameDao.update(g);
//{ct:1}
ServletActionContext.getResponse()
.getWriter().write("{\"ct\":" + count + "}");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}


package com.SSHC.bean;
public class Game {
private Integer id;
private String gname;
private String gtype;
private String Gcomp;
private String gyear;
//分页属性
private Integer page;
private Integer rows;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGname() {
return gname;
}
public void setGname(String gname) {
this.gname = gname;
}
public String getGtype() {
return gtype;
}
public void setGtype(String gtype) {
this.gtype = gtype;
}
public String getGcomp() {
return Gcomp;
}
public void setGcomp(String Gcomp) {
this.Gcomp = Gcomp;
}
public String getGyear() {
return gyear;
}
public void setGyear(String gyear) {
this.gyear = gyear;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getRows() {
return rows;
}
public void setRows(Integer rows) {
this.rows = rows;
}
}


package com.SSHC.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 com.SSHC.bean.Game;
import com.SSHC.util.DbUtil;
public class GameDao {
public List<Game>selectByPage(Game game){
String sql = "select * from game limit ?,?";
List<Game>list = new ArrayList<Game>();
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
conn = DbUtil.getConn();
pstm = conn.prepareStatement(sql);
Integer page = game.getPage();
Integer rows = game.getRows();
//隐藏的记录条数
Integer hideCount = (page - 1) * rows;
pstm.setInt(1, hideCount);
pstm.setInt(2, rows);
rs = pstm .executeQuery();
while(rs.next()){
Game g = new Game();
g.setId(rs.getInt("id"));
g.setGname(rs.getString("gname"));
g.setGtype(rs.getString("gtype"));
g.setGcomp(rs.getString("Gcomp"));
g.setGyear(rs.getString("gyear"));
list.add(g);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DbUtil.close(rs, pstm, conn);
}
return list;
}
public Integer total(){
String sql = "select count(*) ct from game";
Integer count = 0;
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
conn = DbUtil.getConn();
pstm = conn.prepareStatement(sql);
rs = pstm.executeQuery();
if(rs.next()) {
count = rs.getInt("ct");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DbUtil.close(rs, pstm, conn);
}
return count;
}
public Integer add(Game g){
String sql = "insert into game "
+ "(gname,gtype,Gcomp,gyear) values(?,?,?,?)";
Connection conn = null;
PreparedStatement pstm = null;
Integer count = 0;
try {
conn = DbUtil.getConn();
pstm = conn.prepareStatement(sql);
pstm.setString(1, g.getGname());
pstm.setString(2, g.getGtype());
pstm.setString(3, g.getGcomp());
pstm.setString(4, g.getGyear());
count = pstm.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count;
}
public Integer delete(Integer id){
String sql = "delete from game where id = ?";
Connection conn = null;
PreparedStatement pstm = null;
Integer count = 0;
try {
conn = DbUtil.getConn();
pstm = conn.prepareStatement(sql);
pstm.setInt(1, id);
count = pstm.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count;
}
public List<String> getAllType(){
String sql = "select distinct gtype from game";
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
List<String>list = new ArrayList<String>();
try {
conn = DbUtil.getConn();
pstm = conn.prepareStatement(sql);
rs = pstm.executeQuery();
while(rs.next()) {
list.add(rs.getString("gtype"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public Game selectById(Integer id){
String sql = "select * from game where id = ?";
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
Game g = new Game();
try {
conn = DbUtil.getConn();
pstm = conn.prepareStatement(sql);
pstm.setInt(1, id);
rs = pstm.executeQuery();
if(rs.next()) {
g.setId(id);
g.setGname(rs.getString("gname"));
g.setGtype(rs.getString("gtype"));
g.setGcomp(rs.getString("Gcomp"));
g.setGyear(rs.getString("gyear"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return g;
}
public Integer update(Game g){
String sql = "update game set gname = ?,gtype = ?,Gcomp = ?,gyear = ? where id = ?";
Connection conn = null;
PreparedStatement pstm = null;
Integer count = 0;
try {
conn = DbUtil.getConn();
pstm = conn.prepareStatement(sql);
pstm.setString(1, g.getGname());
pstm.setString(2, g.getGtype());
pstm.setString(3, g.getGcomp());
pstm.setString(4, g.getGyear());
pstm.setInt(5, g.getId());
count = pstm.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count;
}
}


package com.SSHC.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
public class DbUtil {
private static String driverName;
private static String url;
private static String user;
private static String pwd;
static {
//读取properties文件
Properties prop = new Properties();
//将db.properties文件读取到内存中去
InputStream is = DbUtil.class.getClassLoader()
.getResourceAsStream("db.properties");
//加载内容
try {
prop.load(is);
//读取内容
driverName = prop.getProperty("drivername");
url = prop.getProperty("url");
user = prop.getProperty("username");
pwd = prop.getProperty("password");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//获取数据库连接对象的方法
public static Connection getConn(){
Connection conn = null;
try {
Class.forName(driverName);
conn = DriverManager.getConnection(url,user,pwd);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static void close(ResultSet rs,PreparedStatement pstm
,Connection conn){
try {
if(rs != null) {
rs.close();
}
if(pstm != null) {
pstm.close();
}
if(conn != null) {
conn.close();
}
} catch(Exception e) {
e.printStackTrace();
}
}
}


drivername=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/firstjsp?useUnicode=true&characterEncoding=UTF-8
username=root
password=root


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation
//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="my" namespace="/gm" extends="json-default">
<action name="ldAc" class="com.SSHC.action.GameAction"
method="loadData">
<result type="stream">
<param name="contentType">text/plain</param>
<!-- action返回的字符串的内容取自GameAction的哪个属性 -->
<param name="inputName">ins</param>
</result>
</action>
<action name="ldAllAc" class="com.SSHC.action.GameAction"
method="loadAll">
<result type="json">
<param name="root">map</param>
<param name="contentType">text/html</param>
</result>
</action>
<action name="addAc" class="com.SSHC.action.GameAction"
method="addGame">
</action>
<action name="deleteAc" class="com.SSHC.action.GameAction"
method="deleteGame">
</action>
<action name="loadTypeAc" class="com.SSHC.action.GameAction"
method="loadSel">
<result type="stream">
<param name="contentType">text/plain</param>
<param name="inputName">ins</param>
</result>
</action>
<action name="toEditAc" class="com.SSHC.action.GameAction"
method="toEdit">
<result>/edit.jsp</result>
</action>
<action name="editAc" class="com.SSHC.action.GameAction"
method="editGame">
</action>
</package>
</struts>


<?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>J190802</display-name>
<!-- struts2框架的配置 -->
<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.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>
</web-app>

<%@ page language="java" contentType="text/html; charset=UTF-8" 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 hreff="<%=basePath%>">
<title></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">
</head>
<body>
<h1 align="center">新增游戏</h1>
<form id="addFrm" action="" method="post">
<table align="center">
<tr>
<td>游戏名称:</td>
<td>
<input name="g.gname" class="easyui-validatebox"
data-options="required:true"
validType="length[6,30]"
invalidMessage="游戏名称的长度必须在6到30位之间"
style="width:180px;" />
</td>
</tr>
<tr>
<td>游戏类型:</td>
<td>
<input name="g.gtype" class="easyui-combobox"
style="width:180px;"
data-options="valueField:'id',textField:'gtype',
panelHeight:'auto',editable:false,url:'gm/loadTypeAc.action'" />
</td>
</tr>
<tr>
<td>游戏公司:</td>
<td>
<input name="g.Gcomp" class="easyui-validatebox"
validType="length[4,30]"
invalidMessage="游戏公司的长度必须在4到30位之间"
style="width:180px;" />
</td>
</tr>
<tr>
<td>游戏年份:</td>
<td>
<input name="g.gyear" class="easyui-numberbox"
data-options="min:1000,max:9999"
style="width:180px;" />
</td>
</tr>
<tr>
<td colspan="2" align="center">
<a hreff="javascript:saveGame();" class="easyui-linkbutton"
data-options="iconCls:'icon-save'">保存</a>
<a hreff="javascript:clsWin();" class="easyui-linkbutton"
data-options="iconCls:'icon-cut'">取消</a>
</td>
</tr>
</table>
</form>
</body>
</html>


{"total":2,"rows":[{"id":1,"gname":"WANGZHERONGYI","gtype":"MOB","Gcomp":"TENCENT","gyear":2010}]}

<%@ page language="java" contentType="text/html; charset=UTF-8" 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 hreff="<%=basePath%>">
<title></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">
</head>
<body>
<h1 align="center">修改游戏</h1>
<form id="editFrm" action="" method="post">
<!-- 选中的游戏的id存放在隐藏表单域 -->
<input type="hidden" name="g.id" value="${g.id }"/>
<table align="center">
<tr>
<td>游戏名称:</td>
<td>
<input name="g.gname" class="easyui-validatebox"
data-options="required:true"
validType="length[2,30]" value="${g.gname }"
invalidMessage="游戏名称的长度必须在6到30位之间"
style="width:180px;" />
</td>
</tr>
<tr>
<td>游戏类型:</td>
<td>
<input name="g.gtype" class="easyui-combobox"
style="width:180px;" value="${g.gtype}"
data-options="valueField:'id',textField:'gtype',
panelHeight:'auto',editable:false,url:'gm/loadTypeAc.action'" />
</td>
</tr>
<tr>
<td>游戏公司:</td>
<td>
<input name="g.Gcomp" class="easyui-validatebox"
validType="length[2,30]" value="${g.Gcomp }"
invalidMessage="游戏公司的长度必须在4到30位之间"
style="width:180px;" />
</td>
</tr>
<tr>
<td>游戏年份:</td>
<td>
<input name="g.gyear" class="easyui-numberbox"
data-options="min:1000,max:9999" value="${g.gyear }"
style="width:180px;" />
</td>
</tr>
<tr>
<td colspan="2" align="center">
<a hreff="javascript:editGame();" class="easyui-linkbutton"
data-options="iconCls:'icon-save'">保存</a>
<a hreff="javascript:clsWin();" class="easyui-linkbutton"
data-options="iconCls:'icon-cut'">取消</a>
</td>
</tr>
</table>
</form>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=UTF-8" 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 hreff="<%=basePath%>">
<title></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" hreff="css/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" hreff="css/themes/icon.css">
<script type="text/javascript" srcc="js/jquery.min.js"></script>
<script type="text/javascript" srcc="js/jquery.easyui.min.js"></script>
<!-- 语言汉化包 -->
<script type="text/javascript" srcc="js/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript">
function toAdd(){
var url = 'add.jsp';
$('#win').window({
width : 700,//宽度
height : 550,//高度
title : '新增',
hreff : url
});
$('#win').window('open');//打开窗体
}
function toEdit(){
//获取选中的行
var row = $('#dg').datagrid('getSelected');
var id = row.id;
//判断是否选中
if(! row) {
$.messager.alert("提示", "请选要修改的数据", "info");
} else {
var url = 'gm/toEditAc.action?g.id=' + id;
$('#win').window({
width : 700,//宽度
height : 550,//高度
title : '修改',
hreff : url
});
$('#win').window('open');//打开窗体
}
}
function doDelete(){
//获取选中的行
var row = $('#dg').datagrid('getSelected');
var id = row.id;
//判断是否选中
if(! row) {
$.messager.alert("提示", "请选要删除的数据", "info");
} else {
//删除二次确认
$.messager.confirm("提示", "确定删除" + id + "的记录吗?",function(re) {
//re为true就表示点击了确定按钮
//re为false就表示点击了取消按钮
if(re) {
//提交ajax执行删除
$.ajax({
url: 'gm/deleteAc.action',
type: 'POST',
data: {
'g.id': id
},
success: function(data){
var o = JSON.parse(data);
if(o.ct > 0) {
$.messager.alert("提示", "删除成功!", "info");
//刷新datagrid
$('#dg').datagrid('reload');
} else {
$.messager.alert("提示", "删除失败!", "info");
}
}
});
}
});
}
}
function clsWin(){
$('#win').window('close');
}
//提交新增表单(在add.jsp页面调用这个方法)
//通过这种方式提交表单是没有页面跳转
function saveGame(){
//手动提交表单
$('#addFrm').form('submit',{
url: 'gm/addAc',
onSubmit: function(){//表单验证
//this就是指当前的表单
//调用表单验证的方法
var isValid = $(this).form('validate');
//if(!isValid) {
// alert('验证不通过')
//}
return isValid;
},
success: function(data){//表单提交成功以后执行的回调函数
var o = JSON.parse(data);
if(o.ct > 0) {
$.messager.alert("提示", "新增成功", "info");
//刷新datagrid
$('#dg').datagrid('reload');
//关闭窗体
$('#win').window('close');
} else {
$.messager.alert("提示", "新增失败", "info");
}
}
});
}
function editGame(){
$('#editFrm').form('submit',{
url: 'gm/editAc.action',
onSubmit: function(){
var isValid = $(this).form('validate');
return isValid;
},
success: function(data){
var o = JSON.parse(data);
if(o.ct > 0) {
$.messager.alert("提示", "修改成功", "info");
//刷新datagrid
$('#dg').datagrid('reload');
//关闭窗体
$('#win').window('close');
} else {
$.messager.alert("提示", "修改失败", "info");
}
}
});
}
</script>
</head>
<body>
<table id="dg" class="easyui-datagrid" title="游戏管理模块"
style="width:1000px;height:450px"
data-options="singleSelect:true,collapsible:true,
url:'gm/ldAllAc.action',method:'get',pagination:true,
pageList:[3,5,7,10,15],pageSize:5,toolbar:'#tb'">
<thead>
<tr>
<th data-options="field:'id',width:80">游戏ID</th>
<th data-options="field:'gname',width:100">游戏名称</th>
<th data-options="field:'gtype',width:80,align:'right'">游戏类型</th>
<th data-options="field:'Gcomp',width:80,align:'right'">游戏公司</th>
<th data-options="field:'gyear',width:250">游戏年份</th>
</tr>
</thead>
</table>
<!-- 工具栏 -->
<div id="tb" style="padding:5px;height:auto">
<div style="margin-bottom:5px">
<a hreff="javascript:toAdd();" class="easyui-linkbutton"
iconCls="icon-add" plain="true" title="新增"></a>
<a hreff="javascript:toEdit();" class="easyui-linkbutton"
iconCls="icon-edit" plain="true" title="修改"></a>
<a hreff="javascript:doDelete();" class="easyui-linkbutton"
iconCls="icon-remove" plain="true" title="删除"></a>
</div>
</div>
<!-- 弹出窗体 -->
<div id="win" class="easyui-window"
data-options="modal:true,closed:true,iconCls:'icon-save', top: 20,
minimizable: false,maximizable: false,collapsible: false,left: 100">
</div>
</body>
</html>









加载下拉框,增删改查的完整例子 END
例子 END
视频和个人笔记 START



