[可用]SSM框架搭建(Spring+SpringMVC+MyBatis)+EasyUI 在IDEA 上实现增删改查实例

 

 

之前工作有用到SpringMVC,最近想整理个例子,用于归纳总结,及方便新手学习。查看了网上的不少例子,都是不完整或者用不了的,爬了不少坑,终于花两天时间调通了这个例子,并花了一晚上写完这篇文章。

关于spring相关概念及SSM框架,直接贴代码,理论的不多赘述了。项目代码结构请参照文章结尾。

一、软件准备:

1.1 idea下载地址(IntelliJ IDEA 2018.1.6 x64专业版):https://www.jetbrains.com/idea/download/#section=windows

1.2 easyUI下载地址(jquery-easyui-1.5.5.4):http://www.jeasyui.com/download/v154.php

二、IDEA 开发环境搭建部署及建立 maven web项目

参考文章:https://blog.csdn.net/zwjzqqb/article/details/79040383

注意:1.创建maven web项目  没有src webapp文件夹  原因:maven仓库调用外网

建议使用maven私服库: maven安装地址 下更改setting.xml 

	<!-- 阿里云仓库 -->
	<mirrors>
         <mirror>
            <id>alimaven</id>
            <mirrorOf>central</mirrorOf>
             <name>aliyun maven</name>
             <url>http://maven.aliyun.com/nexus/content/repositories/central/</url>
         </mirror>
 
 
         <!-- 中央仓库 -->
         <mirror>
             <id>repo</id>
             <mirrorOf>central</mirrorOf>
             <name>Human Readable Name for this Mirror.</name>
             <url>http://repo1.maven.org/maven2/</url>
         </mirror>
	</mirrors>

创建maven web项目成功。

项目结构如下:

在src/main下新增java  resources文件夹  分别设置为 sources  resources

新增src/test/java 设置为tests

项目结构修改如下:

 

三、SSM框架整合

Spring 4.0.2 RELEASE

Spring MVC 4.0.2 RELEASE

MyBatis 3.2.6

3.1、Maven引入需要的JAR包

pom.xml文件 

<?xml version="1.0" encoding="UTF-8"?>

<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">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.zhq</groupId>
  <artifactId>mavenDemo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>mavenDemo Maven Webapp</name>

  <properties>
    <!-- spring版本号 -->
    <spring.version>4.0.2.RELEASE</spring.version>
    <!-- mybatis版本号 -->
    <mybatis.version>3.2.6</mybatis.version>
    <!-- log4j日志文件管理包版本 -->
    <slf4j.version>1.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <!-- 表示开发的时候引入,发布的时候不会加载此包 -->
      <scope>test</scope>
    </dependency>
    <!-- spring核心包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- mybatis核心包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!-- mybatis/spring包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!-- 导入java ee jar 包 -->
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
    </dependency>
    <!-- 导入Mysql数据库链接jar包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>
    <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!-- JSTL标签类 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- 日志文件管理包 -->
    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>

    <!-- 格式化对象,方便输出日志 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.1.41</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <!-- log end -->
    <!-- 映入JSON -->
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.13</version>
    </dependency>
    <!-- 上传组件包 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.9</version>
    </dependency>
  </dependencies>


  <build>
    <finalName>mavenDemo</finalName>
    <!--  强制将xml文件打到war包中 s-->
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <!-- 编码和编译和JDK版本 -->
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.3.2</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <encoding>utf8</encoding>
          </configuration>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

注意:使得mapping下的UserDao.xml起作用:

    <!--  强制将xml文件打到war包中 s-->
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>

 

3.2、Spring与MyBatis的整合

3.2.1、建立JDBC属性文件

mysql数据库连接:   数据库名:zhq    ?后面的 防止中文乱码  

jdbc.properties (文件编码修改为 utf-8 )

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/zhq?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true
username=root
password=
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000

3.2.2、建立spring-mybatis.xml配置文件

之前dao所在包名错误  导致一直报错

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.1.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- 自动扫描 -->
    <context:component-scan base-package="com.zhq" />
    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath*:com/zhq/mapping/*.xml"></property>
    </bean>

    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zhq.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

3.2.3、Log4j的配置

log4j.rootLogger=debug,stdout,logfile及后面4行  使得输出执行的sql语句  很有用

log4j.rootLogger=debug,stdout,logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=E:/Work/WorkSpaces/MyEclipse 10/mavenDemo/logs/ssm.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n


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

3.2.4、JUnit测试

3.2.4.1、创建测试表 数据

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(32) DEFAULT NULL,
  `password` varchar(64) DEFAULT NULL,
  `age` int(4) DEFAULT NULL,
  `true_name` varchar(32) DEFAULT NULL,
  `email` varchar(64) DEFAULT NULL,
  `phone` varchar(64) DEFAULT NULL,
  `role_name` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('1', '测试', 'sfasgfaf', '24', 'ffff', 'aaa', '18855633', '2');
INSERT INTO `users` VALUES ('2', 'zhq', 'zhq', '27', 'ffggg', 'gga', '2365', 'fsdfsd');
INSERT INTO `users` VALUES ('3', 'hello', 'hello', '22', 'fsdfsd', 'fdf', '222', 'sdfsdf');
INSERT INTO `users` VALUES ('5', '测试1', '123', '23', '庄', '505888888@qq.com', '1884553', 'sales executive');

3.2.4.2、利用MyBatis Generator自动创建代码

参考文章:http://blog.csdn.net/zhshulin/article/details/23912615

生成:UserDao.java   UserDao.xml   User.java   

userDao.xml生成后需要自己修改  namespace  parameterType

UserDao.java

package com.zhq.dao;

import com.zhq.pojo.User;

import java.util.List;
import java.util.Map;

/**
 * 用户DAO接口
 * @author Administrator
 *
 */
public interface UserDao {
    /**
     * 删除用户
     * @param id
     * @return
     */
    public int delete(int id);
    /**
     * 更新用户
     * @param user
     * @return
     */
    public int update(User user);
    /**
     * 添加用户
     * @param user
     * @return
     */
    public int add(User user);
    /**
     * 用户查询
     * @param map
     * @return
     */
    public List<User> find(Map<String,Object> map);
    /**
     * 获取总记录数
     * @param map
     * @return
     */
    public Long getTotal(Map<String,Object> map);
    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    public User getUserById(int id);
}

UserDao.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">
<mapper namespace="com.zhq.dao.UserDao">
  <!-- 定义缓存  一般是一级缓存,如果用同一个sqlsession 那么相同查询直接会从缓存中查找 -->
  <cache size="1024" flushInterval="60000" eviction="LRU" readOnly="false"></cache>
  <!-- 增加 -->
  <insert id="add" parameterType="com.zhq.pojo.User">
    insert into users values(null,#{userName},#{password},#{age},#{trueName},#{email},#{phone},#{roleName})
  </insert>
  <resultMap id="userResultMap" type="com.zhq.pojo.User" >
    <id property="id" column="id"/>
    <result property="userName" column="user_name"/>
    <result property="password" column="password"/>
    <result property="age" column="age"/>
    <result property="trueName" column="true_name" />
    <result property="email" column="email" />
    <result property="phone" column="phone" />
    <result property="roleName" column="role_name" />
  </resultMap>
  <select id="getUserById" parameterType="integer" resultMap="userResultMap">
    select * from users where id=#{id}
  </select>
  <select id="find" parameterType="map" resultMap="userResultMap">
    select * from users
    <where>
      <if test="userName!=null and userName!='' ">
        user_name like #{userName}
      </if>
    </where>
    <if test="start!=null and size!=null">
      limit #{start},#{size}
    </if>
  </select>
  <select id="getTotal" parameterType="map" resultType="long">
    select count(*) from users
    <where>
      <if test="userName!=null and userName!='' ">
        user_name like #{userName}
      </if>
    </where>
  </select>
  <!-- 用户删除 -->
  <delete id="delete" parameterType="integer">
    delete from users where id = #{id}
  </delete>
  <!-- 用户修改 -->
  <update id="update" parameterType="com.zhq.pojo.User">
    update users
    <set>
      <if test="age != null and age != ''">age = #{age},</if>
      <if test="userName != null and userName != ''">user_name = #{userName},</if>
      <if test="password != null and password != ''">password = #{password},</if>
      <if test="trueName != null and trueName != ''">true_name = #{trueName},</if>
      <if test="email != null and email != ''">email = #{email},</if>
      <if test="phone != null and phone != ''">phone = #{phone},</if>
      <if test="roleName != null and roleName != ''">role_name = #{roleName},</if>
    </set>
    where id = #{id}
  </update>
</mapper>

User.java

package com.zhq.pojo;

import java.io.Serializable;

/**
 * 用户实体
 * @author Administrator
 *
 */
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String userName;
    private String password;
    private Integer age;
    private String trueName;
    private String email;
    private String phone;
    private String roleName;

    public Integer getId() {
        return id;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getTrueName() {
        return trueName;
    }

    public void setTrueName(String trueName) {
        this.trueName = trueName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }
}

3.2.4.3、建立Service接口和实现类

UserService.java

package com.zhq.service;

import com.zhq.pojo.User;

import java.util.List;
import java.util.Map;

public interface UserService {
    public int delete(int id);
    public int update(User user);
    public int add(User user);
    public List<User> find(Map<String,Object> map);
    public Long getTotal(Map<String,Object> map);
    public User getUserById(int id);
}

 UserServiceImpl.java

package com.zhq.service.impl;

import com.zhq.dao.UserDao;
import com.zhq.pojo.User;
import com.zhq.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service(value="com.zhq.userService.impl")
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public int delete(int id) {
        return userDao.delete(id);
    }

    @Override
    public int update(User user) {
        return userDao.update(user);
    }

    @Override
    public int add(User user) {
        return userDao.add(user);
    }

    @Override
    public List<User> find(Map<String, Object> map) {
        return userDao.find(map);
    }

    @Override
    public Long getTotal(Map<String, Object> map) {
        return userDao.getTotal(map);
    }
    public User getUserById(int id){
        return userDao.getUserById(id);
    }
}

3.2.4.4、建立测试类

import com.alibaba.fastjson.JSON;
import com.zhq.pojo.User;
import com.zhq.service.UserService;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

/**
 * Created by zhqPc on 2018/7/19.
 */
@RunWith(SpringJUnit4ClassRunner.class)		//表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
public class TestMyBatis {
    private static Logger logger = Logger.getLogger(TestMyBatis.class);
    //	private ApplicationContext ac = null;
    @Resource
    private UserService userService;

//	@Before
//	public void before() {
//		ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//		userService = (UserService) ac.getBean("userService");
//	}

    @Test
    public void test1() {
        User user = userService.getUserById(1);
        // System.out.println(user.getUserName());
        // logger.info("值:"+user.getUserName());
        logger.info(JSON.toJSONString(user));
    }
}

测试结果:

 

3.3、整合SpringMVC 

         上面已经完成了2大框架的整合,SpringMVC的配置文件单独放,然后在web.xml中配置整合。

3.3.1、配置spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.1.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
    <context:component-scan base-package="com.zhq.controller" />
<!--    <context:component-scan base-package="com.zhq.service"/>
    <context:component-scan base-package="com.zhq.dao"/>-->

    <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
    <bean id="mappingJacksonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
    <bean
            class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" />	<!-- JSON转换器 -->
            </list>
        </property>
    </bean>

    <!-- 定义跳转的文件的前后缀 ,视图模式配置-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
        <property name="prefix" value="/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 默认编码 -->
        <property name="defaultEncoding" value="utf-8" />
        <!-- 文件大小最大值 -->
        <property name="maxUploadSize" value="10485760000" />
        <!-- 内存中的最大值 -->
        <property name="maxInMemorySize" value="40960" />
    </bean>

</beans>

3.3.2、配置web.xml文件

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <display-name>Archetype Created Web Application</display-name>
    <!-- Spring和mybatis的配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mybatis.xml</param-value>
    </context-param>

    <!-- 编码过滤器 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>*.do</url-pattern>
    </filter-mapping>

    <!-- Spring监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 防止Spring内存溢出监听器 -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>


    <!-- Spring MVC servlet -->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

*.do  用于控制器调用

3.3.3、测试

        至此已经完成了SSM三大框架的整合了,接下来测试一下。

3.3.3.1、新建jsp页面

上传文件file.jsp页面

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

</form>
</body>
</html>

userManage.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <base href="<%=basePath%>">

  <title>SSM集成easyUI实现增删改查</title>

  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
  <link rel="stylesheet" type="text/css" href="/jquery-easyui-1.5.5.4/themes/default/easyui.css">
  <link rel="stylesheet" type="text/css" href="/jquery-easyui-1.5.5.4/themes/icon.css">
  <script type="text/javascript" src="/jquery-easyui-1.5.5.4/jquery.min.js"></script>
  <script type="text/javascript" src="/jquery-easyui-1.5.5.4/jquery.easyui.min.js"></script>
  <script type="text/javascript" src="/jquery-easyui-1.5.5.4/locale/easyui-lang-zh_CN.js"></script>
  <script type="text/javascript">
    var url;
    function openUserAddDialog() {
      $("#dlg").dialog("open").dialog("setTitle", "添加用户信息");
      url = "${pageContext.request.contextPath}/user/save.do";
    }
    function saveUser() {
      $("#fm").form("submit", {
        url : url,
        onSubmit : function() {
          if ($("#roleName").combobox("getValue") == "") {
            $.messager.alert("系统提示", "请选择用户角色!");
            return false;
          }
          return $(this).form("validate");
        },
        success : function(result) {
          var result = eval('(' + result + ')');
          if (result.success) {
            $.messager.alert("系统提示", "保存成功!");
            resetValue();
            $("#dlg").dialog("close");
            $("#dg").datagrid("reload");
          } else {
            $.messager.alert("系统提示", "保存失败!");
            return;
          }
        }
      });
    }
    function searchUser() {
      $("#dg").datagrid('load', {
        "userName" : $("#s_userName").val(),
        "page":"0",
        "rows":"10"
      });
    }
    function resetValue() {
      $("#userName").val("");
      $("#password").val("");
      $("#trueName").val("");
      $("#email").val("");
      $("#phone").val("");
      $("#roleName").combobox("setValue", "");
    }
    function deleteUser() {
      var selectedRows = $("#dg").datagrid("getSelections");
      if (selectedRows.length == 0) {
        $.messager.alert("系统提示", "请选择要删除的数据!");
        return;
      }
      var strIds = [];
      for ( var i = 0; i < selectedRows.length; i++) {
        strIds.push(selectedRows[i].id);
      }
      var ids = strIds.join(",");
      $.messager.confirm("系统提示", "您确定要删除这<font color=red>"
      + selectedRows.length + "</font>条数据吗?", function(r) {
        if (r) {
          $.post("${pageContext.request.contextPath}/user/delete.do", {
            ids : ids
          }, function(result) {
            if (result.success) {
              $.messager.alert("系统提示", "数据已成功删除!");
              $("#dg").datagrid("reload");
            } else {
              $.messager.alert("系统提示", "数据删除失败,请联系系统管理员!");
            }
          }, "json");
        }
      });
    }
    function openUserModifyDialog() {
      var selectedRows = $("#dg").datagrid("getSelections");
      if (selectedRows.length != 1) {
        $.messager.alert("系统提示", "请选择一条要编辑的数据!");
        return;
      }
      var row = selectedRows[0];
      $("#dlg").dialog("open").dialog("setTitle", "编辑用户信息");
      $("#fm").form("load", row);
      url = "${pageContext.request.contextPath}/user/save.do?id=" + row.id;
    }
    function closeUserDialog() {
        $('#dlg').dialog("close");
    }
  </script>
</head>

<body style="margin: 1px">
<table id="dg" title="用户管理" class="easyui-datagrid" fitColumns="true"
       pagination="true" rownumbers="true"
       url="/user/list.do" fit="true"
       toolbar="#tb">
  <thead>
  <tr>
    <th field="cb" checkbox="true" align="center"></th>
    <th field="id" width="50" align="center">编号</th>
    <th field="userName" width="50" align="center">用户名</th>
    <th field="password" width="50" align="center">密码</th>
    <th field="trueName" width="50" align="center">真实姓名</th>
    <th field="email" width="50" align="center">邮件</th>
    <th field="phone" width="50" align="center">联系电话</th>
    <th field="roleName" width="50" align="center">角色</th>
  </tr>
  </thead>
</table>
<div id="tb">
  <a href="javascript:openUserAddDialog()" class="easyui-linkbutton"
     iconCls="icon-add" plain="true">添加</a> <a
        href="javascript:openUserModifyDialog()" class="easyui-linkbutton"
        iconCls="icon-edit" plain="true">修改</a> <a
        href="javascript:deleteUser()" class="easyui-linkbutton"
        iconCls="icon-remove" plain="true">删除</a>
  <div>
    用户名: <input type="text" id="s_userName" size="20"
                onkeydown="if(event.keyCode == 13)searchUser()" /> <a
          href="javascript:searchUser()" class="easyui-linkbutton"
          iconCls="icon-search" plain="true">查询</a>
  </div>
  <div id="dlg-buttons">
    <a href="javascript:saveUser()" class="easyui-linkbutton"
       iconCls="icon-ok">保存</a> <a href="javascript:closeUserDialog()" 
                                   class="easyui-linkbutton" iconCls="icon-cancel">关闭</a>
  </div>
  <div id="dlg" class="easyui-dialog"
       style="width: 730px;height:280px;padding:10px 10px;" closed="true"
       buttons="#dlg-buttons">
    <form method="post" id="fm">
      <table cellspacing="8px;">
        <tr>
          <td>用户名:</td>
          <td><input type="text" id="userName" name="userName"
                     class="easyui-validatebox" required="true" /> <span
                  style="color: red">*</span>
          </td>
          <td>	</td>
          <td>密码:</td>
          <td><input type="password" id="password" name="password"
                     class="easyui-validatebox" required="true" /> <span
                  style="color: red">*</span>
          </td>
        </tr>
        <tr>
          <td>真实姓名:</td>
          <td><input type="text" id="trueName" name="trueName"
                     class="easyui-validatebox" required="true" /> <span
                  style="color: red">*</span>
          </td>
          <td>	</td>
          <td>邮箱:</td>
          <td><input type="text" id="email" name="email"
                     validType="email" class="easyui-validatebox" />
          </td>
        </tr>
        <tr>
          <td>联系电话:</td>
          <td><input type="text" id="phone" name="phone"
                     class="easyui-validatebox" required="true" /> <span
                  style="color: red">*</span>
          </td>
          <td>	</td>
          <td>年龄:</td>
          <td><input type="text" id="age" name="age"
                     class="easyui-validatebox"  />
          </td>

        </tr>
        <tr>
          <td>用户角色:</td>
          <td><select name="roleName" class="easyui-combobox"
                      id="roleName" style="width: 154px;" editable="false"
                      panelHeight="auto">
            <option value="">请选择角色</option>
            <option value="admin">系统管理员</option>
            <option value="sales executive">销售主管</option>
            <option value="customer manager">客户经理</option>
            <option value="senior executive">高管</option>
          </select>  <span style="color: red">*</span>
          </td>
        </tr>
      </table>
    </form>
  </div>
</div>
</body>
</html>

 下列代码用于引用easyUI:

<link rel="stylesheet" type="text/css" href="/jquery-easyui-1.5.5.4/themes/default/easyui.css">
  <link rel="stylesheet" type="text/css" href="/jquery-easyui-1.5.5.4/themes/icon.css">
  <script type="text/javascript" src="/jquery-easyui-1.5.5.4/jquery.min.js"></script>
  <script type="text/javascript" src="/jquery-easyui-1.5.5.4/jquery.easyui.min.js"></script>
  <script type="text/javascript" src="/jquery-easyui-1.5.5.4/locale/easyui-lang-zh_CN.js"></script>

easyUI存在webapp下的 jquery-easyui-1.5.5.4文件夹

3.3.3.2、建立UserController类

UserController.java  控制器:增删改查的入口

package com.zhq.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhq.pojo.User;
import com.zhq.service.UserService;
import com.zhq.util.PageBean;
import com.zhq.util.ResponseUtil;
import com.zhq.util.StringUtil;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    private static Logger log= Logger.getLogger(UserController.class);
    @Resource
    private UserService userService;

    @RequestMapping("/showUser.do")
    public String toIndex(HttpServletRequest request,Model model){
        System.out.println("liuhaitest");
        return "showUser";
    }
    // /user/test.do?id=1
    @RequestMapping(value="/test.do",method=RequestMethod.GET)
    public String test(HttpServletRequest request,Model model){
        int userId = Integer.parseInt(request.getParameter("id"));
        System.out.println("userId:"+userId);
        User user=null;
        if (userId==1) {
            user = new User();
            user.setAge(11);
            user.setId(1);
            user.setPassword("123");
            user.setUserName("javen");
        }
        log.debug(user.toString());
        model.addAttribute("user", user);
        return "index";
    }
    // /user/showUser.do?id=1
    @RequestMapping(value="/showUser.do",method=RequestMethod.GET)
    public String toindex(HttpServletRequest request,Model model){
        int userId = Integer.parseInt(request.getParameter("id"));
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);
        log.debug(user.toString());
        model.addAttribute("user", user);
        return "showUser";
    }

    // /user/showUser2.do?id=1
    @RequestMapping(value="/showUser2.do",method=RequestMethod.GET)
    public String toIndex2(@RequestParam("id") String id,Model model){
        int userId = Integer.parseInt(id);
        System.out.println("userId:" + userId);
        User user = this.userService.getUserById(userId);
        log.debug(user.toString());
        model.addAttribute("user", user);
        return "showUser";
    }

    // /user/jsontype.do?id=1
    @RequestMapping(value="/jsontype.do",method=RequestMethod.GET)
    public @ResponseBody User getUserInJson(@RequestParam("id") String id,Map<String, Object> model){
        int userId = Integer.parseInt(id);
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);
        log.info(user.toString());
        return user;
    }
    // /user/jsontype2.do?id=1
    @RequestMapping(value="/jsontype2.do",method=RequestMethod.GET)
    public ResponseEntity<User>  getUserInJson2(@RequestParam("id") String id,Map<String, Object> model){
        int userId = Integer.parseInt(id);
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);
        log.info(user.toString());
        return new ResponseEntity<User>(user,HttpStatus.OK);
    }

    //文件上传页面
    @RequestMapping(value="/upload.do")
    public String showUploadPage(){
        return "file";
    }
    //文件上传
    @RequestMapping(value="/doUpload.do",method=RequestMethod.POST)
    public String doUploadFile(@RequestParam("file")MultipartFile file) throws IOException{
        if (!file.isEmpty()) {
            //log.info("Process file:{}",file.getOriginalFilename());
        }
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:\\",System.currentTimeMillis()+file.getOriginalFilename()));
        return "succes";
    }
    /**
     * 用户管理页面
     * @return
     */
    @RequestMapping(value="/userManage.do")
    public String userManagePage(){
        return "userManage";
    }
    /**
     * 添加或者修改
     * @param user
     * @param res
     * @return
     * @throws Exception
     */
    @RequestMapping("/save.do")
    public String save(User user,HttpServletResponse res) throws Exception{
        //操作记录条数,初始化为0
        int resultTotal = 0;
        if (user.getId() == null) {
            resultTotal = userService.add(user);
        }else{
            resultTotal = userService.update(user);
        }
        JSONObject jsonObject = new JSONObject();
        if(resultTotal > 0){   //说明修改或添加成功
            jsonObject.put("success", true);
        }else{
            jsonObject.put("success", false);
        }
        ResponseUtil.write(res, jsonObject);
        return null;
    }
    /**
     * 用户分页查询
     * @param page
     * @param rows
     * @param s_user
     * @param res
     * @return
     * @throws Exception
     */
    @RequestMapping("/list.do")
    public String list(@RequestParam(value="page",required=false) String page,@RequestParam(value="rows",required=false) String rows,User s_user,HttpServletResponse res) throws Exception{
        PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("userName", StringUtil.formatLike(s_user.getUserName()));
        map.put("start", pageBean.getStart());
        map.put("size", pageBean.getPageSize());
        List<User> userList=userService.find(map);
        String jsonString=JSON.toJSONString(userList);
        JSONArray jsonArray=JSONArray.parseArray(jsonString);

        Long total=userService.getTotal(map);
        JSONObject result=new JSONObject();
        result.put("rows", jsonArray);
        result.put("total", total);
        ResponseUtil.write(res, result);
        return null;
    }
    /**
     * 删除用户
     * @param ids
     * @param res
     * @return
     * @throws Exception
     */
    @RequestMapping("/delete.do")
    public String delete(@RequestParam(value="ids") String ids,HttpServletResponse res) throws Exception{
        String[] idStr = ids.split(",");
        JSONObject jsonObject = new JSONObject();
        for (String id : idStr) {
            userService.delete(Integer.parseInt(id));
        }
        jsonObject.put("success", true);
        ResponseUtil.write(res, jsonObject);
        return null;
    }
}

3.3.3.3、其它工具类

 分页Model类PageBean.java

package com.zhq.util;
/**
 * 分页Model类
 * @author Administrator
 *
 */
public class PageBean {
    private int page; // 第几页
    private int pageSize; // 每页记录数
    private int start;  // 起始页
    public PageBean(int page, int pageSize) {
        super();
        this.page = page;
        this.pageSize = pageSize;
    }
    public int getPage() {
        return page;
    }
    public void setPage(int page) {
        this.page = page;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
    public int getStart() {
        return (page-1)*pageSize;
    }
}

用于返回json数据ResponseUtil.java

package com.zhq.util;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/***
 * 主要用于返回json数据
 * @author Administrator
 */
public class ResponseUtil {
    public static void write(HttpServletResponse response,Object object)throws Exception{
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        out.println(object);
        out.flush();
        out.close();
    }
}

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

package com.zhq.util;

/***
 * 字符串工具类
 * @author Administrator
 *
 */
public class StringUtil {
    /**
     * 判断是否是空
     * @param str
     * @return
     */
    public static boolean isEmpty(String str){
        if(str==null||"".equals(str.trim())){
            return true;W
        }else{
            return false;
        }
    }

    /**
     * 判断是否不是空
     * @param str
     * @return
     */
    public static boolean isNotEmpty(String str){
        if((str!=null)&&!"".equals(str.trim())){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 格式化模糊查询
     * @param str
     * @return
     */
    public static String formatLike(String str){
        if(isNotEmpty(str)){
            return "%"+str+"%";
        }else{
            return "";
        }
    }

    /**
     * 获取非空值
     * @param str
     * @return
     */
    public static String getValue(String str){
        if (isEmpty(str)){
            return "";
        }else{
            return str;
        }
    }
}

 

四、项目部署发布:

4.1项目目录

4.2将项目部署到tomcat上

输入地址:http://localhost:8080/user/userManage.do

 

源码下载地址:https://download.csdn.net/download/zhq505824802/10556369

转载请注明出处:https://blog.csdn.net/zhq505824802/article/details/81148859

  • 9
    点赞
  • 1
    评论
  • 17
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

打赏
文章很值,打赏犒劳作者一下
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页

打赏

田心王大可

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者