个人博客系统(SSM)

简单做一个个人博客系统,以博客中的日记模块为例。后台使用easyui。

数据库:personal_blog

日记表:diary

字段:


创建Maven工程

pom.xml文件

<dependencies>
<!-- mybatis核心包 -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.1</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.29</version>
</dependency>
<!--日志包-->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.6.1</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.6.1</version>
</dependency>
<!--spring数据库-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.3.11.RELEASE</version>
</dependency>
<!--aop-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>4.3.11.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.11.RELEASE</version>
</dependency>
<!--spring-mybatis整合包-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.1</version>
</dependency>
<!--spring MVC相关包-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.11.RELEASE</version>
</dependency>
<!--JSTL的目的就是在JSTL页面中美观的输出数据,它内置了很多标签库,包括很多逻辑判断,迭代,函数,数据库标签-->
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
<!--mybatis分页插件-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>4.2.1</version>
</dependency>
<!-- Jackson Json处理工具包 -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.7.4</version>
</dependency>
<!--文件上传包-->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
</dependencies>

<!--构建项目需要的信息-->
<build>
    <finalName>ssm-blog-admin</finalName>
    <!--这个元素描述了项目相关的所有资源路径列表,例如和项目相关的属性文件,这些资源被包含在最终的打包文件里。-->
    <!--maven工程默认只导入resources下的配置文件 -->
    <resources>
        <!--这个元素描述了项目相关或测试相关的所有资源路径,-->
        <!--导入mybatis-mapper.xml文件 -->
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <!--扫描存放资源的路径 -->
            <directory>src/main/resources</directory>
            <!--包含的内容列表 -->
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
        </resource>
    </resources>
</build>
实体类pojo

Diary.java

public class Diary {
    private Integer id;  //主键ID
    private Integer userId;  //用户ID
    private Date createdDate; //日记创建时间
    private String content;   //日记内容
    private String title;  //日记标题
    private int status;   //身份权限,1:有效,0:无效
    private String nickname;   //昵称
    private AdminUser adminUser;  //管理员

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    public Date getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public AdminUser getAdminUser() {
        return adminUser;
    }

    public void setAdminUser(AdminUser adminUser) {
        this.adminUser = adminUser;
    }
}

DAO层

DiaryDAO.java

public interface DiaryDAO {
    //插入日记方法
    void addDiary(Diary diary);
    //查询日记列表
    List<Diary> getDiaryList(Diary diary);
    //根据id查询日记
    Diary getDiaryById(int id);
    //更新日记
    void updateDiary(Diary diary);
    //更新用户权限
    void updateDiaryStatus(Diary diary);
}

DiaryMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace:对应dao层的全路径-->
<mapper namespace="com.ssm.blog.dao.DiaryDAO">

    <!--id:dao层中添加日记方法,parameterType:mapper接口方法接受的参数类型-->
    <insert id="addDiary" parameterType="Diary">
        INSERT INTO diary(USER_ID,CREATED_DATE,CONTENT,TITLE,STATUS)
        VALUES (#{userId},now(),#{content},#{title},#{status})
    </insert>

    <!--id 下方resultMap,type 对应实体类名-->
    <resultMap id="diaryMap" type="Diary">
        <!--property对应实体类中属性名,column对应数据库中字段名-->
        <id property="id" column="ID"/>
        <result property="userId" column="USER_ID"/>
        <result property="createdDate" column="CREATED_DATE"/>
        <result property="content" column="CONTENT"/>
        <result property="title" column="TITLE"/>
        <result property="status" column="STATUS"/>
    </resultMap>
    <!--id对应DAO层查询列表方法名,parameterType:mapper接口方法接受的参数类型,resultMap对应上方id值-->
    <select id="getDiaryList" parameterType="Diary" resultMap="diaryMap">
        SELECT D.ID,D.TITLE,D.USER_ID,D.CREATED_DATE,D.CONTENT,D.STATUS,A.NICKNAME
        FROM diary D
        INNER JOIN ADMIN_USER A ON D.USER_ID=A.ID
        <where>
            <if test="id !=null">D.ID=#{id}</if>
            <if test="title !=null and title!=''">and TITLE like concat('%',#{title},'%')</if>
            <if test="nickname !=null and nickname!=''">and NICKNAME like concat('%',#{nickname},'%')</if>
        </where>
    </select>

    <!--根据id查询,用户点击修改时回显数据-->
    <!--id:dao层中根据id查询日记方法,parameterType:mapper接口方法接受的参数类型-->
    <select id="getDiaryById" parameterType="int" resultMap="diaryMap">
        SELECT ID,TITLE,CONTENT,STATUS
        FROM Diary
        WHERE ID=#{id}
    </select>

    <!--id:dao层中更新日记方法,parameterType:mapper接口方法接受的参数类型-->
    <update id="updateDiary" parameterType="Diary">
        update diary set TITLE=#{title},CONTENT=#{content},STATUS=#{status}
        where ID=#{id}
    </update>

    <!--修改用户权限,点击删除后将权限为1的修改为权限为0的-->
    <!--id:dao层中更改权限方法,parameterType:mapper接口方法接受的参数类型-->
    <update id="updateDiaryStatus" parameterType="Diary">
        update diary set STATUS=0
        where ID=#{id}
    </update>
</mapper>

service层

DiaryService.java

public interface DiaryService {
    //插入日记
    void addDiary(Diary diary);

    //查询日记列表并分页
    PageInfo<Diary> getDiaryList(Diary diary,int pageNum,int pageSize);

    //根据id查询,用于回显
    Diary getDiaryById(Integer id);

    //更新日记
    void updateDiary(Diary diary);
    //更改权限
    void updateDiaryStatus(int id);
}

service层  DiarySrviceImpl.java

//加service注解
@Service
public class DiaryServiceImpl implements DiaryService {
//    当Spring发现@Autowired注解时,将自动在代码上下文中找到和其匹配(默认是类型匹配)的Bean,
// 并自动注入到相应的地方去。
    @Autowired
    private DiaryDAO diaryDAO;

    //插入日记
    @Override
    public void addDiary(Diary diary) {
        diaryDAO.addDiary(diary);
    }
    //查询日记列表并分页
    @Override
    public PageInfo<Diary> getDiaryList(Diary diary, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Diary> diaryList = diaryDAO.getDiaryList(diary);
        PageInfo<Diary> pageInfo = new PageInfo<>(diaryList);
        return pageInfo;
    }
    //根据id查询日记
    @Override
    public Diary getDiaryById(Integer id) {
        return diaryDAO.getDiaryById(id);
    }
    //更新日记
    @Override
    public void updateDiary(Diary diary) {
        diaryDAO.updateDiary(diary);
    }
    //更新身份权限
    @Override
    public void updateDiaryStatus(int id) {
        Diary diary = diaryDAO.getDiaryById(id);

        diaryDAO.updateDiaryStatus(diary);
    }
}

controller层

 DiaryController.java

//加controller注解,处理由DispatcherServlet分发的请求
@Controller
//定义url
@RequestMapping("/diary.html")
public class DiaryController {
    @Autowired
    private DiaryService diaryService;

    @RequestMapping(params = "act=edit")
    @ResponseBody   //这个注解表示该方法的返回结果直接写入HTTP response body中,一般在异步获取数据时使用。
    //添加和修改,一个方法实现两个功能
    public Map<String,Object> edit(Diary diary){
        if (diary.getId() == null) {
            //从session中获取user的信息,后面写完登录再改
            diary.setUserId(2);
            diaryService.addDiary(diary);
        }else{
            //修改
            diaryService.updateDiary(diary);
        }
        return JsonUtils.getSuccessMessage("编辑成功",null);
    }

    //查询日记列表并分页    
    @RequestMapping(params = "act=list")
    @ResponseBody
    public Map<String,Object> list(Diary diary, int page, int rows){
        PageInfo<Diary> pageInfo = diaryService.getDiaryList(diary, page, rows);
        return JsonUtils.getDatagridPagerResult(pageInfo.getTotal(),pageInfo.getList());
    }

    //根据id查询所有,用于点击修改后回显
    @RequestMapping(params = "act=get")
    public ModelAndView getDiary(Integer id){
        Diary diary = null;
        if (id!=null){
            diary = diaryService.getDiaryById(id);
        }
        return new ModelAndView("diary_edit","diary",diary);
    }

    //文件上传
    @Value("${DIARY_IMAGE_DIR}")
    private String DIARY_IMAGE_DIR;
    @Value("${DIARY_IMAGE_URL}")
    private String DIARY_IMAGE_URL;

    @RequestMapping(params = "act=upload")
    @ResponseBody
    public String upload(MultipartFile file) {
        return JsonUtils.fileUpload(file,DIARY_IMAGE_DIR,DIARY_IMAGE_URL);
    }

    //删除(修改权限)
    @RequestMapping(params = "act=delete")
    @ResponseBody
    public Map<String,Object> delete(int id){
        Diary diary = diaryService.getDiaryById(id);
        if (diary.getStatus()!=0){
            diaryService.updateDiaryStatus(id);
        }
        return JsonUtils.getSuccessMessage("删除权限成功",null);
    }
}

util工具类

JsonUtils.java

public class JsonUtils {
    public static Map<String,Object> getSuccessMessage(String message,Object other){
        Map<String,Object> result = new HashMap<>();
        result.put("status", true);
        result.put("message", "添加成功");
        result.put("other",other);
        return result;
    }

    public static Map<String,Object> getErrorMessage(String message,Object other){
        Map<String,Object> result = new HashMap<>();
        result.put("status", false);
        result.put("message", "添加成功");
        result.put("other",other);
        return result;
    }

    public static Map<String,Object> getDatagridPagerResult(long total, List list){
        Map<String,Object> result = new HashMap<>();
        result.put("total",total);  //总条数
        result.put("rows",list);  //返回的list数据
        return result;
    }

    public static String fileUpload(MultipartFile file,String DIR,String URL){
        String oldFileName = file.getOriginalFilename();
        String extName = oldFileName.substring(oldFileName.lastIndexOf("."));
        String newFileName = System.currentTimeMillis()+extName;
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(DIR,newFileName));
            return "{\"error\":0,\"url\":\"" + URL + newFileName + "\"}";
        } catch (IOException e) {
            e.printStackTrace();
            return "{\"error\":1}";
        }
    }
}

resource

db.properties:配置mysql

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/personal_blog?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

log4j.properties:输出日志信息

log4j.rootLogger=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

#begin
#for normal test,delete when online
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG

log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG

resourse.properties:配置文件上传路径和url地址

DIARY_IMAGE_DIR=E:/upload/diary/

DIARY_IMAGE_URL=http://localhost:8080/upload/diary/

spring-config.xml

<!--读取配置文件-->
<context:property-placeholder location="classpath:db.properties" ignore-unresolvable="true"/>
<!--从配置文件中获取数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driver}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

<!-- 启动自动扫描 -->
<context:component-scan base-package="com.ssm.blog.*">
    <!-- 制定扫包规则 ,不扫描@Controller注解的JAVA类 -->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!--spring管理session工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mapperLocations" value="classpath:com/ssm/blog/dao/mapper/*.xml"/>
    <property name="typeAliasesPackage" value="com.ssm.blog.pojo"/>
    <property name="plugins">
        <array>
            <bean class="com.github.pagehelper.PageHelper">
                <property name="properties">
                    <value>
                        dialect=mysql
                        reasonable=true
                    </value>
                </property>
            </bean>
        </array>
    </property>
</bean>
<!--扫描所有mybatis的dao接口,生成代理实现类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.ssm.blog.dao"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager"
      class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>
<!--事务增强-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <!-- 传播行为,匹配的是方法名 -->
        <tx:method name="add*" rollback-for="Exception"/>
        <tx:method name="delete*" rollback-for="Exception"/>
        <tx:method name="update*" rollback-for="Exception"/>
        <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
        <tx:method name="do*" rollback-for="Exception"/>
    </tx:attributes>
</tx:advice>
<!-- 通过AOP配置提供事务增强,让service包下所有Bean的所有方法拥有事务 -->
<aop:config>
    <aop:pointcut id="serviceMethod"
                  expression="execution(* com.ssm.blog.service..*(..))"/>
    <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>
</aop:config>

WEB-INF

springMVC-servlet.xml

<!--加载下方返回值转换器-->
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManagerFactoryBean"/>
<!--扫描过滤器-->
<context:component-scan base-package="com.ssm.blog.controller">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/"></property><!--前缀-->
    <property name="suffix" value=".jsp"></property><!--后缀-->
</bean>
<!--加载media下的easyui和富文本编辑器-->
<mvc:resources mapping="/media/**" location="/media/"/>
<!--配置返回值转换器-->
<bean id="contentNegotiationManagerFactoryBean"
      class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="favorPathExtension" value="false"/>
    <property name="favorParameter" value="false"/>
    <property name="ignoreAcceptHeader" value="false"/>
    <property name="mediaTypes">
        <map>
            <entry key="json" value="application/json"/>
        </map>
    </property>
</bean>
<!--文件上传解析器-->
<bean id="multipartResolver"   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="1048576"/>
    <property name="defaultEncoding" value="UTF-8"/>
    <property name="resolveLazily" value="true"/>
</bean>

web.xml

<!--加载spring-config.xml-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-config.xml</param-value>
</context-param>
<!--配置listener,在启动Web容器的时候加载Spring的配置-->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置DispatcherServlet -->
<servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>/blog/list.html</welcome-file>
</welcome-file-list>

diary_list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--panel面板可以设置整体的高度--%>
<div class="easyui-panel" style="height: 95%">
    <table id="diary-datagrid" style="height:450px">
    </table>
    <div id="diary-datagrid-toolbar">
        <div>
            ID:<input type="text" class="easyui-numberbox" id="search-diary-id"/>
            标题:<input type="text" id="search-diary-title"/>
            昵称:<input type="text" id="search-diary-nickname"/>
            <a href="#" class="easyui-linkbutton" iconCls="icon-search"
               onclick="doDiarySearch()">搜索</a>
        </div>
        <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="doEditDiary(0)">新增</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="doEditDiary(1)">修改</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" plain="true" onclick="doDeleteDiary()">删除权限</a>
    </div>
</div>

<div class="easyui-dialog" closed="true" id="edit-diary-dialog"
     modal="true" title="编辑日记" style="width:800px;height:600px;padding:30px" buttons="#dlg-diary-buttons">
</div>
<div id="dlg-diary-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitDiary()">保存</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" onclick="$('#edit-diary-form').form('reset');">重填</a>
</div>
<link href="<%=request.getContextPath()%>/media/kindeditor-4.1.10/themes/default/default.css" type="text/css"
      rel="stylesheet">
<script type="text/javascript" charset="utf-8"
        src="<%=request.getContextPath()%>/media/kindeditor-4.1.10/kindeditor-all.js"></script>
<script type="text/javascript" charset="utf-8"
        src="<%=request.getContextPath()%>/media/kindeditor-4.1.10/lang/zh_CN.js"></script>

<script type="text/javascript">
    $(function () {
        $("#diary-datagrid").datagrid({
            url: "<%=request.getContextPath()%>/diary.html?act=list",
            pagination: true,
            pageList: [5, 10, 15, 20],
            toolbar: "#diary-datagrid-toolbar",
            frozen: true,//冻结标题行
            singleSelect:true,
            fit: true,//让表格自动适应面板的高度
            nowrap: false,//高度自适应,当内容比较多的时候会自动换行
            columns: [[
                {field: 'id', title: 'ID', width: 80},
                {field: 'title', title: '标题', width: 80},
                {field: 'createdDate', title: '发布时间', width: 160},
                {field: 'nickname', title: '作者', width: 80},
                {
                    field: 'status', title: '身份权限', width: 80, formatter: function (val, row) {
                    if (row.status == 0) return "<span style='color:red'>无效</span>";
                    return row.status
                }
                }
            ]]
        })
    })

    function doDiarySearch() {
        var queryParams = $('#diary-datagrid').datagrid('options').queryParams;
        queryParams.id = $("#search-diary-id").val();
        queryParams.title = $("#search-diary-title").val();
        queryParams.nickname = $("#search-diary-nickname").val();
        //重新加载datagrid
        $("#diary-datagrid").datagrid('reload');
    }

    var kingEditorParams = {
        filePostName: "file",//指定上传文件参数名称
        uploadJson: '<%=request.getContextPath()%>/diary.html?act=upload',//指定上传文件请求的url。
        dir: "image"//上传类型,分别为image、flash、media、file,
    }
    var editor;

    function doEditDiary(type) {
        var id = "";
        var row = $('#diary-datagrid').datagrid('getSelected');  //单选
        if (type == 1) {//要修改
            if (row == null) {
                alert("请选择要编辑的数据");
                return;
            }
            id = row.id;
        }
        $("#edit-diary-dialog").dialog({
            href: "<%=request.getContextPath()%>/diary.html?act=get&id=" + id,
            onLoad: function () {
                editor = KindEditor.create($("#editor"), kingEditorParams);
            },
            onBeforeDestroy: function () {
                KindEditor.remove("#editor");
            }
        }).dialog('open');
    }

    function submitDiary() {
        $('#edit-diary-form').form('submit', {
            onSubmit: function () {
                if ($(this).form('enableValidation').form('validate')) {
                    editor.sync();//同步富文本编辑器,否则拿不到
                    $.ajax({
                        url: "<%=request.getContextPath()%>/diary.html?act=edit",
                        data: $("#edit-diary-form").serialize(),
                        method: "post",
                        success: function (data) {
                            if (data.status) {
                                $("#diary-datagrid").datagrid('reload');
                                $("#edit-diary-dialog").dialog("close");
                            } else {
                                alert(data.message)
                            }
                        }
                    })
                }
                return false;
            }
        });
    }

    function doDeleteDiary() {
        var row = $('#diary-datagrid').datagrid('getSelected');
        if (row == null){
            return;
        }
        if (confirm("确定要删除权限吗?")){
            $.ajax({
                url:"<%=request.getContextPath()%>/diary.html?act=delete",
                data:"id=" + row.id,
                method:"post",
                success:function (data) {
                    if (data.status){
                        $("#diary-datagrid").datagrid('reload');
                    }else{
                        alert(data.message)
                    }
                }
            })
        }
    }

</script>

diary_edit.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--panel面板可以设置整体的高度--%>
<div class="easyui-panel" style="height: 95%">
    <table id="diary-datagrid" style="height:450px">
    </table>
    <div id="diary-datagrid-toolbar">
        <div>
            ID:<input type="text" class="easyui-numberbox" id="search-diary-id"/>
            标题:<input type="text" id="search-diary-title"/>
            昵称:<input type="text" id="search-diary-nickname"/>
            <a href="#" class="easyui-linkbutton" iconCls="icon-search"
               onclick="doDiarySearch()">搜索</a>
        </div>
        <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="doEditDiary(0)">新增</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="doEditDiary(1)">修改</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" plain="true" onclick="doDeleteDiary()">删除权限</a>
    </div>
</div>

<div class="easyui-dialog" closed="true" id="edit-diary-dialog"
     modal="true" title="编辑日记" style="width:800px;height:600px;padding:30px" buttons="#dlg-diary-buttons">
</div>
<div id="dlg-diary-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitDiary()">保存</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" onclick="$('#edit-diary-form').form('reset');">重填</a>
</div>
<link href="<%=request.getContextPath()%>/media/kindeditor-4.1.10/themes/default/default.css" type="text/css"
      rel="stylesheet">
<script type="text/javascript" charset="utf-8"
        src="<%=request.getContextPath()%>/media/kindeditor-4.1.10/kindeditor-all.js"></script>
<script type="text/javascript" charset="utf-8"
        src="<%=request.getContextPath()%>/media/kindeditor-4.1.10/lang/zh_CN.js"></script>

<script type="text/javascript">
    $(function () {
        $("#diary-datagrid").datagrid({
            url: "<%=request.getContextPath()%>/diary.html?act=list",
            pagination: true,
            pageList: [5, 10, 15, 20],
            toolbar: "#diary-datagrid-toolbar",
            frozen: true,//冻结标题行
            singleSelect:true,
            fit: true,//让表格自动适应面板的高度
            nowrap: false,//高度自适应,当内容比较多的时候会自动换行
            columns: [[
                {field: 'id', title: 'ID', width: 80},
                {field: 'title', title: '标题', width: 80},
                {field: 'createdDate', title: '发布时间', width: 160},
                {field: 'nickname', title: '作者', width: 80},
                {
                    field: 'status', title: '身份权限', width: 80, formatter: function (val, row) {
                    if (row.status == 0) return "<span style='color:red'>无效</span>";
                    return row.status
                }
                }
            ]]
        })
    })

    function doDiarySearch() {
        var queryParams = $('#diary-datagrid').datagrid('options').queryParams;
        queryParams.id = $("#search-diary-id").val();
        queryParams.title = $("#search-diary-title").val();
        queryParams.nickname = $("#search-diary-nickname").val();
        //重新加载datagrid
        $("#diary-datagrid").datagrid('reload');
    }

    var kingEditorParams = {
        filePostName: "file",//指定上传文件参数名称
        uploadJson: '<%=request.getContextPath()%>/diary.html?act=upload',//指定上传文件请求的url。
        dir: "image"//上传类型,分别为image、flash、media、file,
    }
    var editor;

    function doEditDiary(type) {
        var id = "";
        var row = $('#diary-datagrid').datagrid('getSelected');  //单选
        if (type == 1) {//要修改
            if (row == null) {
                alert("请选择要编辑的数据");
                return;
            }
            id = row.id;
        }
        $("#edit-diary-dialog").dialog({
            href: "<%=request.getContextPath()%>/diary.html?act=get&id=" + id,
            onLoad: function () {
                editor = KindEditor.create($("#editor"), kingEditorParams);
            },
            onBeforeDestroy: function () {
                KindEditor.remove("#editor");
            }
        }).dialog('open');
    }

    function submitDiary() {
        $('#edit-diary-form').form('submit', {
            onSubmit: function () {
                if ($(this).form('enableValidation').form('validate')) {
                    editor.sync();//同步富文本编辑器,否则拿不到
                    $.ajax({
                        url: "<%=request.getContextPath()%>/diary.html?act=edit",
                        data: $("#edit-diary-form").serialize(),
                        method: "post",
                        success: function (data) {
                            if (data.status) {
                                $("#diary-datagrid").datagrid('reload');
                                $("#edit-diary-dialog").dialog("close");
                            } else {
                                alert(data.message)
                            }
                        }
                    })
                }
                return false;
            }
        });
    }

    function doDeleteDiary() {
        var row = $('#diary-datagrid').datagrid('getSelected');
        if (row == null){
            return;
        }
        if (confirm("确定要删除权限吗?")){
            $.ajax({
                url:"<%=request.getContextPath()%>/diary.html?act=delete",
                data:"id=" + row.id,
                method:"post",
                success:function (data) {
                    if (data.status){
                        $("#diary-datagrid").datagrid('reload');
                    }else{
                        alert(data.message)
                    }
                }
            })
        }
    }

</script>








没有更多推荐了,返回首页