博客系统 02 分类管理

一、分类管理

(1)分类表的创建及映射文件的配置

  • 分类表
-- ----------------------------
-- Table structure for category
-- ----------------------------
DROP TABLE IF EXISTS `category`;
CREATE TABLE `category` (
  `cid` int(11) NOT NULL AUTO_INCREMENT,
  `cname` varchar(255) DEFAULT NULL,
  `parentid` int(11) DEFAULT NULL,
  PRIMARY KEY (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of category
-- ----------------------------
INSERT INTO `category` VALUES ('1', 'java', null);
INSERT INTO `category` VALUES ('2', 'python', null);
INSERT INTO `category` VALUES ('3', 'web', null);
INSERT INTO `category` VALUES ('4', 'mysql', '1');
INSERT INTO `category` VALUES ('5', 'web服务器', '1');
INSERT INTO `category` VALUES ('6', 'css', '3');
INSERT INTO `category` VALUES ('7', 'html', '3');
INSERT INTO `category` VALUES ('8', 'js', '3');
  • Category 类
import lombok.Getter;
import lombok.Setter;

@Getter @Setter
public class Category {
    private Integer cid;
    private String cname;
    private Integer parentid;

    @Override
    public String toString() {
        return "Category{" +
                "cid=" + cid +
                ", cname='" + cname + '\'' +
                ", parentid=" + parentid +
                '}';
    }
}
  • Category 表的关系映射文件(Category.hbm.xml):
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.blog.domain.Category" table="category">
        <!--建立类属性哪一个是主键 还要跟数据库当中主键进行对应 -->
        <id name="cid" column="cid">
            <generator class="native" />
        </id>
        <!--建立类中的普通属性与数据库当中字段进行关联 -->
        <property name="cname" column="cname" />
        <property name="parentid" column="parentid" />
    </class>
</hibernate-mapping>
  • 将 Category.hbm.xml 添加到 hibernateApplication.xml 中
<!-- 设置映射文件 -->
<property name="mappingResources">
    <list>
        <value>com/blog/domain/User.hbm.xml</value>
        <value>com/blog/domain/Category.hbm.xml</value>
    </list>
</property>

(2)创建 CategoryAction 类 并交给spring管理

  • struts.xml
<action name="category_*" class="categoryAction" method="{1}">
    <!--<allowed-methods>regex:.*</allowed-methods>-->
</action>
  • applicationContext.xml
<bean id="categoryAction" class="com.blog.web.CategoryAction" scope="prototype"/>
  • CategoryAction 类
public class CategoryAction extends ActionSupport implements ModelDriven<Category> {

	private Category category = new Category();

	@Override
	public Category getModel() {
		return category;
	}
}

(3)分类添加

a)分类添加请求

  • mgr_category.jsp:
<div id="modal_content">
    <div id="close"><img src="images/delete_icon.png" alt=""></div>
    <div class="edit_content">
        <div class="item1">
            <div><span>添加分类:</span></div>
        </div>
        <div class="item1">
            <div>
                <span>parentid:</span>
                <input type="text" class="am-form-field" id="parentid">&nbsp;&nbsp;
                <br/>
                <span>分类名称:</span>
                <input type="text" class="am-form-field" id="cname">&nbsp;&nbsp;
                <br/>
                <button class="am-btn am-btn-default" type="button" id="addcategory">添加</button>
            </div>
        </div>
    </div>
</div>
  • 监听添加按钮
/* 监听添加按钮点击 */
$("#addcategory").click(function () {
    /* 获取文本内容 */
    var parentid = $('#parentid').val();
    var cname = $('#cname').val();
    // alert(parentid + " " + cname);
    /* 发送请求 */
    $(window).attr('location', '${pageContext.request.contextPath}/category_add.action?parentid=' + parentid + '&cname=' + cname);
});
  • struts.xml 中添加方法白名单
<action name="category_*" class="categoryAction" method="{1}">
    <allowed-methods>add</allowed-methods>
    <!--<allowed-methods>regex:.*</allowed-methods>-->
</action>
  • CategoryAction 类中添加add方法
public class CategoryAction extends ActionSupport implements ModelDriven<Category> {

    private Category category = new Category();

    @Override
    public Category getModel() {
        return category;
    }

    public String add(){
        System.out.println("来到添加分类action");
        System.out.println(category);
        return null;
    }
}

b)分类添加完成

  • Service层:创建 CategoryService 和 CategoryServiceImpl
public interface CategoryService {
    public void save(Category category);
}
@Transactional
public class CategoryServiceImpl implements CategoryService {

    // 注入Dao
    @Setter
    private CategoryDao categoryDao;

    @Override
    public void save(Category category) {
        System.out.println("CategoryService: " + category);
        // 调用dao
        categoryDao.save(category);
    }
}
  • dao层:创建 CategoryDao 和 CategoryDaoImpl
public interface CategoryDao {
    public void save(Category category);
}
public class CategoryDaoImpl extends HibernateDaoSupport implements CategoryDao {
    @Override
    public void save(Category category) {
        System.out.println("CategoryDao: " + category);
        this.getHibernateTemplate().save(category);
    }
}
  • web 层:action类中注入service
public class CategoryAction extends ActionSupport implements ModelDriven<Category> {

    private Category category = new Category();

    @Override
    public Category getModel() {
        return category;
    }

    // 注入Service
    @Setter
    private CategoryService categoryService;

    public String add(){
        System.out.println("来到添加分类action");
        System.out.println(category);
        // 调用Service
        categoryService.save(category);
        return null;
    }
}
  • applicationContext.xml 配置
<!-- action bean -->
<bean id="categoryAction" class="com.blog.web.CategoryAction" scope="prototype">
    <property name="categoryService" ref="categoryService"/>
</bean>

<!-- service bean -->
<bean id="categoryService" class="com.blog.Service.impl.CategoryServiceImpl">
    <property name="categoryDao" ref="categoryDao"/>
</bean>

<!-- dao bean -->
<bean id="categoryDao" class="com.blog.dao.impl.CategoryDaoImpl">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>

(4)分类列表

  • 左侧分类链接点击发送请求 mgr_left.jsp
<ul>
    <li><a href="${pageContext.request.contextPath}/category_list.action" target="mainFrame"><i></i>分类管理</a></li>
    <li><a href="mgr_main.jsp" target="mainFrame"><i></i>文章管理</a></li>
    <li></i><a href="mgr_account.jsp" target="mainFrame"><i></i>用户管理</a></li>
</ul>
  • 配置接收请求 struts.xml
<action name="category_*" class="categoryAction" method="{1}">
    <result name="list">/mgr_category.jsp</result>
    <allowed-methods>add,list</allowed-methods>
    <!--<allowed-methods>regex:.*</allowed-methods>-->
</action>
  • action处理
public String list(){
    System.out.println("来到分类列表action");
    // 调用业务层
    List<Category> list = categoryService.list();
    System.out.println(list);
    // 把数据存到值栈当中
    ActionContext.getContext().getValueStack().set("categorylist",list);
    return "list";
}
  • 调用业务层
@Transactional
public class CategoryServiceImpl implements CategoryService {

    // 注入Dao
    @Setter
    private CategoryDao categoryDao;

    @Override
    public void save(Category category) {
        System.out.println("CategoryService: " + category);
        // 调用dao
        categoryDao.save(category);
    }

    @Override
    public List<Category> list() {
        // 调用dao
        List<Category> list = categoryDao.findAll();
        return list;
    }
}
  • 调用dao层
public class CategoryDaoImpl extends HibernateDaoSupport implements CategoryDao {
    @Override
    public void save(Category category) {
        System.out.println("CategoryDao: " + category);
        this.getHibernateTemplate().save(category);
    }

    @Override
    public List<Category> findAll() {
        DetachedCriteria criteria = DetachedCriteria.forClass(Category.class);
        List<Category> list = (List<Category>)this.getHibernateTemplate().findByCriteria(criteria);
        return list;
    }
}
  • 页面展示数据
<div class="goods_list" id="account_List">
    <ul class="title_ul">
        <li>parentid</li>
        <li>分类名称</li>
        <li>修改分类</li>
        <li>删除分类</li>
    </ul>
    <s:iterator value="categorylist" var="category">
        <ul class="list_goods_ul">
            <li><s:property value="#category.parentid"/></li>
            <li><s:property value="#category.cname"/></li>
            <li><a href="#"><img class="img_icon" src="images/edit_icon.png" alt=""></a></li>
            <li><a href="#"><img class="img_icon" src="images/delete_icon.png" alt=""></a></li>
        </ul>
    </s:iterator>
</div>

(5)分类修改

  • 界面准备
<div id="modal_content2" style="height: 250px; display: none">
	<div id="close2"><img src="images/delete_icon.png" alt=""></div>
	<div class="edit_content">
		<div class="item1">
			<div><span>修改分类:</span></div>
		</div>
		<div class="item1">
			<div>
				<span>parentid:</span>
				<input type="text" class="am-form-field" id="parentid2">&nbsp;&nbsp;
				<br/>
				<span>分类名称:</span>
				<input type="text" class="am-form-field" id="cname2">&nbsp;&nbsp;
				<br/>
				<input type="hidden" id="cid2">
				<button class="am-btn am-btn-default" type="button" id="updatebtn">修改</button>
			</div>
		</div>
	</div>
</div>

style.css

#modal_content, #modal_content2 {
    padding: 30px 20px;
    width: 400px;
    height: 260px;
    background: white;
    position: fixed;
    left: 50%;
    top: 50%;
    margin-left: -200px;
    margin-top: -100px;
    display: none;
}

#close, #close2 {
    position: absolute;
    right: 10px;
    top: 10px;
}
  • 监听修改按钮

mgr_category.jsp:

<s:iterator value="categorylist" var="category">
    <ul class="list_goods_ul">
        <li><s:property value="#category.parentid"/></li>
        <li><s:property value="#category.cname"/></li>
        <li><a href="#" class="updatebtn">
            <img class="img_icon" src="images/edit_icon.png" alt="">
        </a></li>
        <li><a href="#"><img class="img_icon" src="images/delete_icon.png" alt=""></a></li>
    </ul>
</s:iterator>

监听修改按钮,绑定id

<li>
    <a href="#" class="updatebtn" data-id="<s:property value="#category.cid"/>">
        <img class="img_icon" src="images/edit_icon.png" alt="">
    </a>
</li>
  • 获取修改按钮上绑定的id
/* 监听修改按钮点击 */
$(".updatebtn").click(function () {
    // alert("修改");
    /* 1.当前点击的是那一条记录 */
    var cid = $(this).data("id");
    alert(cid);
    /* 2.把修改页面弹出 */
    $("#modal_view").fadeIn();
    $("#modal_content2").fadeIn();
});

$("#close2").click(function () {
    $("#modal_view").fadeOut();
    $("#modal_content2").fadeOut();
});
  • 异步发送请求(发送AJAX请求)
/* 监听修改按钮点击 */
$(".updatebtn").click(function () {
    // alert("修改");
    /* 1.当前点击的是那一条记录 */
    var cid = $(this).data("id");
    alert(cid);
    /*
     * 取出对应id的数据,到数据库当中查询当前记录
     * 返回给页面,展示到页面当中.
     * 发送请求的时候,不需要页面的跳转 Ajax(前端技术)   能够取当前返回数据  展示到界面
     */
     $.post("${pageContext.request.contextPath}/category_updateUI.action",{"cid":cid},function (data) {
     	console.log("-------json------");
     	console.log(data);

     },"json");

     /* 2.把修改页面弹出 */
     $("#modal_view").fadeIn();
     $("#modal_content2").fadeIn();
 });

$("#close2").click(function () {
	$("#modal_view").fadeOut();
	$("#modal_content2").fadeOut();
});
  • 服务器接收请求

struts.xml 中添加方法“白名单”。

<action name="category_*" class="categoryAction" method="{1}">
    <result name="list">/mgr_category.jsp</result>
    <allowed-methods>add,list,updateUI</allowed-methods>
    <!--<allowed-methods>regex:.*</allowed-methods>-->
</action>

CategoryAction中添加updateUI方法

public String updateUI(){
    System.out.println(category.getCid());
    System.out.println("updateUI----------");
    // 调用业务层
    Category category2 = categoryService.getOneCategory(category.getCid());
    System.out.println(category2);
    return null;
}
  • 调用业务层

CategoryService 接口

public interface CategoryService {
    /* 保存分类业务 */
    public void save(Category category);
    /* 获取所有分类信息业务 */
    List<Category> list();
    /* 根据id查询分类信息 */
    Category getOneCategory(Integer cid);
}

CategoryServiceImpl 实现方法

@Override
public Category getOneCategory(Integer cid) {
    // 调用dao层
    Category category = categoryDao.getOneCategory(cid);
    return category;
}
  • 调用dao层

CategoryDao 接口

public interface CategoryDao {
    /* 保存分类 */
    public void save(Category category);
    /* 获取所有分类 */
    List<Category> findAll();
    /* 根据id到数据库当中查询分类 */
    Category getOneCategory(Integer cid);
}

CategoryDaoImpl 实现方法

@Override
public Category getOneCategory(Integer cid) {
    DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Category.class);
    //设置条件
    detachedCriteria.add(Restrictions.eq("cid",cid));
    List<Category> list = (List<Category>)this.getHibernateTemplate().findByCriteria(detachedCriteria);
    if(list.size() > 0){
        return list.get(0);
    }
    return null;
}
  • web层接收到数据后,以json形式返回

要用 json ,需要导入json的jar包

public String updateUI() throws IOException {
    System.out.println(category.getCid());
    System.out.println("updateUI----------");
    // 调用业务层
    Category category2 = categoryService.getOneCategory(category.getCid());
    System.out.println(category2);
    // 把数据给页面
    // 以json(数据格式) 响应给页面
    JSONArray jsonArray = JSONArray.fromObject(category2, new JsonConfig());
    System.out.println(jsonArray);
    // 响应给页面
    ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
    ServletActionContext.getResponse().getWriter().println(jsonArray.toString());
    return null;
}
  • 页面接收到返回的json进行展示
/* 监听修改按钮点击 */
$(".updatebtn").click(function () {
    // alert("修改");
    /* 1.当前点击的是那一条记录 */
    var cid = $(this).data("id");
    alert(cid);
    /*
             * 取出对应id的数据,到数据库当中查询当前记录
             * 返回给页面,展示到页面当中.
             * 发送请求的时候,不需要页面的跳转 Ajax(前端技术)   能够取当前返回数据  展示到界面
             */
    $.post("${pageContext.request.contextPath}/category_updateUI.action",{"cid":cid},function (data) {
        console.log("-------json------");
        console.log(data);
        /*把json数据展示到文本框 */
        $("#parentid2").val(data[0].parentid);
        $("#cname2").val(data[0].cname);
        $("#cid2").val(data[0].cid);
    },"json");


    /* 2.把修改页面弹出 */
    $("#modal_view").fadeIn();
    $("#modal_content2").fadeIn();
});

$("#close2").click(function () {
    $("#modal_view").fadeOut();
    $("#modal_content2").fadeOut();
});
  • 修改按钮点击监听
$("#updatebtn").click(function () {
    /* 1.获取文本框值 */
    var parentid2 = $("#parentid2").val();
    var cname2 = $("#cname2").val();
    var cid2 = $("#cid2").val();
    // alert(parentid2+cname2+cid2);
    /* 2.发送请求 */
    $(window).attr('location','${pageContext.request.contextPath}/category_update.action?parentid='+parentid2+'&cname='+cname2+'&cid='+cid2);
});
  • 服务器接收请求

struts.xml 中添加方法“白名单”。

<action name="category_*" class="categoryAction" method="{1}">
    <result name="list">/mgr_category.jsp</result>
    <allowed-methods>add,list,updateUI,update</allowed-methods>
    <!--<allowed-methods>regex:.*</allowed-methods>-->
</action>

CategoryAction中添加update方法

public String update(){
    System.out.println("update--------------");
    System.out.println(category);
    // 调用业务层
    categoryService.update(category);
    return null;
}
  • 调用业务层

CategoryService 接口

public interface CategoryService {
    /* 保存分类业务 */
    public void save(Category category);
    /* 获取所有分类信息业务 */
    List<Category> list();
    /* 根据id查询分类信息 */
    Category getOneCategory(Integer cid);
    /* 修改分类 */
    void update(Category category);
}

CategoryServiceImpl 实现方法

@Override
public void update(Category category) {
    // 调用dao层
    categoryDao.update(category);
}
  • 调用dao层

CategoryDao 接口

public interface CategoryDao {
    /* 保存分类 */
    public void save(Category category);
    /* 获取所有分类 */
    List<Category> findAll();
    /* 根据id到数据库当中查询分类 */
    Category getOneCategory(Integer cid);
    /* 修改分类 */
    void update(Category category);
}

CategoryDaoImpl 实现方法

@Override
public void update(Category category) {
    this.getHibernateTemplate().update(category);
}
  • 跳转回列表页面
public String update(){
    System.out.println("update--------------");
    System.out.println(category);
    // 调用业务层
    categoryService.update(category);
    return "listAction";
}

struts.xml

<action name="category_*" class="categoryAction" method="{1}">
    <result name="list">/mgr_category.jsp</result>
    <result name="listAction" type="redirectAction">category_list.action</result>
    <allowed-methods>add,list,updateUI,update</allowed-methods>
    <!--<allowed-methods>regex:.*</allowed-methods>-->
</action>

修改添加分类跳转回列表页面

public String add(){
    System.out.println("来到添加分类action");
    System.out.println(category);
    // 调用Service
    categoryService.save(category);
    return "listAction";
}

(6)分类删除

  • 监听删除按钮点击

mgr_category.jsp

<li>
    <a href="${pageContext.request.contextPath}/category_delete.action?cid=<s:property value="#category.cid"/>">
        <img class="img_icon" src="images/delete_icon.png" alt="">
    </a>
</li>
  • web接收

struts.xml 添加方法白名单

<action name="category_*" class="categoryAction" method="{1}">
    <result name="list">/mgr_category.jsp</result>
    <result name="listAction" type="redirectAction">category_list.action</result>
    <allowed-methods>add,list,updateUI,update,delete</allowed-methods>
    <!--<allowed-methods>regex:.*</allowed-methods>-->
</action>

CategoryAction 中添加 delete 方法

public String delete(){
    System.out.println("delete--------------");
    System.out.println(category);
    // 调用业务层
    categoryService.delete(category);
    return null;
}
  • 业务层处理

CategoryService 接口

public interface CategoryService {
    /* 保存分类业务 */
    public void save(Category category);
    /* 获取所有分类信息业务 */
    List<Category> list();
    /* 根据id查询分类信息 */
    Category getOneCategory(Integer cid);
    /* 修改分类 */
    void update(Category category);
    /* 删除分类 */
    void delete(Category category);
}

CategoryServiceImpl 实现方法

@Override
public void delete(Category category) {
    // 调用dao层
    categoryDao.delete(category);
}
  • dao层处理

CategoryDao 接口

public interface CategoryDao {
    /* 保存分类 */
    public void save(Category category);
    /* 获取所有分类 */
    List<Category> findAll();
    /* 根据id到数据库当中查询分类 */
    Category getOneCategory(Integer cid);
    /* 修改分类 */
    void update(Category category);
    /* 删除分类 */
    void delete(Category category);
}

CategoryDaoImpl 实现方法

@Override
public void delete(Category category) {
    this.getHibernateTemplate().delete(category);
}
  • 转发到列表页
public String delete(){
    System.out.println("delete--------------");
    System.out.println(category);
    // 调用业务层
    categoryService.delete(category);
    return "listAction";
}
posted @ 2019-06-04 21:36  Lomen~  阅读(577)  评论(0编辑  收藏  举报