今天看了下Nutz最新的版本库,发现“灰太狼”居然把我上一篇文章《在Nutz中使用Ioc-Annotation的入门教程》收录在Nutz的发行包中,为了表达“灰太狼”的厚爱,决定写多三篇文章以表心意!!!
------------------------------------------------------------------------------------------------------
第一篇:使用Nutz[1.b.38]对数据库表的CRUD操作
第二篇:使用Nutz[1.b.38]对关联数据表的一对一/一对多操作 ----已完成,点击查看
第三篇:在Nutz[1.b.38]中使用视图对关联数据表的操作 ----已完成,点击查看
-------------------------------------------------------------------------------------------------------
为了表达对Nutz的支持,这三篇文章最后都会提供完整的源代码,顺便作为Nutz的demo例子。
好的,直奔主题,今天先完成第一篇,接下来在此基础上完成第二篇、第三篇。
环境与版本:
数据库:MySQL
Nutz:1.b.38
IDE:Eclipse
涉及的知识点:
1、Nutz对数据库的CURD操作
2、除了数据源和dao对象使用dao.js配置外,其余全部使用Ioc-Annotation注解
3、在@Ok注解中使用NutzEL表达式,不必为跳转到Fail视图而故意抛出异常了
一、数据库表
-- ----------------------------
-- Table structure for `departmentinfo`
-- ----------------------------
DROP TABLE IF EXISTS `departmentinfo`;
CREATE TABLE `departmentinfo` (
`departmentInfoId` int(11) NOT NULL AUTO_INCREMENT,
`departmentName` varchar(50) DEFAULT NULL,
PRIMARY KEY (`departmentInfoId`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of departmentinfo
-- ----------------------------
INSERT INTO `departmentinfo` VALUES ('1', 'IT部');
INSERT INTO `departmentinfo` VALUES ('2', '人力资源');
INSERT INTO `departmentinfo` VALUES ('3', '财务部');
INSERT INTO `departmentinfo` VALUES ('4', '市场部');
二、例子使用的Jar包
三、结构图
四、代码
1、首先配置Web.xml,配置Nutz的主模块。
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>UserManageSystem</display-name> <filter> <filter-name>nutz</filter-name> <filter-class>org.nutz.mvc.NutFilter</filter-class> <init-param> <param-name>modules</param-name> <param-value>demo.nutz.setup.MainModule</param-value> </init-param> </filter> <filter-mapping> <filter-name>nutz</filter-name> <url-pattern>*.shtml</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
2、创建主模块类MainModule.java
package demo.nutz.setup; import org.nutz.mvc.annotation.IocBy; import org.nutz.mvc.annotation.Modules; import org.nutz.mvc.annotation.SetupBy; import org.nutz.mvc.ioc.provider.ComboIocProvider; import demo.nutz.action.DepartmentInfoAction; /** * 主模块 * * @author gevin([email protected]) * */ @Modules(value = DepartmentInfoAction.class, scanPackage = true) @IocBy(type = ComboIocProvider.class, args = { "*org.nutz.ioc.loader.json.JsonLoader", "ioc/dao.js", "*org.nutz.ioc.loader.annotation.AnnotationIocLoader", "demo.nutz"}) @SetupBy(NutzSetup.class) public class MainModule { }
由于使用了两种注入的配置方式,因此此处使用了Ioc复合加载器ComboIocProvider。
1)使用"*org.nutz.ioc.loader.json.JsonLoader", "ioc/dao.js"加载JS文件,dao.js中配置了数据源对象和dao对象的注入,貌似听“Wendal-兽”说无法用注解来配置,只能用配置文件。
2)使用"*org.nutz.ioc.loader.annotation.AnnotationIocLoader", "demo.nutz"来自动加载包demo.nutz或其子包中被@IocBean注解过的类。
3)@Modules(value = ArticleInfoAction.class, scanPackage = true) 用来告诉Nutz自动去扫描ArticleInfoAction.class所在包的所有类,如果有类包括了一个以上的入口函数将被认为是模块类。
3、“ioc/dao.js”文件
/* * 本配置文件声明了整个应用的数据库连接部分。 */ var ioc = { /* * 数据库连接池 */ dataSource : { type : "com.mchange.v2.c3p0.ComboPooledDataSource", fields : { driverClass : "com.mysql.jdbc.Driver", jdbcUrl : "jdbc:mysql://127.0.0.1/nutzdemo", user : "root", password : "123456" } }, /* * 这个配置很好理解, args 表示这个对象构造函数的参数。显然,下面的注入方式将调用 new NutDao(dataSource) */ dao : { type : "org.nutz.dao.impl.NutDao", args : [ { refer : "dataSource" } ] } };
4、Model类DepartmentInfo.java
package demo.nutz.model; import org.nutz.dao.entity.annotation.Id; import org.nutz.dao.entity.annotation.Table; @Table("DepartmentInfo") public class DepartmentInfo { @Id //指明主键是整型且默认为自增1 private Integer departmentInfoId; private String departmentName; /*此处省略Getter和Setter*/ }
5、Service层DepartmentInfoService.java
package demo.nutz.service; import org.nutz.dao.Dao; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.service.IdEntityService; import demo.nutz.model.DepartmentInfo; /** * 部门信息-业务层 * * @author gevin([email protected]) * */ @IocBean(args = { "refer:dao" }) // 使用@IocBean注解,无需通过配置文件配置,此处必须带上构造函数的参数所引用的对象 public class DepartmentInfoService extends IdEntityService<DepartmentInfo> { public DepartmentInfoService() { super(); } public DepartmentInfoService(Dao dao, Class<DepartmentInfo> entityType) { super(dao, entityType); } public DepartmentInfoService(Dao dao) { super(dao); } }
6、为了方便以后扩展或进行一些全局的操作,自己定义了一个BaseAction.java,在此类中可定义各种公用变量或函数
package demo.nutz.base; import java.util.Map; /** * Action基类,在此类中可定义各种公用变量或函数 * * @author gevin([email protected]) * */ public class BaseAction { // 定义操作结果字符串 protected static String ADD_SUCCESS = "addSuccess"; protected static String ADD_FAILURE = "addFailure"; protected static String EDIT_SUCCESS = "editSuccess"; protected static String EDIT_FAILURE = "editFailure"; protected static String DEL_SUCCESS = "delSuccess"; protected static String DEL_FAILURE = "delFailure"; protected static String GET_SUCCESS = "getSuccess"; protected static String GET_FAILURE = "getFailure"; protected static String OP_SUCCESS = "opSuccess"; protected static String OP_FAILURE = "opFailure"; /** * 返回错误结果 * * @param errorMsg * @param map * @return */ public Map<String, Object> failure(String errorMsg, Map<String, Object> map) { map.put("msg", errorMsg); return map; } /** * 返回成功结果 * * @param successMsg * @param map * @return */ public Map<String, Object> success(String successMsg, Map<String, Object> map) { map.put("msg", successMsg); return map; } /** * 返回成功结果 * * @param successMsg * @param map * @return */ public Map<String, Object> success(Map<String, Object> map) { map.put("msg", null); return map; } }
7、控制CRUD操作的Action类DepartmentInfoAction.java
package demo.nutz.action; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.nutz.dao.Cnd; import org.nutz.ioc.loader.annotation.Inject; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.mvc.annotation.At; import org.nutz.mvc.annotation.Ok; import org.nutz.mvc.annotation.Param; import demo.nutz.base.BaseAction; import demo.nutz.model.DepartmentInfo; import demo.nutz.service.DepartmentInfoService; /** * 部门信息模块 * * @author gevin([email protected]) * */ @IocBean @At("/departmentinfo") public class DepartmentInfoAction extends BaseAction { @Inject // 通过注解@Inject注入对象 private DepartmentInfoService departmentInfoService; /** * 跳转到添加页面 * * @return */ @At("/addDepartmentInfo") @Ok("jsp:${obj.msg == null ? '/departmentinfo/addDepartmentInfo' : '/departmentinfo/showMessage'}") // 在@Ok中使用NutzEL表达式 public Map<String, Object> addDepartmentInfo() { Map<String, Object> map = new HashMap<String, Object>(); try { return success(map); } catch (Exception e) { e.printStackTrace(); return failure(GET_FAILURE, map); } } /** * 添加成功 * * @param di * @return */ @At("/addDepartmentInfoOk") @Ok("jsp:/departmentinfo/showMessage") public Map<String, Object> addDepartmentInfoOk(@Param("..") DepartmentInfo di) { Map<String, Object> map = new HashMap<String, Object>(); try { if (di == null) return failure(GET_FAILURE, map); // 添加成功 if (this.departmentInfoService.dao().insert(di) == null) return failure(ADD_FAILURE, map); return success(ADD_SUCCESS, map); } catch (Exception e) { e.printStackTrace(); map.put("msg", "getFailure"); return map; } } /** * 跳转到修改页面 * * @param departmentInfoId * @return */ @At("/editDepartmentInfo") @Ok("jsp:${obj.msg == null ? '/departmentinfo/editDepartmentInfo' : '/departmentinfo/showMessage'}") public Map<String, Object> editDepartmentInfo(@Param("departmentInfoId") Integer departmentInfoId) { Map<String, Object> map = new HashMap<String, Object>(); try { if (departmentInfoId == null) return failure(GET_FAILURE, map); // 获取对象 DepartmentInfo di = this.departmentInfoService.fetch(departmentInfoId); if (di == null) return failure(GET_FAILURE, map); map.put("departmentInfo", di); return success(map); } catch (Exception e) { e.printStackTrace(); return failure(GET_FAILURE, map); } } /** * 修改成功 * * @param di * @return */ @At("/editDepartmentInfoOk") @Ok("jsp:/departmentinfo/showMessage") public Map<String, Object> editDepartmentInfoOk(@Param("..") DepartmentInfo di) { Map<String, Object> map = new HashMap<String, Object>(); try { if (di == null) return failure(GET_FAILURE, map); // 修改对象 if (this.departmentInfoService.dao().update(di) == 0) return failure(EDIT_FAILURE, map); return success(EDIT_SUCCESS, map); } catch (Exception e) { e.printStackTrace(); return failure(GET_FAILURE, map); } } /** * 删除成功 * * @param di * @param request * @return */ @At("/delDepartmentInfoOk") @Ok("jsp:/departmentinfo/showMessage") public Map<String, Object> delDepartmentInfoOk(@Param("..") DepartmentInfo di, HttpServletRequest request) { Map<String, Object> map = new HashMap<String, Object>(); try { if (di == null) return failure(GET_FAILURE, map); // 删除对象 if (this.departmentInfoService.dao().delete(di) == 0) return failure(DEL_FAILURE, map); return success(DEL_SUCCESS, map); } catch (Exception e) { e.printStackTrace(); return failure(GET_FAILURE, map); } } /** * 显示列表 * * @return */ @At("/showDepartmentInfoList") @Ok("jsp:/departmentinfo/showDepartmentInfoList") public Map<String, Object> showDepartmentInfoList() { Map<String, Object> map = new HashMap<String, Object>(); try { List<DepartmentInfo> diList = this.departmentInfoService.query(Cnd.orderBy().asc("departmentName"), null); map.put("departmentInfoList", diList); return success(map); } catch (Exception e) { e.printStackTrace(); return failure(GET_FAILURE, map); } } }
8、JSP视图文件
showArticleInfoList.shtml
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %> <%@ include file="../include/taglibs.jsp" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>部门信息列表</title> <link href="../css/web.css" rel="stylesheet" type="text/css" /> </head> <body> <br /> <table width="500" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td height="35"><label> <input type="button" name="add" id="add" value="添加部门信息" onclick="window.location='addDepartmentInfo.shtml'" /> </label></td> </tr> </table> <table width="500" border="0" align="center" cellpadding="1" cellspacing="1" class="TableOut"> <tr> <td height="30" colspan="3" align="center" class="TableTop">部门信息列表</td> </tr> <tr class="TableInWhite"> <td width="104" height="30" align="center">序号</td> <td width="272" align="center">部门名称</td> <td width="124" align="center">操作</td> </tr> <c:forEach var = "di" items = "${obj.departmentInfoList}" varStatus="status"> <tr class="TableInWhite"> <td height="30" align="center">${status.count}</td> <td align="center">${di.departmentName}</td> <td align="center">[<a href="editDepartmentInfo.shtml?departmentInfoId=${di.departmentInfoId}">修改</a>] [<a href="delDepartmentInfoOk.shtml?departmentInfoId=${di.departmentInfoId}" onclick="return confirm('是否真的要删除此部门?')">删除</a>]</td> </tr> </c:forEach> </table> </body> </html>
addDepartmentInfo.jsp
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>添加部门信息</title> <link href="../css/web.css" rel="stylesheet" type="text/css" /> </head> <body> <br /> <br /> <form id="form1" name="form1" method="post" action="addDepartmentInfoOk.shtml"> <table width="400" border="0" align="center" cellpadding="1" cellspacing="1" class="TableOut"> <tr> <td height="30" colspan="2" align="center" class="TableTop">添加部门信息</td> </tr> <tr class="TableInWhite"> <td width="91" height="30" align="center">部门名称:</td> <td width="302"><label> <input type="text" name="departmentName" id="departmentName" /> </label></td> </tr> <tr class="TableInWhite"> <td height="30" colspan="2" align="center"><label> <input type="submit" name="add" id="add" value=" 提 交 " /> <input type="reset" name="reset" id="reset" value=" 重 置 " /> </label></td> </tr> </table> </form> </body> </html>
editDepartmentInfo.jsp
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %> <%@ include file="../include/taglibs.jsp" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>修改部门信息</title> <link href="../css/web.css" rel="stylesheet" type="text/css" /> </head> <body> <br /> <br /> <c:set var="di" value="${obj.departmentInfo}" /> <form id="form1" name="form1" method="post" action="editDepartmentInfoOk.shtml"> <input type="hidden" id="departmentInfoId" name="departmentInfoId" value="${di.departmentInfoId}" /> <table width="400" border="0" align="center" cellpadding="1" cellspacing="1" class="TableOut"> <tr> <td height="30" colspan="2" align="center" class="TableTop">修改部门信息</td> </tr> <tr class="TableInWhite"> <td width="91" height="30" align="center">部门名称:</td> <td width="302"><label> <input type="text" name="departmentName" id="departmentName" value="${di.departmentName}" /> </label></td> </tr> <tr class="TableInWhite"> <td height="30" colspan="2" align="center"><label> <input type="submit" name="add" id="add" value=" 提 交 " /> <input type="reset" name="reset" id="reset" value=" 返 回" onclick="history.back()" /> </label></td> </tr> </table> </form> </body> </html>
信息提示文件:showMessage.jsp
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %> <%@ include file="../include/taglibs.jsp" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>信息提示</title> <script type="text/javascript" src="../js/common.js"></script> </head> <body> <c:set var="msg" value="${obj.msg}" /> <c:choose> <c:when test="${msg=='addSuccess'}"> <script type="text/javascript">alertMsg("添加成功.","showDepartmentInfoList.shtml");</script> </c:when> <c:when test="${msg=='editSuccess'}"> <script type="text/javascript">alertMsg("修改成功.","showDepartmentInfoList.shtml");</script> </c:when> <c:when test="${msg=='delSuccess'}"> <script type="text/javascript">alertMsg("删除成功.","showDepartmentInfoList.shtml");</script> </c:when> <c:when test="${msg=='addFailure'}"> <script type="text/javascript">alertMsg("添加失败,请返回重新操作.","back");</script> </c:when> <c:when test="${msg=='editFailure'}"> <script type="text/javascript">alertMsg("修改失败,请返回重新操作.","back");</script> </c:when> <c:when test="${msg=='delFailure'}"> <script type="text/javascript">alertMsg("删除失败,请返回重新操作.","back");</script> </c:when> <c:when test="${msg=='getFailure'}"> <script type="text/javascript">alertMsg("获取失败,请返回重新操作.","back");</script> </c:when> <c:when test="${msg=='opFailure'}"> <script type="text/javascript">alertMsg("操作失败,请返回重新操作.","back");</script> </c:when> </c:choose> </body> </html>
9、OK了,所有文件都配置好了,我们重启Tomcat,访问以下测试地址。
http://127.0.0.1:204/UserManageSystem/departmentinfo/showDepartmentInfoList.shtml
效果图:
---------------------------------------------------------------------------------------------------------------------
第二次写学习心得,还是觉得太花时间了,哈哈!!啥时候才能养成写BLOG的习惯呢。。。。 时间啊!!
最后,当然是本例子的完整代码了。。。希望对Nutz的初学者有用!让更多人使用Nutz,哈哈!!