这几天刚看完struts2,所以用struts2和JDBC做了一个增删改查的小练习,里边也加了国家、省、市的三级联动,也算顺便复习,下边贴代码。
先是Demo的视图
先是配置文件,struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="userAction" class="com.bjsxt.action.UserAction">
<result name="getList" type="redirect">userAction!findAll.action</result>
<result name="list">/list.jsp</result>
<result name="update">/update.jsp</result>
</action>
<action name="locationAction" class="com.bjsxt.action.LocationAction">
<result name="country" type="stream">
<param name="contentType">${contentType}</param>
<!--发送到头信息中 -->
<param name="inputName">is</param>
<!-- inputName指获取文件的来源,一般用于下载中,因为使用了流 -->
<param name="bufferSize">8192</param>
</result>
<result name="province" type="stream">
<param name="contentType">${contentType}</param>
<param name="inputName">is</param>
<param name="bufferSize">8192</param>
</result>
<result name="city" type="stream">
<param name="contentType">${contentType}</param>
<param name="inputName">is</param>
<param name="bufferSize">8192</param>
</result>
</action>
</package>
</struts>
1.dao层,接口BaseDao
public interface BaseDao<Entity> {
/**
* 增加
*/
void add(Entity entity) throws Exception;
/**
* 删除
*
*/
void delete(int id) throws Exception;
/**
* 修改
*/
// Entity update(Entity entity) throws Exception;//错误写法
void update(Entity entity) throws Exception;
/**
* 查询所有值
*/
List<Entity> findAll() throws Exception;
/**
* 按照id查找
*
*/
Entity findById(int id) throws Exception;
}
dao层,LocationDao,这是关于地址的
public interface LocationDao {
List<Country> findAllCountry() throws Exception;
List<Province> findAllProvinceByCountryId(int cid) throws Exception;
List<City> findAllCityByProvinceId(int pid) throws Exception;
}
dao层,UserDao,关于用户的
public interface UserDao extends BaseDao<User>{
//注意此处泛型为User,而不是Entity
}
2.daoimpl,dao的实现层。BaseDaoImpl的,实现增删改查
public class BaseDaoImpl<Entity> implements BaseDao<Entity>{
protected Class clazz;
public BaseDaoImpl() {
ParameterizedType pz = (ParameterizedType) this.getClass().getGenericSuperclass();
clazz = (Class)pz.getActualTypeArguments()[0];
//获得父类的泛型参数的实际类型
}
public void add(Entity entity) throws Exception {
Connection conn = DBUtil.getConn();
String sql = "insert into " + clazz.getSimpleName() + " values(null";//id值为null
Field[] fs = clazz.getDeclaredFields();
for (int i = 1; i < fs.length; i++) {//注意是从1开始
sql += ",?";
}
sql += ")";
PreparedStatement ps = DBUtil.getPs(sql, conn);
for (int i = 1; i < fs.length; i++) {
String methodName = "get" + Character.toUpperCase(fs[i].getName().charAt(0)) +fs[i].getName().substring(1);
Method m = clazz.getDeclaredMethod(methodName);
ps.setObject(i,m.invoke(entity));//将后边的值按照索引i依次添加
}
ps.executeUpdate();
DBUtil.close(ps);
DBUtil.close(conn);
}
public void delete(int id) throws Exception {
Connection conn = DBUtil.getConn();
String sql = "delete from " + clazz.getSimpleName() + " where id = ?" ;
PreparedStatement ps = DBUtil.getPs(sql, conn);
ps.setInt(1, id);
ps.executeUpdate();
DBUtil.close(ps);
DBUtil.close(conn);
}
public void update(Entity entity) throws Exception {
Connection conn = DBUtil.getConn();
String sql = "update " + clazz.getSimpleName() + " set ";
Field[] fs = clazz.getDeclaredFields();
for (int i = 1; i < fs.length; i++) {
sql += fs[i].getName() + " = ?,";//当初这儿少了个“+”,蛋疼无比
}
sql = sql.substring(0,sql.length()-1) + " where id = ?";
// PreparedStatement ps = conn.prepareStatement(sql);//这是错误写法
System.out.println("update方法的sql为" + sql);
PreparedStatement ps = DBUtil.getPs(sql, conn);
for (int i = 1; i < fs.length; i++) {
String methodName = "get" + Character.toUpperCase(fs[i].getName().charAt(0))+ fs[i].getName().substring(1);
Method m = clazz.getDeclaredMethod(methodName);
ps.setObject(i, m.invoke(entity));
}
Method getId = clazz.getDeclaredMethod("getId");
ps.setInt(fs.length,(Integer) getId.invoke(entity));
ps.executeUpdate();
DBUtil.close(ps);
DBUtil.close(conn);
}
@Override
public List<Entity> findAll() throws Exception {
Connection conn = DBUtil.getConn(); //jdbc
String sql = " select * from " + clazz.getSimpleName(); //sql
PreparedStatement ps = DBUtil.getPs(sql,conn);
ResultSet rs = ps.executeQuery();
List<Entity> enList = new ArrayList<Entity>();
while(rs.next()){
Entity en = (Entity)clazz.newInstance();
Field[] fs = clazz.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
String methodName = "set" + Character.toUpperCase(fs[i].getName().charAt(0)) + fs[i].getName().substring(1);
Method m = clazz.getDeclaredMethod(methodName, fs[i].getType());
m.invoke(en, rs.getObject(fs[i].getName()));
}
enList.add(en);
}
DBUtil.close(rs);
DBUtil.close(ps);
DBUtil.close(conn);
return enList;
}
@Override
public Entity findById(int id) throws Exception {
Connection conn = DBUtil.getConn();
String sql = " select * from " + clazz.getSimpleName() + " where id = ? ";
PreparedStatement ps = DBUtil.getPs(sql,conn);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
Entity entity = (Entity)clazz.newInstance();
Field[] fs = clazz.getDeclaredFields();
if(rs.next()){
for(int i = 0 ; i < fs.length ; i++){
String methodName = "set" + Character.toUpperCase(fs[i].getName().charAt(0)) + fs[i].getName().substring(1);
Method m = clazz.getDeclaredMethod(methodName, fs[i].getType());
m.invoke(entity , rs.getObject(fs[i].getName()));
}
}
DBUtil.close(rs);
DBUtil.close(ps);
DBUtil.close(conn);
return entity;
}
}
LocationDaoImpl,关于地址的
public class LocationDaoImpl implements LocationDao{
public List<Country> findAllCountry() throws Exception {
Connection conn = DBUtil.getConn();
String sql = "select cid,cname from country";
PreparedStatement ps = conn.prepareStatement(sql);
List<Country> listcountry = new ArrayList<Country>();
ResultSet rs = ps.executeQuery();
while(rs.next()){
Country c = new Country(rs.getInt("cid"),rs.getString("cname"));
listcountry.add(c);
}
DBUtil.close(rs);
DBUtil.close(ps);
DBUtil.close(conn);
return listcountry;
}
public List<Province> findAllProvinceByCountryId(int cid) throws Exception {
Connection conn = DBUtil.getConn();
String sql = "select pid,pname from province where cid = ?" ;
PreparedStatement ps = conn.prepareStatement(sql);
List<Province> listprovince = new ArrayList<Province>();
ps.setInt(1, cid);//推荐这样的写法
ResultSet rs = ps.executeQuery();
while(rs.next()){
Province p = new Province(rs.getInt("pid"),rs.getString("pname"));
listprovince.add(p);
}
DBUtil.close(rs);
DBUtil.close(ps);
DBUtil.close(conn);
return listprovince;
}
public List<City> findAllCityByProvinceId(int pid) throws Exception {
Connection conn = DBUtil.getConn();
String sql = "select cityid,cityname from city where pid = ?" ;
PreparedStatement ps = conn.prepareStatement(sql);
List<City> listcity = new ArrayList<City>();
ps.setInt(1, pid);//与上同理
ResultSet rs = ps.executeQuery();
while(rs.next()){
City c = new City(rs.getInt("cityid"),rs.getString("cityname"));
listcity.add(c);
}
DBUtil.close(rs);
DBUtil.close(ps);
DBUtil.close(conn);
return listcity;
}
}
UserDaoImpl,用户的
public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao{
//注意该处写法
}
3.action的,先是UserAction
public class UserAction extends ActionSupport{
private UserDao udao = new UserDaoImpl();
private User user;
private List<User> list;//这两个(user和list)必须有get/set方法,其余类似
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<User> getList() {
return list;
}
public void setList(List<User> list) {
this.list = list;
}
/**
* 增加用户
* @throws Exception
*
*/
// public String add(User user) throws Exception{//错误写法,括号不用加User
public String add() throws Exception{
this.udao.add(this.user);
return "getList";
}
/**
* 删除用户
* @throws Exception
*/
public String del() throws Exception{
this.udao.delete(this.id);
return "getList";
}
/**
* 预修改
* @throws Exception
*/
public String preUpdate() throws Exception{
// this.udao.findById(this.user.getId());//写法不完整,必须有this.user,用来存储结果,否则不显示
this.user = this.udao.findById(this.id);
return "update";
}
/**
* 修改
* @throws Exception
*
*/
public String update() throws Exception{
// this.udao.update(this.user.getId());//错误写法
this.udao.update(this.user);
return "getList";
}
/**
* 根据id查找用户也可以,就是要再加一条id属性,再加get/set方法
* @throws Exception
*
*/
// public String findById() throws Exception{
// this.udao.findById(this.user.getId());
// return "";
// }
/**
* 查找所有用户
* @throws Exception
*
*/
public String findAll() throws Exception{
this.list = this.udao.findAll();
return "list";
}
}
LocationAction
public class LocationAction {
private LocationDao ldao = new LocationDaoImpl();
private List<Country> listcountry;
private List<Province> listprovince;
private List<City> listcity;
private int cid;
private int pid;
private String contentType;//为了将java对象转换为json
private InputStream is;//转码
public InputStream getIs() {
return is;
}
public void setIs(InputStream is) {
this.is = is;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public List<Country> getListcountry() {
return listcountry;
}
public void setListcountry(List<Country> listcountry) {
this.listcountry = listcountry;
}
public List<Province> getListprovince() {
return listprovince;
}
public void setListprovince(List<Province> listprovince) {
this.listprovince = listprovince;
}
public List<City> getListcity() {
return listcity;
}
public void setListcity(List<City> listcity) {
this.listcity = listcity;
}
/**
* 查找国家
* @return
* @throws Exception
*/
public String findCountry() throws Exception{
this.contentType = "text/plain;charset=utf-8";//会回应到头信息中,可用firebug查看
this.listcountry = this.ldao.findAllCountry();
Gson gson = new Gson();//这样建立gson即可
String countrystr = gson.toJson(this.listcountry);//将plain对象转换为gson对象
this.is = new ByteArrayInputStream(countrystr.getBytes("utf-8"));//转换编码格式,防止出现乱码
return "country";
}
/**
* 查找省份
* @throws Exception
*
*/
public String findProvince() throws Exception{
this.contentType = "text/plain;charset=utf-8";
this.listprovince = this.ldao.findAllProvinceByCountryId(this.cid);
Gson gson = new Gson();
String provincestr = gson.toJson(this.listprovince);
this.is = new ByteArrayInputStream(provincestr.getBytes("utf-8"));
return "province";
}
/**
* 查找城市
* @throws Exception
*/
public String findCity() throws Exception{
this.contentType = "text/plain;charset=utf-8";
this.listcity = this.ldao.findAllCityByProvinceId(this.pid);
Gson gson = new Gson();
String citystr = gson.toJson(this.listcity);
this.is = new ByteArrayInputStream(citystr.getBytes("utf-8"));
return "city";
}
}
最后再贴一个最重要的,关于实现三级联动的js
<script type="text/javascript">
$(function(){
$.ajax({
type:"post",
url:"locationAction!findCountry.action",
dataType:"json",
success:function(rs){
var c = $("#countryid");//jquery的ajax写法
for ( var i = 0; i < rs.length; i++) {
c.append("<option value=" + rs[i].cid +" >" + rs[i].cname + "</option>");
}
}
})
$("#countryid").change(function(){
var cid = $(this).val();//注意此处的val为获取值得方法,不是属性。括号不能丢
//这儿this的用法也说过很多次了,被哪个函数调用,就指向哪个函数
$.ajax({
type:"post",
//url:"locationAction!findProvince?cid=" + cid,//错误的url写作方式
data:"cid=" + cid,
url:"locationAction!findProvince.action",
dataType:"json",
success:function(rs){
var p = $("#provinceid");//#符号不能丢,否则取不到值
p.children().remove("option[value!=0]");//清空省,就是在换了上一级选项后,下一级全部是符合要求的子选项
var c = $("#cityid");
c.children().remove("option[value!=0]");//清空城市
for ( var i = 0; i < rs.length; i++) {
p.append("<option value=" + rs[i].pid +" >" + rs[i].pname + "</option>");
}
}
})
})
$("#provinceid").change(function(){
var pid = $(this).val();
$.ajax({
type:"post",
data:"pid="+ pid,
dataType:"json",
url:"locationAction!findCity.action",
success:function(rs){
var c = $("#cityid");
c.children().remove("option[value!=0]");
for ( var i = 0; i < rs.length; i++) {
c.append("<option value=" + rs[i].cityid + " >" + rs[i].cityname + "</option>");
}
}
})
})
})
</script>
<body>
<form action="userAction!add.action" method="post" autocomplete="off">
用户名:<input name="user.username" ><br/>
密码:<input name="user.password" type="password"><br/>
籍贯:
<select name="user.cid" id="countryid"><!--注意name属性的写法,其他的项也同理-->
<option value="0">--请选择国家--</option>
</select>
<select name="user.pid" id="provinceid">
<option value="0">--请选择省份--</option>
</select>
<select name="user.cityid" id="cityid">
<option value="0">--请选择城市--</option>
</select>
<br/><br/>
<input type="submit" value="提交" >
<input type="reset" value="重置">
</form>
</body>
再说一下关于属性注入的,前边也提过,
除了要写相应的get/set方法外,要记住,在相应的jsp页面也得写类似于user.name这样的,而不是只写name,否则注入不进去。
其余的代码太多就不贴了,我已经上传到资源空间,有需要的可以去下载。注释写了不少,同时里边也加了sql文件,可以直接测试。地址是
http://download.csdn.net/detail/lixin3273110c/6476443
(PS:在这里说一下,下载我的资源不需要积分,觉得开发这活儿就得多交流进步才能快,资源什么的也可以共享,自己复习的同时也帮助了别人。)