ssm框架

Posted yuanning1

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ssm框架相关的知识,希望对你有一定的参考价值。

  1. dependencies>
  2. <!-- mybatis核心包 -->
  3. <dependency>
  4. <groupId>org.mybatis</groupId>
  5. <artifactId>mybatis</artifactId>
  6. <version>3.4.1</version>
  7. </dependency>
  8. <!-- mysql驱动包 -->
  9. <dependency>
  10. <groupId>mysql</groupId>
  11. <artifactId>mysql-connector-java</artifactId>
  12. <version>5.1.29</version>
  13. </dependency>
  14. <!--日志包-->
  15. <dependency>
  16. <groupId>org.slf4j</groupId>
  17. <artifactId>slf4j-log4j12</artifactId>
  18. <version>1.6.1</version>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.slf4j</groupId>
  22. <artifactId>slf4j-api</artifactId>
  23. <version>1.6.1</version>
  24. </dependency>
  25. <!--spring数据库-->
  26. <dependency>
  27. <groupId>org.springframework</groupId>
  28. <artifactId>spring-jdbc</artifactId>
  29. <version>4.3.11.RELEASE</version>
  30. </dependency>
  31. <!--aop-->
  32. <dependency>
  33. <groupId>org.springframework</groupId>
  34. <artifactId>spring-aspects</artifactId>
  35. <version>4.3.11.RELEASE</version>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.springframework</groupId>
  39. <artifactId>spring-context</artifactId>
  40. <version>4.3.11.RELEASE</version>
  41. </dependency>
  42. <!--spring-mybatis整合包-->
  43. <dependency>
  44. <groupId>org.mybatis</groupId>
  45. <artifactId>mybatis-spring</artifactId>
  46. <version>1.3.1</version>
  47. </dependency>
  48. <!--spring MVC相关包-->
  49. <dependency>
  50. <groupId>org.springframework</groupId>
  51. <artifactId>spring-webmvc</artifactId>
  52. <version>4.3.11.RELEASE</version>
  53. </dependency>
  54. <!--JSTL的目的就是在JSTL页面中美观的输出数据,它内置了很多标签库,包括很多逻辑判断,迭代,函数,数据库标签-->
  55. <dependency>
  56. <groupId>jstl</groupId>
  57. <artifactId>jstl</artifactId>
  58. <version>1.2</version>
  59. </dependency>
  60. <!--mybatis分页插件-->
  61. <dependency>
  62. <groupId>com.github.pagehelper</groupId>
  63. <artifactId>pagehelper</artifactId>
  64. <version>4.2.1</version>
  65. </dependency>
  66. <!-- Jackson Json处理工具包 -->
  67. <dependency>
  68. <groupId>com.fasterxml.jackson.core</groupId>
  69. <artifactId>jackson-databind</artifactId>
  70. <version>2.7.4</version>
  71. </dependency>
  72. <!--文件上传包-->
  73. <dependency>
  74. <groupId>commons-fileupload</groupId>
  75. <artifactId>commons-fileupload</artifactId>
  76. <version>1.3.3</version>
  77. </dependency>
  78. </dependencies>
  79.  
  80. <!--构建项目需要的信息-->
  81. <build>
  82. <finalName>ssm-blog-admin</finalName>
  83. <!--这个元素描述了项目相关的所有资源路径列表,例如和项目相关的属性文件,这些资源被包含在最终的打包文件里。-->
  84. <!--maven工程默认只导入resources下的配置文件 -->
  85. <resources>
  86. <!--这个元素描述了项目相关或测试相关的所有资源路径,-->
  87. <!--导入mybatis-mapper.xml文件 -->
  88. <resource>
  89. <directory>src/main/java</directory>
  90. <includes>
  91. <include>**/*.xml</include>
  92. </includes>
  93. <filtering>true</filtering>
  94. </resource>
  95. <resource>
  96. <!--扫描存放资源的路径 -->
  97. <directory>src/main/resources</directory>
  98. <!--包含的内容列表 -->
  99. <includes>
  100. <include>**/*.xml</include>
  101. <include>**/*.properties</include>
  102. </includes>
  103. </resource>
  104. </resources>
  105. </build>

实体类pojo

Diary.java

  1. public class Diary {
  2. private Integer id; //主键ID
  3. private Integer userId; //用户ID
  4. private Date createdDate; //日记创建时间
  5. private String content; //日记内容
  6. private String title; //日记标题
  7. private int status; //身份权限,1:有效,0:无效
  8. private String nickname; //昵称
  9. private AdminUser adminUser; //管理员
  10.  
  11. public Integer getId() {
  12. return id;
  13. }
  14.  
  15. public void setId(Integer id) {
  16. this.id = id;
  17. }
  18.  
  19. public Integer getUserId() {
  20. return userId;
  21. }
  22.  
  23. public void setUserId(Integer userId) {
  24. this.userId = userId;
  25. }
  26. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
  27. public Date getCreatedDate() {
  28. return createdDate;
  29. }
  30.  
  31. public void setCreatedDate(Date createdDate) {
  32. this.createdDate = createdDate;
  33. }
  34.  
  35. public String getContent() {
  36. return content;
  37. }
  38.  
  39. public void setContent(String content) {
  40. this.content = content;
  41. }
  42.  
  43. public String getTitle() {
  44. return title;
  45. }
  46.  
  47. public void setTitle(String title) {
  48. this.title = title;
  49. }
  50.  
  51. public int getStatus() {
  52. return status;
  53. }
  54.  
  55. public void setStatus(int status) {
  56. this.status = status;
  57. }
  58.  
  59. public String getNickname() {
  60. return nickname;
  61. }
  62.  
  63. public void setNickname(String nickname) {
  64. this.nickname = nickname;
  65. }
  66.  
  67. public AdminUser getAdminUser() {
  68. return adminUser;
  69. }
  70.  
  71. public void setAdminUser(AdminUser adminUser) {
  72. this.adminUser = adminUser;
  73. }
  74. }


DAO层

DiaryDAO.java

  1. public interface DiaryDAO {
  2. //插入日记方法
  3. void addDiary(Diary diary);
  4. //查询日记列表
  5. List<Diary> getDiaryList(Diary diary);
  6. //根据id查询日记
  7. Diary getDiaryById(int id);
  8. //更新日记
  9. void updateDiary(Diary diary);
  10. //更新用户权限
  11. void updateDiaryStatus(Diary diary);
  12. }

 

DiaryMapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <!--namespace:对应dao层的全路径-->
  6. <mapper namespace="com.ssm.blog.dao.DiaryDAO">
  7.  
  8. <!--id:dao层中添加日记方法,parameterType:mapper接口方法接受的参数类型-->
  9. <insert id="addDiary" parameterType="Diary">
  10. INSERT INTO diary(USER_ID,CREATED_DATE,CONTENT,TITLE,STATUS)
  11. VALUES (#{userId},now(),#{content},#{title},#{status})
  12. </insert>
  13.  
  14. <!--id 下方resultMap,type 对应实体类名-->
  15. <resultMap id="diaryMap" type="Diary">
  16. <!--property对应实体类中属性名,column对应数据库中字段名-->
  17. <id property="id" column="ID"/>
  18. <result property="userId" column="USER_ID"/>
  19. <result property="createdDate" column="CREATED_DATE"/>
  20. <result property="content" column="CONTENT"/>
  21. <result property="title" column="TITLE"/>
  22. <result property="status" column="STATUS"/>
  23. </resultMap>
  24. <!--id对应DAO层查询列表方法名,parameterType:mapper接口方法接受的参数类型,resultMap对应上方id值-->
  25. <select id="getDiaryList" parameterType="Diary" resultMap="diaryMap">
  26. SELECT D.ID,D.TITLE,D.USER_ID,D.CREATED_DATE,D.CONTENT,D.STATUS,A.NICKNAME
  27. FROM diary D
  28. INNER JOIN ADMIN_USER A ON D.USER_ID=A.ID
  29. <where>
  30. <if test="id !=null">D.ID=#{id}</if>
  31. <if test="title !=null and title!=‘‘">and TITLE like concat(‘%‘,#{title},‘%‘)</if>
  32. <if test="nickname !=null and nickname!=‘‘">and NICKNAME like concat(‘%‘,#{nickname},‘%‘)</if>
  33. </where>
  34. </select>
  35.  
  36. <!--根据id查询,用户点击修改时回显数据-->
  37. <!--id:dao层中根据id查询日记方法,parameterType:mapper接口方法接受的参数类型-->
  38. <select id="getDiaryById" parameterType="int" resultMap="diaryMap">
  39. SELECT ID,TITLE,CONTENT,STATUS
  40. FROM Diary
  41. WHERE ID=#{id}
  42. </select>
  43.  
  44. <!--id:dao层中更新日记方法,parameterType:mapper接口方法接受的参数类型-->
  45. <update id="updateDiary" parameterType="Diary">
  46. update diary set TITLE=#{title},CONTENT=#{content},STATUS=#{status}
  47. where ID=#{id}
  48. </update>
  49.  
  50. <!--修改用户权限,点击删除后将权限为1的修改为权限为0的-->
  51. <!--id:dao层中更改权限方法,parameterType:mapper接口方法接受的参数类型-->
  52. <update id="updateDiaryStatus" parameterType="Diary">
  53. update diary set STATUS=0
  54. where ID=#{id}
  55. </update>
  56. </mapper>


service层

DiaryService.java

  1. public interface DiaryService {
  2. //插入日记
  3. void addDiary(Diary diary);
  4.  
  5. //查询日记列表并分页
  6. PageInfo<Diary> getDiaryList(Diary diary,int pageNum,int pageSize);
  7.  
  8. //根据id查询,用于回显
  9. Diary getDiaryById(Integer id);
  10.  
  11. //更新日记
  12. void updateDiary(Diary diary);
  13. //更改权限
  14. void updateDiaryStatus(int id);
  15. }

 

service层  DiarySrviceImpl.java

  1. //加service注解
  2. @Service
  3. public class DiaryServiceImpl implements DiaryService {
  4. // 当Spring发现@Autowired注解时,将自动在代码上下文中找到和其匹配(默认是类型匹配)的Bean,
  5. // 并自动注入到相应的地方去。
  6. @Autowired
  7. private DiaryDAO diaryDAO;
  8.  
  9. //插入日记
  10. @Override
  11. public void addDiary(Diary diary) {
  12. diaryDAO.addDiary(diary);
  13. }
  14. //查询日记列表并分页
  15. @Override
  16. public PageInfo<Diary> getDiaryList(Diary diary, int pageNum, int pageSize) {
  17. PageHelper.startPage(pageNum, pageSize);
  18. List<Diary> diaryList = diaryDAO.getDiaryList(diary);
  19. PageInfo<Diary> pageInfo = new PageInfo<>(diaryList);
  20. return pageInfo;
  21. }
  22. //根据id查询日记
  23. @Override
  24. public Diary getDiaryById(Integer id) {
  25. return diaryDAO.getDiaryById(id);
  26. }
  27. //更新日记
  28. @Override
  29. public void updateDiary(Diary diary) {
  30. diaryDAO.updateDiary(diary);
  31. }
  32. //更新身份权限
  33. @Override
  34. public void updateDiaryStatus(int id) {
  35. Diary diary = diaryDAO.getDiaryById(id);
  36.  
  37. diaryDAO.updateDiaryStatus(diary);
  38. }
  39. }
  40.  

controller层

 DiaryController.java

  1. //加controller注解,处理由DispatcherServlet分发的请求
  2. @Controller
  3. //定义url
  4. @RequestMapping("/diary.html")
  5. public class DiaryController {
  6. @Autowired
  7. private DiaryService diaryService;
  8.  
  9. @RequestMapping(params = "act=edit")
  10. @ResponseBody //这个注解表示该方法的返回结果直接写入HTTP response body中,一般在异步获取数据时使用。
  11. //添加和修改,一个方法实现两个功能
  12. public Map<String,Object> edit(Diary diary){
  13. if (diary.getId() == null) {
  14. //从session中获取user的信息,后面写完登录再改
  15. diary.setUserId(2);
  16. diaryService.addDiary(diary);
  17. }else{
  18. //修改
  19. diaryService.updateDiary(diary);
  20. }
  21. return JsonUtils.getSuccessMessage("编辑成功",null);
  22. }
  23.  
  24. //查询日记列表并分页
  25. @RequestMapping(params = "act=list")
  26. @ResponseBody
  27. public Map<String,Object> list(Diary diary, int page, int rows){
  28. PageInfo<Diary> pageInfo = diaryService.getDiaryList(diary, page, rows);
  29. return JsonUtils.getDatagridPagerResult(pageInfo.getTotal(),pageInfo.getList());
  30. }
  31.  
  32. //根据id查询所有,用于点击修改后回显
  33. @RequestMapping(params = "act=get")
  34. public ModelAndView getDiary(Integer id){
  35. Diary diary = null;
  36. if (id!=null){
  37. diary = diaryService.getDiaryById(id);
  38. }
  39. return new ModelAndView("diary_edit","diary",diary);
  40. }
  41.  
  42. //文件上传
  43. @Value("${DIARY_IMAGE_DIR}")
  44. private String DIARY_IMAGE_DIR;
  45. @Value("${DIARY_IMAGE_URL}")
  46. private String DIARY_IMAGE_URL;
  47.  
  48. @RequestMapping(params = "act=upload")
  49. @ResponseBody
  50. public String upload(MultipartFile file) {
  51. return JsonUtils.fileUpload(file,DIARY_IMAGE_DIR,DIARY_IMAGE_URL);
  52. }
  53.  
  54. //删除(修改权限)
  55. @RequestMapping(params = "act=delete")
  56. @ResponseBody
  57. public Map<String,Object> delete(int id){
  58. Diary diary = diaryService.getDiaryById(id);
  59. if (diary.getStatus()!=0){
  60. diaryService.updateDiaryStatus(id);
  61. }
  62. return JsonUtils.getSuccessMessage("删除权限成功",null);
  63. }
  64. }


util工具类

JsonUtils.java

  1. public class JsonUtils {
  2. public static Map<String,Object> getSuccessMessage(String message,Object other){
  3. Map<String,Object> result = new HashMap<>();
  4. result.put("status", true);
  5. result.put("message", "添加成功");
  6. result.put("other",other);
  7. return result;
  8. }
  9.  
  10. public static Map<String,Object> getErrorMessage(String message,Object other){
  11. Map<String,Object> result = new HashMap<>();
  12. result.put("status", false);
  13. result.put("message", "添加成功");
  14. result.put("other",other);
  15. return result;
  16. }
  17.  
  18. public static Map<String,Object> getDatagridPagerResult(long total, List list){
  19. Map<String,Object> result = new HashMap<>();
  20. result.put("total",total); //总条数
  21. result.put("rows",list); //返回的list数据
  22. return result;
  23. }
  24.  
  25. public static String fileUpload(MultipartFile file,String DIR,String URL){
  26. String oldFileName = file.getOriginalFilename();
  27. String extName = oldFileName.substring(oldFileName.lastIndexOf("."));
  28. String newFileName = System.currentTimeMillis()+extName;
  29. try {
  30. FileUtils.copyInputStreamToFile(file.getInputStream(),new File(DIR,newFileName));
  31. return "{"error":0,"url":"" + URL + newFileName + ""}";
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. return "{"error":1}";
  35. }
  36. }
  37. }


resource

db.properties:配置mysql

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

 

log4j.properties:输出日志信息

  1. log4j.rootLogger=DEBUG, stdout
  2.  
  3. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  4. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  5. log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
  6.  
  7. #begin
  8. #for normal test,delete when online
  9. log4j.logger.com.ibatis=DEBUG
  10. log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
  11. log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
  12. log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
  13.  
  14. log4j.logger.java.sql.Connection=DEBUG
  15. log4j.logger.java.sql.Statement=DEBUG
  16. log4j.logger.java.sql.PreparedStatement=DEBUG
  17. log4j.logger.java.sql.ResultSet=DEBUG

 

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

  1. DIARY_IMAGE_DIR=E:/upload/diary/
  2.  
  3. DIARY_IMAGE_URL=http://localhost:8080/upload/diary/


spring-config.xml

  1. <!--读取配置文件-->
  2. <context:property-placeholder location="classpath:db.properties" ignore-unresolvable="true"/>
  3. <!--从配置文件中获取数据源-->
  4. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  5. <property name="driverClassName" value="${jdbc.driver}"/>
  6. <property name="url" value="${jdbc.url}"/>
  7. <property name="username" value="${jdbc.username}"/>
  8. <property name="password" value="${jdbc.password}"/>
  9. </bean>
  10.  
  11. <!-- 启动自动扫描 -->
  12. <context:component-scan base-package="com.ssm.blog.*">
  13. <!-- 制定扫包规则 ,不扫描@Controller注解的JAVA类 -->
  14. <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  15. </context:component-scan>
  16.  
  17. <!--spring管理session工厂-->
  18. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  19. <property name="dataSource" ref="dataSource"/>
  20. <property name="mapperLocations" value="classpath:com/ssm/blog/dao/mapper/*.xml"/>
  21. <property name="typeAliasesPackage" value="com.ssm.blog.pojo"/>
  22. <property name="plugins">
  23. <array>
  24. <bean class="com.github.pagehelper.PageHelper">
  25. <property name="properties">
  26. <value>
  27. dialect=mysql
  28. reasonable=true
  29. </value>
  30. </property>
  31. </bean>
  32. </array>
  33. </property>
  34. </bean>
  35. <!--扫描所有mybatis的dao接口,生成代理实现类-->
  36. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  37. <property name="basePackage" value="com.ssm.blog.dao"/>
  38. </bean>
  39. <!-- 配置事务管理器 -->
  40. <bean id="transactionManager"
  41. class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  42. <property name="dataSource" ref="dataSource"/>
  43. </bean>
  44. <!--事务增强-->
  45. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  46. <tx:attributes>
  47. <!-- 传播行为,匹配的是方法名 -->
  48. <tx:method name="add*" rollback-for="Exception"/>
  49. <tx:method name="delete*" rollback-for="Exception"/>
  50. <tx:method name="update*" rollback-for="Exception"/>
  51. <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
  52. <tx:method name="do*" rollback-for="Exception"/>
  53. </tx:attributes>
  54. </tx:advice>
  55. <!-- 通过AOP配置提供事务增强,让service包下所有Bean的所有方法拥有事务 -->
  56. <aop:config>
  57. <aop:pointcut id="serviceMethod"
  58. expression="execution(* com.ssm.blog.service..*(..))"/>
  59. <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>
  60. </aop:config>

 

WEB-INF

springMVC-servlet.xml

  1. <!--加载下方返回值转换器-->
  2. <mvc:annotation-driven content-negotiation-manager="contentNegotiationManagerFactoryBean"/>
  3. <!--扫描过滤器-->
  4. <context:component-scan base-package="com.ssm.blog.controller">
  5. <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  6. </context:component-scan>
  7. <!-- 配置视图解析器-->
  8. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  9. <property name="prefix" value="/"></property><!--前缀-->
  10. <property name="suffix" value=".jsp"></property><!--后缀-->
  11. </bean>
  12. <!--加载media下的easyui和富文本编辑器-->
  13. <mvc:resources mapping="/media/**" location="/media/"/>
  14. <!--配置返回值转换器-->
  15. <bean id="contentNegotiationManagerFactoryBean"
  16. class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
  17. <property name="favorPathExtension" value="false"/>
  18. <property name="favorParameter" value="false"/>
  19. <property name="ignoreAcceptHeader" value="false"/>
  20. <property name="mediaTypes">
  21. <map>
  22. <entry key="json" value="application/json"/>
  23. </map>
  24. </property>
  25. </bean>
  26. <!--文件上传解析器-->
  27. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  28. <property name="maxUploadSize" value="1048576"/>
  29. <property name="defaultEncoding" value="UTF-8"/>
  30. <property name="resolveLazily" value="true"/>
  31. </bean>


web.xml

  1. <!--加载spring-config.xml-->
  2. <context-param>
  3. <param-name>contextConfigLocation</param-name>
  4. <param-value>classpath:spring-config.xml</param-value>
  5. </context-param>
  6. <!--配置listener,在启动Web容器的时候加载Spring的配置-->
  7. <listener>
  8. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  9. </listener>
  10. <filter>
  11. <filter-name>CharacterEncodingFilter</filter-name>
  12. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  13. <init-param>
  14. <param-name>encoding</param-name>
  15. <param-value>UTF-8</param-value>
  16. </init-param>
  17. <init-param>
  18. <param-name>forceEncoding</param-name>
  19. <param-value>true</param-value>
  20. </init-param>
  21. </filter>
  22. <filter-mapping>
  23. <filter-name>CharacterEncodingFilter</filter-name>
  24. <url-pattern>/*</url-pattern>
  25. </filter-mapping>
  26. <!--配置DispatcherServlet -->
  27. <servlet>
  28. <servlet-name>springMVC</servlet-name>
  29. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  30. </servlet>
  31. <servlet-mapping>
  32. <servlet-name>springMVC</servlet-name>
  33. <url-pattern>*.html</url-pattern>
  34. </servlet-mapping>
  35. <welcome-file-list>
  36. <welcome-file>/blog/list.html</welcome-file>
  37. </welcome-file-list>


diary_list.jsp

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <%--panel面板可以设置整体的高度--%>
  3. <div class="easyui-panel" style="height: 95%">
  4. <table id="diary-datagrid" style="height:450px">
  5. </table>
  6. <div id="diary-datagrid-toolbar">
  7. <div>
  8. ID:<input type="text" class="easyui-numberbox" id="search-diary-id"/>
  9. 标题:<input type="text" id="search-diary-title"/>
  10. 昵称:<input type="text" id="search-diary-nickname"/>
  11. <a href="#" class="easyui-linkbutton" iconCls="icon-search"
  12. οnclick="doDiarySearch()">搜索</a>
  13. </div>
  14. <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" οnclick="doEditDiary(0)">新增</a>
  15. <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" οnclick="doEditDiary(1)">修改</a>
  16. <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" plain="true" οnclick="doDeleteDiary()">删除权限</a>
  17. </div>
  18. </div>
  19.  
  20. <div class="easyui-dialog" closed="true" id="edit-diary-dialog"
  21. modal="true" title="编辑日记" style="width:800px;height:600px;padding:30px" buttons="#dlg-diary-buttons">
  22. </div>
  23. <div id="dlg-diary-buttons">
  24. <a href="javascript:void(0)" class="easyui-linkbutton" οnclick="submitDiary()">保存</a>
  25. <a href="javascript:void(0)" class="easyui-linkbutton" οnclick="$(‘#edit-diary-form‘).form(‘reset‘);">重填</a>
  26. </div>
  27. <link href="<%=request.getContextPath()%>/media/kindeditor-4.1.10/themes/default/default.css" type="text/css"
  28. rel="stylesheet">
  29. <script type="text/javascript" charset="utf-8"
  30. src="<%=request.getContextPath()%>/media/kindeditor-4.1.10/kindeditor-all.js"></script>
  31. <script type="text/javascript" charset="utf-8"
  32. src="<%=request.getContextPath()%>/media/kindeditor-4.1.10/lang/zh_CN.js"></script>
  33.  
  34. <script type="text/javascript">
  35. $(function () {
  36. $("#diary-datagrid").datagrid({
  37. url: "<%=request.getContextPath()%>/diary.html?act=list",
  38. pagination: true,
  39. pageList: [5, 10, 15, 20],
  40. toolbar: "#diary-datagrid-toolbar",
  41. frozen: true,//冻结标题行
  42. singleSelect:true,
  43. fit: true,//让表格自动适应面板的高度
  44. nowrap: false,//高度自适应,当内容比较多的时候会自动换行
  45. columns: [[
  46. {field: ‘id‘, title: ‘ID‘, width: 80},
  47. {field: ‘title‘, title: ‘标题‘, width: 80},
  48. {field: ‘createdDate‘, title: ‘发布时间‘, width: 160},
  49. {field: ‘nickname‘, title: ‘作者‘, width: 80},
  50. {
  51. field: ‘status‘, title: ‘身份权限‘, width: 80, formatter: function (val, row) {
  52. if (row.status == 0) return "<span style=‘color:red‘>无效</span>";
  53. return row.status
  54. }
  55. }
  56. ]]
  57. })
  58. })
  59.  
  60. function doDiarySearch() {
  61. var queryParams = $(‘#diary-datagrid‘).datagrid(‘options‘).queryParams;
  62. queryParams.id = $("#search-diary-id").val();
  63. queryParams.title = $("#search-diary-title").val();
  64. queryParams.nickname = $("#search-diary-nickname").val();
  65. //重新加载datagrid
  66. $("#diary-datagrid").datagrid(‘reload‘);
  67. }
  68.  
  69. var kingEditorParams = {
  70. filePostName: "file",//指定上传文件参数名称
  71. uploadJson: ‘<%=request.getContextPath()%>/diary.html?act=upload‘,//指定上传文件请求的url。
  72. dir: "image"//上传类型,分别为image、flash、media、file,
  73. }
  74. var editor;
  75.  
  76. function doEditDiary(type) {
  77. var id = "";
  78. var row = $(‘#diary-datagrid‘).datagrid(‘getSelected‘); //单选
  79. if (type == 1) {//要修改
  80. if (row == null) {
  81. alert("请选择要编辑的数据");
  82. return;
  83. }
  84. id = row.id;
  85. }
  86. $("#edit-diary-dialog").dialog({
  87. href: "<%=request.getContextPath()%>/diary.html?act=get&id=" + id,
  88. onLoad: function () {
  89. editor = KindEditor.create($("#editor"), kingEditorParams);
  90. },
  91. onBeforeDestroy: function () {
  92. KindEditor.remove("#editor");
  93. }
  94. }).dialog(‘open‘);
  95. }
  96.  
  97. function submitDiary() {
  98. $(‘#edit-diary-form‘).form(‘submit‘, {
  99. onSubmit: function () {
  100. if ($(this).form(‘enableValidation‘).form(‘validate‘)) {
  101. editor.sync();//同步富文本编辑器,否则拿不到
  102. $.ajax({
  103. url: "<%=request.getContextPath()%>/diary.html?act=edit",
  104. data: $("#edit-diary-form").serialize(),
  105. method: "post",
  106. success: function (data) {
  107. if (data.status) {
  108. $("#diary-datagrid").datagrid(‘reload‘);
  109. $("#edit-diary-dialog").dialog("close");
  110. } else {
  111. alert(data.message)
  112. }
  113. }
  114. })
  115. }
  116. return false;
  117. }
  118. });
  119. }
  120.  
  121. function doDeleteDiary() {
  122. var row = $(‘#diary-datagrid‘).datagrid(‘getSelected‘);
  123. if (row == null){
  124. return;
  125. }
  126. if (confirm("确定要删除权限吗?")){
  127. $.ajax({
  128. url:"<%=request.getContextPath()%>/diary.html?act=delete",
  129. data:"id=" + row.id,
  130. method:"post",
  131. success:function (data) {
  132. if (data.status){
  133. $("#diary-datagrid").datagrid(‘reload‘);
  134. }else{
  135. alert(data.message)
  136. }
  137. }
  138. })
  139. }
  140. }
  141.  
  142. </script>


diary_edit.jsp

    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <%--panel面板可以设置整体的高度--%>
    3. <div class="easyui-panel" style="height: 95%">
    4. <table id="diary-datagrid" style="height:450px">
    5. </table>
    6. <div id="diary-datagrid-toolbar">
    7. <div>
    8. ID:<input type="text" class="easyui-numberbox" id="search-diary-id"/>
    9. 标题:<input type="text" id="search-diary-title"/>
    10. 昵称:<input type="text" id="search-diary-nickname"/>
    11. <a href="#" class="easyui-linkbutton" iconCls="icon-search"
    12. οnclick="doDiarySearch()">搜索</a>
    13. </div>
    14. <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" οnclick="doEditDiary(0)">新增</a>
    15. <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" οnclick="doEditDiary(1)">修改</a>
    16. <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" plain="true" οnclick="doDeleteDiary()">删除权限</a>
    17. </div>
    18. </div>
    19.  
    20. <div class="easyui-dialog" closed="true" id="edit-diary-dialog"
    21. modal="true" title="编辑日记" style="width:800px;height:600px;padding:30px" buttons="#dlg-diary-buttons">
    22. </div>
    23. <div id="dlg-diary-buttons">
    24. <a href="javascript:void(0)" class="easyui-linkbutton" οnclick="submitDiary()">保存</a>
    25. <a href="javascript:void(0)" class="easyui-linkbutton" οnclick="$(‘#edit-diary-form‘).form(‘reset‘);">重填</a>
    26. </div>
    27. <link href="<%=request.getContextPath()%>/media/kindeditor-4.1.10/themes/default/default.css" type="text/css"
    28. rel="stylesheet">
    29. <script type="text/javascript" charset="utf-8"
    30. src="<%=request.getContextPath()%>/media/kindeditor-4.1.10/kindeditor-all.js"></script>
    31. <script type="text/javascript" charset="utf-8"
    32. src="<%=request.getContextPath()%>/media/kindeditor-4.1.10/lang/zh_CN.js"></script>
    33.  
    34. <script type="text/javascript">
    35. $(function () {
    36. $("#diary-datagrid").datagrid({
    37. url: "<%=request.getContextPath()%>/diary.html?act=list",
    38. pagination: true,
    39. pageList: [5, 10, 15, 20],
    40. toolbar: "#diary-datagrid-toolbar",
    41. frozen: true,//冻结标题行
    42. singleSelect:true,
    43. fit: true,//让表格自动适应面板的高度
    44. nowrap: false,//高度自适应,当内容比较多的时候会自动换行
    45. columns: [[
    46. {field: ‘id‘, title: ‘ID‘, width: 80},
    47. {field: ‘title‘, title: ‘标题‘, width: 80},
    48. {field: ‘createdDate‘, title: ‘发布时间‘, width: 160},
    49. {field: ‘nickname‘, title: ‘作者‘, width: 80},
    50. {
    51. field: ‘status‘, title: ‘身份权限‘, width: 80, formatter: function (val, row) {
    52. if (row.status == 0) return "<span style=‘color:red‘>无效</span>";
    53. return row.status
    54. }
    55. }
    56. ]]
    57. })
    58. })
    59.  
    60. function doDiarySearch() {
    61. var queryParams = $(‘#diary-datagrid‘).datagrid(‘options‘).queryParams;
    62. queryParams.id = $("#search-diary-id").val();
    63. queryParams.title = $("#search-diary-title").val();
    64. queryParams.nickname = $("#search-diary-nickname").val();
    65. //重新加载datagrid
    66. $("#diary-datagrid").datagrid(‘reload‘);
    67. }
    68.  
    69. var kingEditorParams = {
    70. filePostName: "file",//指定上传文件参数名称
    71. uploadJson: ‘<%=request.getContextPath()%>/diary.html?act=upload‘,//指定上传文件请求的url。
    72. dir: "image"//上传类型,分别为image、flash、media、file,
    73. }
    74. var editor;
    75.  
    76. function doEditDiary(type) {
    77. var id = "";
    78. var row = $(‘#diary-datagrid‘).datagrid(‘getSelected‘); //单选
    79. if (type == 1) {//要修改
    80. if (row == null) {
    81. alert("请选择要编辑的数据");
    82. return;
    83. }
    84. id = row.id;
    85. }
    86. $("#edit-diary-dialog").dialog({
    87. href: "<%=request.getContextPath()%>/diary.html?act=get&id=" + id,
    88. onLoad: function () {
    89. editor = KindEditor.create($("#editor"), kingEditorParams);
    90. },
    91. onBeforeDestroy: function () {
    92. KindEditor.remove("#editor");
    93. }
    94. }).dialog(‘open‘);
    95. }
    96.  
    97. function submitDiary() {
    98. $(‘#edit-diary-form‘).form(‘submit‘, {
    99. onSubmit: function () {
    100. if ($(this).form(‘enableValidation‘).form(‘validate‘)) {
    101. editor.sync();//同步富文本编辑器,否则拿不到
    102. $.ajax({
    103. url: "<%=request.getContextPath()%>/diary.html?act=edit",
    104. data: $("#edit-diary-form").serialize(),
    105. method: "post",
    106. success: function (data) {
    107. if (data.status) {
    108. $("#diary-datagrid").datagrid(‘reload‘);
    109. $("#edit-diary-dialog").dialog("close");
    110. } else {
    111. alert(data.message)
    112. }
    113. }
    114. })
    115. }
    116. return false;
    117. }
    118. });
    119. }
    120.  
    121. function doDeleteDiary() {
    122. var row = $(‘#diary-datagrid‘).datagrid(‘getSelected‘);
    123. if (row == null){
    124. return;
    125. }
    126. if (confirm("确定要删除权限吗?")){
    127. $.ajax({
    128. url:"<%=request.getContextPath()%>/diary.html?act=delete",
    129. data:"id=" + row.id,
    130. method:"post",
    131. success:function (data) {
    132. if (data.status){
    133. $("#diary-datagrid").datagrid(‘reload‘);
    134. }else{
    135. alert(data.message)
    136. }
    137. }
    138. })
    139. }
    140. }
    141.  
    142. </script>

以上是关于ssm框架的主要内容,如果未能解决你的问题,请参考以下文章

ssm框架物资审批功能

什么是ssm框架

SSM框架 SSM项目源码 SSM源码

SSM框架 SSM项目源码 SSM源码

SSM框架项目搭建系列—SSM框架的简介及搭建流程

ssm框架,数据库问题