SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现

一、用myEclipse初始化Web项目

新建一个web project:

SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现

二、创建包

controller        //控制类

service //服务接口
service.impl
//服务实现类
dao  //data access object(接口)
dao.impl  //实现类

domain  //实体类

mappers  //mybatis的配置映射文件
        util             //工具类

SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现

三、是maven方式引入类库

3.1启动tomcat服务

3.2给web项目添加maven支持(引入maven私服库)

将web项目转化为maven项目:

SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现

3.3引入依赖

spring

mybatis
spring mvc
c3p0类库
MySQL

.......

3.4主要是编写pom.xml文件

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  2. <modelVersion>4.0.0</modelVersion>
  3. <groupId>com.liuhai</groupId>
  4. <artifactId>eshopSSM</artifactId>
  5. <version>0.0.1-SNAPSHOT</version>
  6. <packaging>war</packaging>
  7. <properties>
  8. <log4j.version>1.2.17</log4j.version>
  9. <slf4j.version>1.7.7</slf4j.version>
  10. </properties>
  11. <build>
  12. <sourceDirectory>src</sourceDirectory>
  13. <resources>
  14. <resource>
  15. <directory>src</directory>
  16. <excludes>
  17. <exclude>**/*.java</exclude>
  18. </excludes>
  19. </resource>
  20. </resources>
  21. <plugins>
  22. <plugin>
  23. <artifactId>maven-compiler-plugin</artifactId>
  24. <version>3.1</version>
  25. <configuration>
  26. <source>1.7</source>
  27. <target>1.7</target>
  28. </configuration>
  29. </plugin>
  30. <plugin>
  31. <artifactId>maven-war-plugin</artifactId>
  32. <version>2.3</version>
  33. <configuration>
  34. <warSourceDirectory>WebRoot</warSourceDirectory>
  35. <failOnMissingWebXml>false</failOnMissingWebXml>
  36. <version>3.0</version>
  37. </configuration>
  38. </plugin>
  39. </plugins>
  40. </build>
  41. <dependencies>
  42. <!-- webmvc -->
  43. <dependency>
  44. <groupId>org.springframework</groupId>
  45. <artifactId>spring-webmvc</artifactId>
  46. <version>4.0.2.RELEASE</version>
  47. </dependency>
  48. <dependency>
  49. <groupId>org.springframework</groupId>
  50. <artifactId>spring-jdbc</artifactId>
  51. <version>4.0.2.RELEASE</version>
  52. </dependency>
  53. <dependency>
  54. <groupId>org.springframework</groupId>
  55. <artifactId>spring-tx</artifactId>
  56. <version>4.0.2.RELEASE</version>
  57. </dependency>
  58. <dependency>
  59. <groupId>org.springframework</groupId>
  60. <artifactId>spring-context-support</artifactId>
  61. <version>4.0.2.RELEASE</version>
  62. </dependency>
  63. <dependency>
  64. <groupId>org.springframework</groupId>
  65. <artifactId>spring-orm</artifactId>
  66. <version>4.0.2.RELEASE</version>
  67. </dependency>
  68. <!-- 导入Mysql数据库链接jar包 -->
  69. <dependency>
  70. <groupId>mysql</groupId>
  71. <artifactId>mysql-connector-java</artifactId>
  72. <version>5.1.17</version>
  73. </dependency>
  74. <!--c3p0 用来在applicationContext.xml中配置数据库   -->
  75. <dependency>
  76. <groupId>com.mchange</groupId>
  77. <artifactId>c3p0</artifactId>
  78. <version>0.9.5.2</version>
  79. </dependency>
  80. <!-- JSTL标签类 -->
  81. <dependency>
  82. <groupId>javax.servlet</groupId>
  83. <artifactId>jstl</artifactId>
  84. <version>1.2</version>
  85. </dependency>
  86. <dependency>
  87. <groupId>commons-io</groupId>
  88. <artifactId>commons-io</artifactId>
  89. <version>2.4</version>
  90. </dependency>
  91. <!-- mybatis核心包 -->
  92. <dependency>
  93. <groupId>org.mybatis</groupId>
  94. <artifactId>mybatis</artifactId>
  95. <version>3.1.1</version>
  96. </dependency>
  97. <!-- mybatis/spring包 -->
  98. <dependency>
  99. <groupId>org.mybatis</groupId>
  100. <artifactId>mybatis-spring</artifactId>
  101. <version>1.2.0</version>
  102. </dependency>
  103. <!-- 映入JSON 对象转json转换器,主要用来restful用-->
  104. <dependency>
  105. <groupId>org.codehaus.jackson</groupId>
  106. <artifactId>jackson-mapper-asl</artifactId>
  107. <version>1.9.4</version>
  108. </dependency>
  109. <!-- log start -->
  110. <dependency>
  111. <groupId>log4j</groupId>
  112. <artifactId>log4j</artifactId>
  113. <version>${log4j.version}</version>
  114. </dependency>
  115. <dependency>
  116. <groupId>org.slf4j</groupId>
  117. <artifactId>slf4j-api</artifactId>
  118. <version>${slf4j.version}</version>
  119. </dependency>
  120. <dependency>
  121. <groupId>org.slf4j</groupId>
  122. <artifactId>slf4j-log4j12</artifactId>
  123. <version>${slf4j.version}</version>
  124. </dependency>
  125. <!-- log end -->
  126. <!-- 上传组件包begin -->
  127. <dependency>
  128. <groupId>commons-fileupload</groupId>
  129. <artifactId>commons-fileupload</artifactId>
  130. <version>1.3.1</version>
  131. </dependency>
  132. <dependency>
  133. <groupId>commons-io</groupId>
  134. <artifactId>commons-io</artifactId>
  135. <version>2.4</version>
  136. </dependency>
  137. <!-- 上传组件包end -->
  138. <!-- json解析包 -->
  139. <dependency>
  140. <groupId>net.sf.json-lib</groupId>
  141. <artifactId>json-lib</artifactId>
  142. <version>2.4</version>
  143. </dependency>
  144. </dependencies>
  145. </project>

四、创建dao和service的基础类库

UserDao.Java如下:

  1. package com.liuhai.eshop.dao;
  2. import java.util.List;
  3. import java.util.Map;
  4. import com.liuhai.eshop.domain.User;
  5. /**
  6. * 用户DAO接口
  7. * @author Administrator
  8. *
  9. */
  10. public interface UserDao {
  11. /**
  12. * 用户登录
  13. * @param user
  14. * @return
  15. */
  16. public User login(User user);
  17. /**
  18. * 查询所有用户
  19. * @return
  20. */
  21. public List<User> getAll();
  22. /**
  23. * 根据条件查询用户
  24. * @param user
  25. * @return
  26. */
  27. public User getUser(User user);
  28. /**
  29. * 删除用户
  30. * @param user
  31. * @return
  32. */
  33. public int delete(int id);
  34. /**
  35. * 更新用户
  36. * @param user
  37. * @return
  38. */
  39. public int update(User user);
  40. /**
  41. * 添加用户
  42. * @param user
  43. * @return
  44. */
  45. public int add(User user);
  46. /**
  47. * 用户查询
  48. * @param map
  49. * @return
  50. */
  51. public List<User> find(Map<String,Object> map);
  52. /**
  53. * 获取总记录数
  54. * @param map
  55. * @return
  56. */
  57. public Long getTotal(Map<String,Object> map);
  58. /**
  59. * 根据id查询用户
  60. * @param id
  61. * @return
  62. */
  63. public User getUserById(int id);
  64. }

UserService.java 用户service层接口如下:

  1. package com.liuhai.eshop.service;
  2. import java.util.List;
  3. import java.util.Map;
  4. import com.liuhai.eshop.domain.User;
  5. public interface UserService {
  6. public List<User> getAll();
  7. public User getUser(User user);
  8. public int delete(int id);
  9. public int update(User user);
  10. public int add(User user);
  11. public List<User> find(Map<String,Object> map);
  12. public Long getTotal(Map<String,Object> map);
  13. public User getUserById(int id);
  14. }

UserServiceImpl.java 用户service实现层如下:

  1. package com.liuhai.eshop.service.impl;
  2. import java.util.List;
  3. import java.util.Map;
  4. import javax.annotation.Resource;
  5. import org.springframework.stereotype.Service;
  6. import com.liuhai.eshop.dao.UserDao;
  7. import com.liuhai.eshop.domain.User;
  8. import com.liuhai.eshop.service.UserService;
  9. @Service(value="userService")
  10. public class UserServiceImpl implements UserService {
  11. private UserDao userDao;
  12. @Resource
  13. public void setUserDao(UserDao userDao) {
  14. this.userDao = userDao;
  15. }
  16. @Override
  17. public List<User> getAll() {
  18. return userDao.getAll();
  19. }
  20. @Override
  21. public User getUser(User user) {
  22. return userDao.getUser(user);
  23. }
  24. @Override
  25. public int delete(int id) {
  26. return userDao.delete(id);
  27. }
  28. @Override
  29. public int update(User user) {
  30. return userDao.update(user);
  31. }
  32. @Override
  33. public int add(User user) {
  34. return userDao.add(user);
  35. }
  36. @Override
  37. public List<User> find(Map<String, Object> map) {
  38. return userDao.find(map);
  39. }
  40. @Override
  41. public Long getTotal(Map<String, Object> map) {
  42. return userDao.getTotal(map);
  43. }
  44. public User getUserById(int id){
  45. return userDao.getUserById(id);
  46. }
  47. }

user实体类如下:

  1. package com.liuhai.eshop.domain;
  2. import java.io.Serializable;
  3. /**
  4. * 用户实体
  5. * @author Administrator
  6. *
  7. */
  8. public class User implements Serializable{
  9. private static final long serialVersionUID = 1L;
  10. private Integer id;
  11. private String userName;
  12. private String password;
  13. private Integer age;
  14. private String trueName;
  15. private String email;
  16. private String phone;
  17. private String roleName;
  18. public Integer getId() {
  19. return id;
  20. }
  21. public void setId(Integer id) {
  22. this.id = id;
  23. }
  24. public Integer getAge() {
  25. return age;
  26. }
  27. public void setAge(Integer age) {
  28. this.age = age;
  29. }
  30. public String getPassword() {
  31. return password;
  32. }
  33. public void setPassword(String password) {
  34. this.password = password;
  35. }
  36. public String getUserName() {
  37. return userName;
  38. }
  39. public void setUserName(String userName) {
  40. this.userName = userName;
  41. }
  42. public String getTrueName() {
  43. return trueName;
  44. }
  45. public void setTrueName(String trueName) {
  46. this.trueName = trueName;
  47. }
  48. public String getEmail() {
  49. return email;
  50. }
  51. public void setEmail(String email) {
  52. this.email = email;
  53. }
  54. public String getPhone() {
  55. return phone;
  56. }
  57. public void setPhone(String phone) {
  58. this.phone = phone;
  59. }
  60. public String getRoleName() {
  61. return roleName;
  62. }
  63. <h1><a name="t8"></a>   public void setRoleName(String roleName) {</h1>     this.roleName = roleName;
  64. }
  65. }

五、配置spring配置文件、jdbc和日志属性文件、myBatis的mapper.xml文件

5.1  spring配置文件applicationContext.xml如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  9. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
  10. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
  11. <!-- 属性配置文件 -->
  12. <context:property-placeholder location="classpath:jdbc.properties"/>
  13. <!-- 组件扫描,指定spring管理哪些bean -->
  14. <context:component-scan base-package="com.liuhai.eshop.dao.impl,com.liuhai.eshop.service.impl"></context:component-scan>
  15. <!-- 注解驱动 -->
  16. <tx:annotation-driven/>
  17. <!-- 创建数据源 -->
  18. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  19. <property name="driverClass" value="${jdbc.driverclass}"></property>
  20. <property name="jdbcUrl" value="${jdbc.url}"></property>
  21. <property name="user" value="${jdbc.username}"></property>
  22. <property name="password" value="${jdbc.password}"></property>
  23. <property name="initialPoolSize" value="${c3p0.pool.size.init}"></property>
  24. <property name="minPoolSize" value="${c3p0.pool.size.min}"></property>
  25. <property name="maxPoolSize" value="${c3p0.pool.size.max}"></property>
  26. <property name="acquireIncrement" value="${c3p0.pool.size.increment}"></property>
  27. </bean>
  28. <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
  29. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  30. <property name="dataSource" ref="dataSource" />
  31. <!-- 自动扫描mapping.xml文件 -->
  32. <property name="mapperLocations" value="classpath:com/liuhai/eshop/mappers/*.xml"></property>
  33. </bean>
  34. <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
  35. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  36. <property name="basePackage" value="com.liuhai.eshop.dao"></property>
  37. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
  38. </bean>
  39. <!-- 事务管理器,service层面上实现事务管理的 -->
  40. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  41. <property name="dataSource" ref="dataSource"></property>
  42. </bean>
  43. </beans>

5.2 jdbc属性文件jdbc.properties如下:

  1. jdbc.driverclass=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc\:mysql\://localhost\:3306/eshop
  3. jdbc.username=root
  4. jdbc.password=123456
  5. c3p0.pool.size.max=10
  6. c3p0.pool.size.min=2
  7. c3p0.pool.size.init=3
  8. c3p0.pool.size.increment=2
  9. hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
  10. hibernate.show_sql=true
  11. hibernate.hbm2ddl.auto=none

5.3 日志属性文件log4j.properties如下:

  1. log4j.rootLogger=INFO,Console,File
  2. #定义日志输出目的地为控制台
  3. log4j.appender.Console=org.apache.log4j.ConsoleAppender
  4. log4j.appender.Console.Target=System.out
  5. #可以灵活地指定日志输出格式,下面一行是指定具体的格式
  6. log4j.appender.Console.layout = org.apache.log4j.PatternLayout
  7. log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
  8. log4j.logger.java.sql.ResultSet=INFO
  9. log4j.logger.org.apache=INFO
  10. log4j.logger.java.sql.Connection=DEBUG
  11. log4j.logger.java.sql.Statement=DEBUG
  12. log4j.logger.java.sql.PreparedStatement=DEBUG
  13. #文件大小到达指定尺寸的时候产生一个新的文件
  14. log4j.appender.File = org.apache.log4j.RollingFileAppender
  15. #指定输出目录
  16. log4j.appender.File.File = logs/ssm.log
  17. #定义文件最大大小
  18. log4j.appender.File.MaxFileSize = 10MB
  19. # 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
  20. log4j.appender.File.Threshold =INFO
  21. log4j.appender.File.layout = org.apache.log4j.PatternLayout
  22. log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

5.4 myBatis的mapper.xml文件(UserMapper.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. <mapper namespace="com.liuhai.eshop.dao.UserDao">
  6. <!-- 定义缓存  一般是一级缓存,如果用同一个sqlsession 那么相同查询直接会从缓存中查找 -->
  7. <cache size="1024" flushInterval="60000" eviction="LRU" readOnly="false"></cache>
  8. <!-- 增加 -->
  9. <insert id="add" parameterType="com.liuhai.eshop.domain.User">
  10. insert into users values(null,#{userName},#{password},#{age},#{trueName},#{email},#{phone},#{roleName})
  11. </insert>
  12. <resultMap id="userResultMap" type="com.liuhai.eshop.domain.User" >
  13. <id property="id" column="id"/>
  14. <result property="userName" column="userName"/>
  15. <result property="password" column="password"/>
  16. <result property="age" column="age"/>
  17. <result property="trueName" column="trueName" />
  18. <result property="email" column="email" />
  19. <result property="phone" column="phone" />
  20. <result property="roleName" column="roleName" />
  21. </resultMap>
  22. <select id="getUserById" parameterType="Integer" resultMap="userResultMap">
  23. select * from users where id=#{id}
  24. </select>
  25. <select id="find" parameterType="com.liuhai.eshop.domain.User" resultMap="userResultMap">
  26. select * from users
  27. <where>
  28. <if test="userName!=null and userName!='' ">
  29. and userName like #{userName}
  30. </if>
  31. </where>
  32. <if test="start!=null and size!=null">
  33. limit #{start},#{size}
  34. </if>
  35. </select>
  36. <select id="getTotal" parameterType="Map" resultType="Long">
  37. select count(*) from users
  38. <where>
  39. <if test="userName!=null and userName!='' ">
  40. and userName like #{userName}
  41. </if>
  42. </where>
  43. </select>
  44. <!-- 用户删除 -->
  45. <delete id="delete" parameterType="Integer">
  46. delete from users where id = #{id}
  47. </delete>
  48. <!-- 用户修改 -->
  49. <update id="update" parameterType="com.liuhai.eshop.domain.User">
  50. update users
  51. <set>
  52. <if test="age != null and age != ''">age = #{age},</if>
  53. <if test="userName != null and userName != ''">userName = #{userName},</if>
  54. <if test="password != null and password != ''">password = #{password},</if>
  55. <if test="trueName != null and trueName != ''">trueName = #{trueName},</if>
  56. <if test="email != null and email != ''">email = #{email},</if>
  57. <if test="phone != null and phone != ''">phone = #{phone},</if>
  58. <if test="roleName != null and roleName != ''">roleName = #{roleName},</if>
  59. </set>
  60. where id = #{id}
  61. </update>
  62. </mapper>

六、创建测试类,测试数据源是否通了

以上spring框架及spring+mybatis配置基本完成,再就是创建测试类测试数据源是否通

首先创建一个mysql库的,再建立users表,创建测试类TestSpring.java如下:

  1. package com.liuhai.eshop;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. import com.liuhai.eshop.domain.User;
  6. import com.liuhai.eshop.service.UserService;
  7. public class TestSpring {
  8. @Test
  9. public void TestUserService() throws Exception{
  10. @SuppressWarnings("resource")
  11. ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
  12. UserService us=(UserService) ac.getBean("userService");
  13. User user=new User();
  14. user.setAge(1);
  15. user.setUserName("zhangsan");
  16. user.setPassword("123456");
  17. user.setTrueName("张三");
  18. us.add(user);
  19. }
  20. }

最后查询users表中是否有新插入的数据。

七、整合SpringMVC

7.1、配置spring-mvc.xml

配置里面的注释也很详细,在此就不说了,主要是自动扫描控制器,视图模式,注解的启动这三个

  1. <span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  7. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  9. <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
  10. <context:component-scan base-package="com.liuhai.eshop.controller"></context:component-scan>
  11. <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
  12. <bean id="mappingJacksonHttpMessageConverter"
  13. class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
  14. <property name="supportedMediaTypes">
  15. <list>
  16. <value>text/html;charset=UTF-8</value>
  17. </list>
  18. </property>
  19. </bean>
  20. <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
  21. <!-- 详细介绍:http://www.ibm.com/developerworks/cn/web/wa-restful/ -->
  22. <bean
  23. class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  24. <property name="messageConverters">
  25. <list>
  26. <ref bean="mappingJacksonHttpMessageConverter" /> <!-- 对象转化为JSON转换器 -->
  27. </list>
  28. </property>
  29. </bean>
  30. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  31. <property name="prefix" value="/jsps/"></property>
  32. <property name="suffix" value=".jsp"></property>
  33. </bean>
  34. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  35. <!-- 默认编码 -->
  36. <property name="defaultEncoding" value="utf-8"></property>
  37. <!-- 文件大小最大值 -->
  38. <property name="maxUploadSize" value="10485760000"></property>
  39. <!-- 内存中的最大值 -->
  40. <property name="maxInMemorySize" value="40960"></property>
  41. </bean>
  42. </beans></span>

7.2、配置web.xml文件

这里面对applicationContext.xml的引入以及配置的spring-mvc的Servlet就是为了完成SSM整合,之前2框架整合不需要在此处进行任何配置。配置一样有详细注释,不多解释了。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  5. version="3.0">
  6. <display-name>web 测试页面</display-name>
  7. <!-- Spring和mybatis的配置文件 -->
  8. <context-param>
  9. <param-name>contextConfigLocation</param-name>
  10. <param-value>classpath:applicationContext.xml</param-value>
  11. </context-param>
  12. <!-- 编码过滤器 -->
  13. <filter>
  14. <filter-name>encodingFilter</filter-name>
  15. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  16. <async-supported>true</async-supported>
  17. <init-param>
  18. <param-name>encoding</param-name>
  19. <param-value>UTF-8</param-value>
  20. </init-param>
  21. </filter>
  22. <filter-mapping>
  23. <filter-name>encodingFilter</filter-name>
  24. <url-pattern>/*</url-pattern>
  25. </filter-mapping>
  26. <!-- Spring监听器:启动Web容器时,自动装配ApplicationContext的配置信息,即上面的:contextConfigLocation-->
  27. <listener>
  28. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  29. </listener>
  30. <!-- 防止Spring内存溢出监听器 -->
  31. <listener>
  32. <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  33. </listener>
  34. <!-- Spring MVC servlet -->
  35. <servlet>
  36. <servlet-name>springMVC</servlet-name>
  37. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  38. <init-param>
  39. <param-name>contextConfigLocation</param-name>
  40. <param-value>classpath:spring-mvc.xml</param-value>
  41. </init-param>
  42. <load-on-startup>1</load-on-startup>
  43. <async-supported>true</async-supported>
  44. </servlet>
  45. <servlet-mapping>
  46. <servlet-name>springMVC</servlet-name>
  47. <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 也可以是/-->
  48. <url-pattern>*.do</url-pattern>
  49. </servlet-mapping>
  50. <!-- 解决由于采用spring的过滤器,导致页面引用的JS、images、CSS发生找不到的错误;也可以用使用spring mvc 的 <mvc:resources /> 注解 用来处理静态文件 -->
  51. <servlet-mapping>
  52. <servlet-name>default</servlet-name>
  53. <url-pattern>*.css</url-pattern>
  54. </servlet-mapping>
  55. <servlet-mapping>
  56. <servlet-name>default</servlet-name>
  57. <url-pattern>*.gif</url-pattern>
  58. </servlet-mapping>
  59. <servlet-mapping>
  60. <servlet-name>default</servlet-name>
  61. <url-pattern>*.png</url-pattern>
  62. </servlet-mapping>
  63. <servlet-mapping>
  64. <servlet-name>default</servlet-name>
  65. <url-pattern>*.jpg</url-pattern>
  66. </servlet-mapping>
  67. <servlet-mapping>
  68. <servlet-name>default</servlet-name>
  69. <url-pattern>*.js</url-pattern>
  70. </servlet-mapping>
  71. <welcome-file-list>
  72. <welcome-file>/index.jsp</welcome-file>
  73. </welcome-file-list>
  74. </web-app>

7.3 新建控制类controller及jsp页面之间交互

在这里使用jsp页面引入easyui集成并实现增删改查功能

userManage.jsp如下:

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  2. <%
  3. String path = request.getContextPath();
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  5. %>
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  7. <html>
  8. <head>
  9. <base href="<%=basePath%>">
  10. <title>My JSP 'userManage.jsp' starting page</title>
  11. <meta http-equiv="pragma" content="no-cache">
  12. <meta http-equiv="cache-control" content="no-cache">
  13. <meta http-equiv="expires" content="0">
  14. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  15. <meta http-equiv="description" content="This is my page">
  16. <link rel="stylesheet" type="text/css" href="jquery-easyui-1.5.1/themes/default/easyui.css">
  17. <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/jquery-easyui-1.5.1/themes/icon.css">
  18. <script type="text/javascript" src="${pageContext.request.contextPath}/jquery-easyui-1.5.1/jquery.min.js"></script>
  19. <script type="text/javascript" src="${pageContext.request.contextPath}/jquery-easyui-1.5.1/jquery.easyui.min.js"></script>
  20. <script type="text/javascript" src="${pageContext.request.contextPath}/jquery-easyui-1.5.1/locale/easyui-lang-zh_CN.js"></script>
  21. <script type="text/javascript">
  22. var url;
  23. function openUserAddDialog() {
  24. $("#dlg").dialog("open").dialog("setTitle", "添加用户信息");
  25. url = "${pageContext.request.contextPath}/user/save.do";
  26. }
  27. function saveUser() {
  28. $("#fm").form("submit", {
  29. url : url,
  30. onSubmit : function() {
  31. if ($("#roleName").combobox("getValue") == "") {
  32. $.messager.alert("系统提示", "请选择用户角色!");
  33. return false;
  34. }
  35. return $(this).form("validate");
  36. },
  37. success : function(result) {
  38. var result = eval('(' + result + ')');
  39. if (result.success) {
  40. $.messager.alert("系统提示", "保存成功!");
  41. resetValue();
  42. $("#dlg").dialog("close");
  43. $("#dg").datagrid("reload");
  44. } else {
  45. $.messager.alert("系统提示", "保存失败!");
  46. return;
  47. }
  48. }
  49. });
  50. }
  51. function searchUser() {
  52. $("#dg").datagrid('load', {
  53. "userName" : $("#s_userName").val()
  54. });
  55. }
  56. function resetValue() {
  57. $("#userName").val("");
  58. $("#password").val("");
  59. $("#trueName").val("");
  60. $("#email").val("");
  61. $("#phone").val("");
  62. $("#roleName").combobox("setValue", "");
  63. }
  64. function deleteUser() {
  65. var selectedRows = $("#dg").datagrid("getSelections");
  66. if (selectedRows.length == 0) {
  67. $.messager.alert("系统提示", "请选择要删除的数据!");
  68. return;
  69. }
  70. var strIds = [];
  71. for ( var i = 0; i < selectedRows.length; i++) {
  72. strIds.push(selectedRows[i].id);
  73. }
  74. var ids = strIds.join(",");
  75. $.messager.confirm("系统提示", "您确定要删除这<font color=red>"
  76. + selectedRows.length + "</font>条数据吗?", function(r) {
  77. if (r) {
  78. $.post("${pageContext.request.contextPath}/user/delete.do", {
  79. ids : ids
  80. }, function(result) {
  81. if (result.success) {
  82. $.messager.alert("系统提示", "数据已成功删除!");
  83. $("#dg").datagrid("reload");
  84. } else {
  85. $.messager.alert("系统提示", "数据删除失败,请联系系统管理员!");
  86. }
  87. }, "json");
  88. }
  89. });
  90. }
  91. function openUserModifyDialog() {
  92. var selectedRows = $("#dg").datagrid("getSelections");
  93. if (selectedRows.length != 1) {
  94. $.messager.alert("系统提示", "请选择一条要编辑的数据!");
  95. return;
  96. }
  97. var row = selectedRows[0];
  98. $("#dlg").dialog("open").dialog("setTitle", "编辑用户信息");
  99. $("#fm").form("load", row);
  100. url = "${pageContext.request.contextPath}/user/save.do?id=" + row.id;
  101. }
  102. </script>
  103. </head>
  104. <body style="margin: 1px">
  105. <table id="dg" title="用户管理" class="easyui-datagrid" fitColumns="true"
  106. pagination="true" rownumbers="true"
  107. url="${pageContext.request.contextPath}/user/list.do" fit="true"
  108. toolbar="#tb">
  109. <thead>
  110. <tr>
  111. <th field="cb" checkbox="true" align="center"></th>
  112. <th field="id" width="50" align="center">编号</th>
  113. <th field="userName" width="50" align="center">用户名</th>
  114. <th field="password" width="50" align="center">密码</th>
  115. <th field="trueName" width="50" align="center">真实姓名</th>
  116. <th field="email" width="50" align="center">邮件</th>
  117. <th field="phone" width="50" align="center">联系电话</th>
  118. <th field="roleName" width="50" align="center">角色</th>
  119. </tr>
  120. </thead>
  121. </table>
  122. <div id="tb">
  123. <a href="javascript:openUserAddDialog()" class="easyui-linkbutton"
  124. iconCls="icon-add" plain="true">添加</a> <a
  125. href="javascript:openUserModifyDialog()" class="easyui-linkbutton"
  126. iconCls="icon-edit" plain="true">修改</a> <a
  127. href="javascript:deleteUser()" class="easyui-linkbutton"
  128. iconCls="icon-remove" plain="true">删除</a>
  129. <div>
  130. 用户名: <input type="text" id="s_userName" size="20"
  131. onkeydown="if(event.keyCode == 13)searchUser()" /> <a
  132. href="javascript:searchUser()" class="easyui-linkbutton"
  133. iconCls="icon-search" plain="true">查询</a>
  134. </div>
  135. <div id="dlg-buttons">
  136. <a href="javascript:saveUser()" class="easyui-linkbutton"
  137. iconCls="icon-ok">保存</a> <a href="javascript:closeUserDialog()"
  138. class="easyui-linkbutton" iconCls="icon-cancel">关闭</a>
  139. </div>
  140. <div id="dlg" class="easyui-dialog"
  141. style="width: 730px;height:280px;padding:10px 10px;" closed="true"
  142. buttons="#dlg-buttons">
  143. <form method="post" id="fm">
  144. <table cellspacing="8px;">
  145. <tr>
  146. <td>用户名:</td>
  147. <td><input type="text" id="userName" name="userName"
  148. class="easyui-validatebox" required="true" /> <span
  149. style="color: red">*</span>
  150. </td>
  151. <td>  </td>
  152. <td>密码:</td>
  153. <td><input type="password" id="password" name="password"
  154. class="easyui-validatebox" required="true" /> <span
  155. style="color: red">*</span>
  156. </td>
  157. </tr>
  158. <tr>
  159. <td>真实姓名:</td>
  160. <td><input type="text" id="trueName" name="trueName"
  161. class="easyui-validatebox" required="true" /> <span
  162. style="color: red">*</span>
  163. </td>
  164. <td>  </td>
  165. <td>邮箱:</td>
  166. <td><input type="text" id="email" name="email"
  167. validType="email" class="easyui-validatebox" required="true" /> <span
  168. style="color: red">*</span>
  169. </td>
  170. </tr>
  171. <tr>
  172. <td>联系电话:</td>
  173. <td><input type="text" id="phone" name="phone"
  174. class="easyui-validatebox" required="true" /> <span
  175. style="color: red">*</span>
  176. </td>
  177. <td>  </td>
  178. <td>用户角色:</td>
  179. <td><select name="roleName" class="easyui-combobox"
  180. id="roleName" style="width: 154px;" editable="false"
  181. panelHeight="auto">
  182. <option value="">请选择角色</option>
  183. <option value="系统管理员">系统管理员</option>
  184. <option value="销售主管">销售主管</option>
  185. <option value="客户经理">客户经理</option>
  186. <option value="高管">高管</option>
  187. </select>  <span style="color: red">*</span>
  188. </td>
  189. </tr>
  190. </table>
  191. </form>
  192. </div>
  193. </div>
  194. </body>
  195. </html>

UserController.java

  1. package com.liuhai.eshop.controller;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import java.util.Map;
  7. import javax.annotation.Resource;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import net.sf.json.JSONArray;
  11. import net.sf.json.JSONObject;
  12. import org.apache.commons.io.FileUtils;
  13. import org.slf4j.Logger;
  14. import org.slf4j.LoggerFactory;
  15. import org.springframework.http.HttpStatus;
  16. import org.springframework.http.ResponseEntity;
  17. import org.springframework.stereotype.Controller;
  18. import org.springframework.ui.Model;
  19. import org.springframework.web.bind.annotation.RequestMapping;
  20. import org.springframework.web.bind.annotation.RequestMethod;
  21. import org.springframework.web.bind.annotation.RequestParam;
  22. import org.springframework.web.bind.annotation.ResponseBody;
  23. import org.springframework.web.multipart.MultipartFile;
  24. import com.liuhai.eshop.domain.User;
  25. import com.liuhai.eshop.service.UserService;
  26. import com.liuhai.eshop.util.PageBean;
  27. import com.liuhai.eshop.util.ResponseUtil;
  28. import com.liuhai.eshop.util.StringUtil;
  29. @Controller
  30. @RequestMapping("/user")
  31. public class UserController {
  32. private static Logger log=LoggerFactory.getLogger(UserController.class);
  33. @Resource
  34. private UserService userService;
  35. @RequestMapping("/showUser.do")
  36. public String toIndex(HttpServletRequest request,Model model){
  37. System.out.println("liuhaitest");
  38. return "showUser";
  39. }
  40. // /user/test.do?id=1
  41. @RequestMapping(value="/test.do",method=RequestMethod.GET)
  42. public String test(HttpServletRequest request,Model model){
  43. int userId = Integer.parseInt(request.getParameter("id"));
  44. System.out.println("userId:"+userId);
  45. User user=null;
  46. if (userId==1) {
  47. user = new User();
  48. user.setAge(11);
  49. user.setId(1);
  50. user.setPassword("123");
  51. user.setUserName("javen");
  52. }
  53. log.debug(user.toString());
  54. model.addAttribute("user", user);
  55. return "index";
  56. }
  57. // /user/showUser.do?id=1
  58. @RequestMapping(value="/showUser.do",method=RequestMethod.GET)
  59. public String toindex(HttpServletRequest request,Model model){
  60. int userId = Integer.parseInt(request.getParameter("id"));
  61. System.out.println("userId:"+userId);
  62. User user = this.userService.getUserById(userId);
  63. log.debug(user.toString());
  64. model.addAttribute("user", user);
  65. return "showUser";
  66. }
  67. // /user/showUser2.do?id=1
  68. @RequestMapping(value="/showUser2.do",method=RequestMethod.GET)
  69. public String toIndex2(@RequestParam("id") String id,Model model){
  70. int userId = Integer.parseInt(id);
  71. System.out.println("userId:"+userId);
  72. User user = this.userService.getUserById(userId);
  73. log.debug(user.toString());
  74. model.addAttribute("user", user);
  75. return "showUser";
  76. }
  77. // /user/jsontype.do?id=1
  78. @RequestMapping(value="/jsontype.do",method=RequestMethod.GET)
  79. public @ResponseBody User getUserInJson(@RequestParam("id") String id,Map<String, Object> model){
  80. int userId = Integer.parseInt(id);
  81. System.out.println("userId:"+userId);
  82. User user = this.userService.getUserById(userId);
  83. log.info(user.toString());
  84. return user;
  85. }
  86. // /user/jsontype2.do?id=1
  87. @RequestMapping(value="/jsontype2.do",method=RequestMethod.GET)
  88. public ResponseEntity<User>  getUserInJson2(@RequestParam("id") String id,Map<String, Object> model){
  89. int userId = Integer.parseInt(id);
  90. System.out.println("userId:"+userId);
  91. User user = this.userService.getUserById(userId);
  92. log.info(user.toString());
  93. return new ResponseEntity<User>(user,HttpStatus.OK);
  94. }
  95. //文件上传页面
  96. @RequestMapping(value="/upload.do")
  97. public String showUploadPage(){
  98. return "file";
  99. }
  100. //文件上传
  101. @RequestMapping(value="/doUpload.do",method=RequestMethod.POST)
  102. public String doUploadFile(@RequestParam("file")MultipartFile file) throws IOException{
  103. if (!file.isEmpty()) {
  104. log.info("Process file:{}",file.getOriginalFilename());
  105. }
  106. FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:\\",System.currentTimeMillis()+file.getOriginalFilename()));
  107. return "succes";
  108. }
  109. /**
  110. * 用户管理页面
  111. * @return
  112. */
  113. @RequestMapping(value="/userManage.do")
  114. public String userManagePage(){
  115. return "userManage";
  116. }
  117. /**
  118. * 添加或者修改
  119. * @param user
  120. * @param res
  121. * @return
  122. * @throws Exception
  123. */
  124. @RequestMapping("/save.do")
  125. public String save(User user,HttpServletResponse res) throws Exception{
  126. //操作记录条数,初始化为0
  127. int resultTotal = 0;
  128. if (user.getId() == null) {
  129. resultTotal = userService.add(user);
  130. }else{
  131. resultTotal = userService.update(user);
  132. }
  133. JSONObject jsonObject = new JSONObject();
  134. if(resultTotal > 0){   //说明修改或添加成功
  135. jsonObject.put("success", true);
  136. }else{
  137. jsonObject.put("success", false);
  138. }
  139. ResponseUtil.write(res, jsonObject);
  140. return null;
  141. }
  142. /**
  143. * 用户分页查询
  144. * @param page
  145. * @param rows
  146. * @param s_user
  147. * @param res
  148. * @return
  149. * @throws Exception
  150. */
  151. @RequestMapping("/list.do")
  152. public String list(@RequestParam(value="page",required=false) String page,@RequestParam(value="rows",required=false) String rows,User s_user,HttpServletResponse res) throws Exception{
  153. PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
  154. Map<String,Object> map=new HashMap<String,Object>();
  155. map.put("userName", StringUtil.formatLike(s_user.getUserName()));
  156. map.put("start", pageBean.getStart());
  157. map.put("size", pageBean.getPageSize());
  158. List<User> userList=userService.find(map);
  159. Long total=userService.getTotal(map);
  160. JSONObject result=new JSONObject();
  161. JSONArray jsonArray=JSONArray.fromObject(userList);
  162. result.put("rows", jsonArray);
  163. result.put("total", total);
  164. ResponseUtil.write(res, result);
  165. return null;
  166. }
  167. /**
  168. * 删除用户
  169. * @param ids
  170. * @param res
  171. * @return
  172. * @throws Exception
  173. */
  174. @RequestMapping("/delete.do")
  175. public String delete(@RequestParam(value="ids") String ids,HttpServletResponse res) throws Exception{
  176. String[] idStr = ids.split(",");
  177. JSONObject jsonObject = new JSONObject();
  178. for (String id : idStr) {
  179. userService.delete(Integer.parseInt(id));
  180. }
  181. jsonObject.put("success", true);
  182. ResponseUtil.write(res, jsonObject);
  183. return null;
  184. }
  185. }

7.4其它工具类及jsp页面

分页Model类PageBean.java

  1. package com.liuhai.eshop.util;
  2. /**
  3. * 分页Model类
  4. * @author Administrator
  5. *
  6. */
  7. public class PageBean {
  8. private int page; // 第几页
  9. private int pageSize; // 每页记录数
  10. private int start;  // 起始页
  11. public PageBean(int page, int pageSize) {
  12. super();
  13. this.page = page;
  14. this.pageSize = pageSize;
  15. }
  16. public int getPage() {
  17. return page;
  18. }
  19. public void setPage(int page) {
  20. this.page = page;
  21. }
  22. public int getPageSize() {
  23. return pageSize;
  24. }
  25. public void setPageSize(int pageSize) {
  26. this.pageSize = pageSize;
  27. }
  28. public int getStart() {
  29. return (page-1)*pageSize;
  30. }
  31. }

用于返回json数据ResponseUtil.java

  1. package com.liuhai.eshop.util;
  2. import java.io.PrintWriter;
  3. import javax.servlet.http.HttpServletResponse;
  4. /***
  5. * 主要用于返回json数据
  6. * @author Administrator
  7. */
  8. public class ResponseUtil {
  9. public static void write(HttpServletResponse response,Object object)throws Exception{
  10. response.setContentType("text/html;charset=utf-8");
  11. PrintWriter out=response.getWriter();
  12. out.println(object);
  13. out.flush();
  14. out.close();
  15. }
  16. }

字符串工具类StringUtil.java如下:

  1. package com.liuhai.eshop.util;
  2. /***
  3. * 字符串工具类
  4. * @author Administrator
  5. *
  6. */
  7. public class StringUtil {
  8. /**
  9. * 判断是否是空
  10. * @param str
  11. * @return
  12. */
  13. public static boolean isEmpty(String str){
  14. if(str==null||"".equals(str.trim())){
  15. return true;
  16. }else{
  17. return false;
  18. }
  19. }
  20. /**
  21. * 判断是否不是空
  22. * @param str
  23. * @return
  24. */
  25. public static boolean isNotEmpty(String str){
  26. if((str!=null)&&!"".equals(str.trim())){
  27. return true;
  28. }else{
  29. return false;
  30. }
  31. }
  32. /**
  33. * 格式化模糊查询
  34. * @param str
  35. * @return
  36. */
  37. public static String formatLike(String str){
  38. if(isNotEmpty(str)){
  39. return "%"+str+"%";
  40. }else{
  41. return null;
  42. }
  43. }
  44. }

上传文件file.jsp页面

  1. <%@ page language="java" contentType="text/html; charset=utf-8"
  2. pageEncoding="utf-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10. <h1>上传文件</h1>
  11. <form method="post" action="../user/doUpload.do" enctype="multipart/form-data">
  12. <input type="file" name="file"/>
  13. <input type="submit" value="上传文件"/>
  14. </form>
  15. </body>
  16. </html>

八、项目结果及目录

SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现

SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现

上一篇:java验证身份证号码是否有效源代码 wn25的头像 wn25 23 2015-01-04 20:09 6 基本信息 Java × 1 浏览


下一篇:Spring MVC拦截器配置