导入工具类和方法的代码
- 过滤中文乱码数据
- HTML转义
- DAOFactory
- JDBC连接池
- UUID工具类
- c3p0.xml配置文件
这些代码都可以在我的博客分类:代码库中找到!
分类模块
首先,我们来做分类模块吧
创建实体Category
privateStringid;
privateStringname;
privateStringdescription;
//各种setter、getter
在数据库创建表
CREATETABLEcategory(
id VARCHAR(40)PRIMARYKEY,
name VARCHAR(10)NOTNULLUNIQUE,
descriptionVARCHAR(255)
);
编写CategoryDAO
/**
* 分类模块
* 1:添加分类
* 2:查找分类
* 3:修改分类
*
*
* */
publicclassCategoryImpl{
publicvoidaddCategory(Categorycategory){
QueryRunnerqueryRunner=newQueryRunner(Utils2DB.getDataSource());
Stringsql="INSERT INTO category (id, name, description) VALUES(?,?,?)";
try{
queryRunner.update(sql,newObject[]{category.getId(),category.getName(),category.getDescription()});
}catch(SQLExceptione){
thrownewRuntimeException(e);
}
}
publicCategoryfindCategory(Stringid){
QueryRunnerqueryRunner=newQueryRunner(Utils2DB.getDataSource());
Stringsql="SELECT * FROM category WHERE id=?";
try{
Categorycategory=(Category)queryRunner.query(sql,id,newBeanHandler(Category.class));
returncategory;
}catch(SQLExceptione){
thrownewRuntimeException(e);
}
}
publicList<Category>getAllCategory(){
QueryRunnerqueryRunner=newQueryRunner(Utils2DB.getDataSource());
Stringsql="SELECT * FROM category";
try{
List<Category>categories=(List<Category>)queryRunner.query(sql,newBeanListHandler(Category.class));
returncategories;
}catch(SQLExceptione){
thrownewRuntimeException(e);
}
}
}
测试DAO
publicclassdemo{
@Test
publicvoidadd(){
Categorycategory=newCategory();
category.setId("2");
category.setName("数据库系列");
category.setDescription("这是数据库系列");
CategoryImplcategory1=newCategoryImpl();
category1.addCategory(category);
}
@Test
publicvoidfind(){
Stringid="1";
CategoryImplcategory1=newCategoryImpl();
Categorycategory=category1.findCategory(id);
System.out.println(category.getName());
}
@Test
publicvoidgetAll(){
CategoryImplcategory1=newCategoryImpl();
List<Category>categories=category1.getAllCategory();
for(Categorycategory:categories){
System.out.println(category.getName());
}
}
}
抽取成DAO接口
publicinterfaceCategoryDao{
voidaddCategory(Categorycategory);
CategoryfindCategory(Stringid);
List<Category>getAllCategory();
}
后台页面的添加分类
- 在超链接上,绑定显示添加分类的页面
<ahref="${pageContext.request.contextPath}/background/addCategory.jsp"target="body">添加分类</a>
- 显示添加分类的JSP页面
<formaction="${pageContext.request.contextPath}/CategoryServlet?method=add"method="post">
分类名称:<inputtype="text"name="name"><br>
分类描述:<textareaname="description"></textarea><br>
<inputtype="submit"value="提交">
</form>
- 处理添加分类的Servlet
if(method.equals("add")){
try{
//把浏览器带过来的数据封装到bean中
Categorycategory=WebUtils.request2Bean(request,Category.class);
category.setId(WebUtils.makeId());
service.addCategory(category);
request.setAttribute("message","添加分类成功!");
}catch(Exceptione){
request.setAttribute("message","添加分类失败");
e.printStackTrace();
}
request.getRequestDispatcher("/message.jsp").forward(request,response);
}
- 效果: