ssm整合开发项目实践(上)

引言

ssm(Spring+Springmvc+Mybatis)整合开发在java开发中是目前比较火的框架整合开发,在此用这三个框架整合开发了一个小项目,本项目已开源,源码已经发布到github仓库,大家可以结合源代码阅读本文,由于个人水平有限,如果有错误的地方,还请指出,大家相互学习,一起进步。

通过本项目我能学习到什么

  • ssm整合环境搭建与使用
  • 分页的实现
  • 前端框架Bootstrap的使用
  • 数据校验
  • ajax和Jquery的使用
  • MyBatis的逆向工程MyBatis Generator使用

项目实现的功能

实现对数据库中的用户管理,如新增、删除、批量删除、修改、查询等

开发环境

  • InteliJ IDEA 2019.2.4
  • JDK 1.8
  • Maven 3.6.3
  • Tomcat 9.0.22

基础环境搭建

1. 创建数据库与数据表

//创建数据库users
CREATE DATABASE users;
//切换至users数据库
USE users;
//创建用户类型表
CREATE TABLE `tbl_utype` (
  `utype_id` int(11) NOT NULL AUTO_INCREMENT,
  `utype_name` varchar(255)  NOT NULL,
  PRIMARY KEY (`utype_id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;
//创建用户表
CREATE TABLE `tbl_user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255)  NOT NULL,
  `gender` char(1) ,
  `email` varchar(255) ,
  `ut_id` int(11) ,
  PRIMARY KEY (`user_id`),
  KEY `ut_id` (`ut_id`),
  CONSTRAINT `tbl_user_ibfk_1` FOREIGN KEY (`ut_id`) REFERENCES `tbl_utype` (`utype_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

2. 创建项目搭建环境

  • 创建项目
    打开idea新建maven工程的mave-archetype-webapp模板,项目名为UserManagement。
  • 在pom.xml的properties标签内引入以下依赖版本控制
<spring.version>5.2.1.RELEASEspring.version>
   <aspectj.version>1.9.2aspectj.version>
   <slf4j.version>1.6.6slf4j.version>
   <log4j.version>1.2.17log4j.version>
   <mysql.version>5.1.6mysql.version>
   <mybatis.version>3.4.5mybatis.version>
   <aspectj.version>1.6.8aspectj.version>
   <junit.version>4.12junit.version>
  • 在pom.xml的dependencies标签内引入项目所有依赖jar包
 
   <dependency>
     <groupId>org.hibernate.validatorgroupId>
     <artifactId>hibernate-validatorartifactId>
     <version>6.1.0.Finalversion>
   dependency>
   
   <dependency>
     <groupId>com.fasterxml.jackson.coregroupId>
     <artifactId>jackson-databindartifactId>
     <version>2.10.0version>
   dependency>
   
   <dependency>
     <groupId>com.github.pagehelpergroupId>
     <artifactId>pagehelperartifactId>
     <version>5.1.10version>
   dependency>
   
   <dependency>
     <groupId>org.mybatis.generatorgroupId>
     <artifactId>mybatis-generator-coreartifactId>
     <version>1.3.0version>
   dependency>
   <dependency>
     
     
     <groupId>org.springframeworkgroupId>
     <artifactId>spring-contextartifactId>
     <version>${spring.version}version>
   dependency>

   
   <dependency>
     <groupId>org.springframeworkgroupId>
     <artifactId>spring-aopartifactId>
     <version>${spring.version}version>
   dependency>
   <dependency>
     <groupId>org.aspectjgroupId>
     <artifactId>aspectjweaverartifactId>
     <version>${aspectj.version}version>
   dependency>

   
   <dependency>
     <groupId>org.springframeworkgroupId>
     <artifactId>spring-webartifactId>
     <version>${spring.version}version>
   dependency>
   <dependency>
     <groupId>org.springframeworkgroupId>
     <artifactId>spring-webmvcartifactId>
     <version>${spring.version}version>
   dependency>

   
   <dependency>
     <groupId>org.springframeworkgroupId>
     <artifactId>spring-testartifactId>
     <version>${spring.version}version>
   dependency>

   
   <dependency>
     <groupId>org.springframeworkgroupId>
     <artifactId>spring-jdbcartifactId>
     <version>${spring.version}version>
   dependency>

   
   <dependency>
     <groupId>org.springframeworkgroupId>
     <artifactId>spring-txartifactId>
     <version>${spring.version}version>
   dependency>
   

   
   <dependency>
     <groupId>javax.servletgroupId>
     <artifactId>servlet-apiartifactId>
     <version>2.5version>
     <scope>providedscope>
   dependency>

   
   <dependency>
     <groupId>javax.servlet.jspgroupId>
     <artifactId>jsp-apiartifactId>
     <version>2.0version>
     <scope>providedscope>
   dependency>

   
   <dependency>
     <groupId>jstlgroupId>
     <artifactId>jstlartifactId>
     <version>1.2version>
   dependency>

   
   <dependency>
     <groupId>org.mybatisgroupId>
     <artifactId>mybatisartifactId>
     <version>${mybatis.version}version>
   dependency>

   
   <dependency>
     <groupId>org.mybatisgroupId>
     <artifactId>mybatis-springartifactId>
     <version>1.3.0version>
   dependency>

   
   <dependency>
     <groupId>mysqlgroupId>
     <artifactId>mysql-connector-javaartifactId>
     <version>${mysql.version}version>
   dependency>

   
   <dependency>
     <groupId>c3p0groupId>
     <artifactId>c3p0artifactId>
     <version>0.9.1.2version>
     <type>jartype>
     <scope>compilescope>
   dependency>

   
   <dependency>
     <groupId>junitgroupId>
     <artifactId>junitartifactId>
     <version>${junit.version}version>
     <scope>compilescope>
   dependency>

3. MyBatis的逆向工程MyBatis Generator使用

  • 使用mybatis的逆向工程生成相应的bean、mapper、mapperdao
    1.编写mbg.xml配置文件,配置自动生成的相关参数,具体如下




<generatorConfiguration>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        commentGenerator>
        
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost/users"
                        userId="root"
                        password="Pankx0128">
        jdbcConnection>

        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        javaTypeResolver>

        
        <javaModelGenerator
                targetPackage="com.pankx.bean"
                targetProject="./src/main/java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        javaModelGenerator>
        
        <sqlMapGenerator
                targetPackage="mappers"
                targetProject="./src/main/resources">
            <property name="enableSubPackages" value="true" />
        sqlMapGenerator>
        
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.pankx.dao"
                             targetProject="./src/main/java">
            <property name="enableSubPackages" value="true" />
        javaClientGenerator>
        
        <table tableName="tbl_user" domainObjectName="User"/>
        <table tableName="tbl_utype" domainObjectName="UType"/>
    context>
generatorConfiguration>

2.编写执行逆向工程的测试类,并执行,此时项目目录会生成相应的文件,代码实现如下

    public static void main(String[] arg) throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("mbg.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }
  • Spring整合SpringMVC,需要涉及到配置文件web.xml、springmvc.xml、applicationconfig.xml
  • 配置web.xml,在web.xml中配置前端控制、处理中文乱码过滤器等。具体如下
  
  <filter>
    <filter-name>characterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>UTF-8param-value>
    init-param>
    <init-param>
      <param-name>forceRequestEncodingparam-name>
      <param-value>trueparam-value>
    init-param>
    <init-param>
      <param-name>forceResponseEncodingparam-name>
      <param-value>trueparam-value>
    init-param>
  filter>
  <filter-mapping>
    <filter-name>characterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

  
  <filter>
    <filter-name>httpPutFormContentFilterfilter-name>
    <filter-class>org.springframework.web.filter.HttpPutFormContentFilterfilter-class>
  filter>
  <filter-mapping>
    <filter-name>httpPutFormContentFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

  
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationconfig.xmlparam-value>
  context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>


  <servlet>
    <servlet-name>dispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>

    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServletservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>
  • 配置springmvc.xml具体如下

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <context:component-scan base-package="com.pankx" >
    
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>

    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    bean>
    
    <mvc:default-servlet-handler/>
    
    <mvc:annotation-driven/>

beans>
  • Spring整合MyBatis只需Spring的配置文件applicationconfig.xml中完成MyBatis的相关配置,配置数据库连接池、SqSessionFactory工厂Bean,使用MapperScannerConfigurer来配置Dao接口所在的包。具体配置如下

   <context:component-scan base-package="com.pankx">
       <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
   context:component-scan>

   <context:property-placeholder location="classpath:mysqlproperties.properties"/>

   <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <property name="driverClass" value="${jdbc.driverClass}"/>
       <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
       <property name="user" value="${jdbc.user}"/>
       <property name="password" value="${jdbc.password}"/>
   bean>
   

   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
       
       <property name="plugins">
           <array>
               <bean class="com.github.pagehelper.PageInterceptor"/>
           array>
       property>

       <property name="dataSource" ref="dataSource"/>
       <property name="mapperLocations" value="classpath:mappers/*.xml"/>
   bean>

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
   <property name="dataSource" ref="dataSource"/>
bean>

   <tx:advice id="transactionInterceptor" transaction-manager="transactionManager">
       <tx:attributes>
           <tx:method name="*"/>
           <tx:method name="get*" read-only="true"/>
       tx:attributes>
   tx:advice>

   <aop:config>
       <aop:advisor advice-ref="transactionInterceptor" pointcut="execution(* com.pankx.service.*.*(..))"/>
   aop:config>

   <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="basePackage" value="com.pankx.dao"/>
   bean>

4.测试ssm环境

  • 创建service类文件TestService.java、controller文件TestController.java、测试请求页面testssm.jsp与成功跳转的页面testsuccess.jsp。
  • 如果通过testssm.jsp页面提交的请求成功跳转到testsuccess.jsp页面并显示从数据库查询到的值,则会表示环境搭建成功。
  • 文件代码内容可以查看源码。在此不再给出。

分页实现

  • 本例使用pagehelper对查询到的数据进行分布显示
  • 引入pagehelper所依赖的jar包,由于刚开始已经引入项目所需jar,故不需再重复引入
  • 在applicationconfig.xml文件中的sqlSessionFactory的bean中加载分页配置
  • 使用PageHelper的startPage(pageNum,pageSize)方法进行分页,pageNum为第几页面开始,pageSize为一页有多少条记录
  • 使用PageInfo封装查询返回的结果,并设置连续显示页面的导航页数

使用前端框架bootstrap搭建用户列表页面

  • 在webapp目录下创建static目录用于存放项目的静态资源,把下载好的bootstrap框架代码拷贝到static下
  • 在static目录下创建js目录,把Jquery也拷贝到js目录中
  • 在index.jsp中引入bootstrap的相关资源与jquery
  • 编写index.jsp显示用户列表的前端相关代码,主要代码如下
 <div class="container">
        <div class="row">
            <div class="col-sm-12"><h1>用户列表h1>div>
        div>
        
        <div class="row">
            <div class="col-sm-2">div>
            <div class="col-sm-offset-10">
                <button class="btn btn-primary">新增button>
                <button class="btn btn-danger">删除button>
            div>
        div>

        
        <div class="row">
            <div class="col-sm-12">
                <table class="table table-hover" id="user_table">
                    <thead>
                        <th>用户IDth>
                        <th>用户名th>
                        <th>姓别th>
                        <th>邮箱th>
                        <th>用户类型th>
                        <th>操作th>
                    thead>
                    <tbody>
                    <td>1td>
                    <td>test1td>
                    <td>td>
                    <td>[email protected]td>
                    <td>普通用户td>
                    <td>
                        <button class="btn btn-primary">编辑button>
                        <button class="btn btn-danger">删除button>
                    td>
                    tbody>
                table>
            div>
        div>
        
        <div class="row">
            
            <div class="col-sm-6">当前第1页,总1000页,总10000记录div>
            
            <div class="col-sm-6">
                <nav aria-label="Page navigation">
                    <ul class="pagination">
                        <li>
                            <a href="#" aria-label="Previous">
                                <span aria-hidden="true">«span>
                            a>
                        li>
                        <li><a href="#">1a>li>
                        <li><a href="#">2a>li>
                        <li><a href="#">3a>li>
                        <li><a href="#">4a>li>
                        <li><a href="#">5a>li>
                        <li>
                            <a href="#" aria-label="Next">
                                <span aria-hidden="true">»span>
                            a>
                        li>
                    ul>
                nav>
            div>
        div>
    div>
  • 这个列表页面的数据为写死的,下面使用ajax发请求到服务器获取用户列表数据动态显示到列表页。

实现用户列表页面数据显示

  • 编写控制器类的查询请求处理方法,主要实现代码如下:
 /**
     * 查询所有用户信息,返回以json格式返回
     * @param pn
     * @return
     */
    @RequestMapping(value = "/user",method = GET)
    @ResponseBody
    public Msg getusers(@RequestParam(value = "pn",defaultValue = "1") int pn){
        //开始分页每页记录条数为5
        PageHelper.startPage(pn,5);
        //查询所有用户记录
        List<User> list = userService.getUsers();
        //封装查询结果
        PageInfo pageInfo = new PageInfo(list,5);
        Msg msg = Msg.success().add("pageinfo",pageInfo);
        return msg;
    }
  • 在用户列表页面直接发送ajax请求获取到用户信息并显示,具体代码如下
    <div class="container">
        <div class="row">
            <div class="col-sm-12"><h1>用户列表h1>div>
        div>
        
        <div class="row">
            <div class="col-sm-2">div>
            <div class="col-sm-offset-10">
                <button class="btn btn-primary">新增button>
                <button class="btn btn-danger">删除button>
            div>
        div>

        
        <div class="row">
            <div class="col-sm-12">
                <table class="table table-hover" id="user_table">
                    <thead>
                        <th>用户IDth>
                        <th>用户名th>
                        <th>姓别th>
                        <th>邮箱th>
                        <th>用户类型th>
                        <th>操作th>
                    thead>
                    <tbody>tbody>
                table>
            div>
        div>
        
        <div class="row">
            
            <div class="col-sm-6" id="page_msg">div>
            
            <div class="col-sm-6">
                <nav aria-label="Page navigation">
                    <ul class="pagination">
                        <li>
                            <a href="#" aria-label="Previous">
                                <span aria-hidden="true">«span>
                            a>
                        li>
                        <li><a href="#">1a>li>
                        <li><a href="#">2a>li>
                        <li><a href="#">3a>li>
                        <li><a href="#">4a>li>
                        <li><a href="#">5a>li>
                        <li>
                            <a href="#" aria-label="Next">
                                <span aria-hidden="true">»span>
                            a>
                        li>
                    ul>
                nav>
            div>
        div>
    div>
    <script type="text/javascript">
        //页面加载完成发送ajax请求到服务器获取数据
        $(function(){
            get_emps(1);
        });
        //发送ajax请求方法
        function get_emps (pn){
            $.ajax({
                url:"${APP_PATH}/user",
                data:"pn="+ pn,
                type:"GET",
                success:function(data){
                    console.log(data);
                    //解析数据到table
                    user_table(data);
                    //处理显示分布的信息
                    page_msg(data);

                }
            });
        }
        //解析数据到table
        function user_table(data){
            //清空tbody内容再添加
            $("#user_table tbody").empty();
            var users = data.reldata.pageinfo.list;
            console.log(users);
            //遍历返回的数据并解析显示到table
            $.each(users,function(index,item){
                //用户id单元格
                var useridTd = $("").append(item.userId);
                //用户名单元格
                var userNameTd = $("").append(item.userName);
                //用户姓别单元格
                var genderTd = $("").append(item.gender=="M"?"男":"女");
                //用户邮箱单元格
                var emailTd = $("").append(item.email);
                //用户类型单元格
                var uTypeTd = $("").append(item.uType.utypeName);
                //编辑按钮
                var edit_btn = $("").addClass("btn btn-primary btn-sm").append("").addClass("glyphicon glyphicon-pencil").append("编辑");
                //删除按钮
                var del_btn = $("").addClass("btn btn-danger btn-sm").append("").addClass("glyphicon glyphicon-trash").append("删除");
                var btnTd = $("").append(edit_btn).append(" ").append(del_btn);
                $("").append(useridTd).append(userNameTd).append(genderTd).append(emailTd).append(uTypeTd).append(btnTd).appendTo($("#user_table tbody"));
            });
        }
        //处理分页信息
        function page_msg(data){
            var pageInfo = data.reldata.pageinfo;
            $("#page_msg").append("当前第"+pageInfo.pageNum+"页,总"+pageInfo.pages+"页,总"+pageInfo.total+"记录")
        }
    script>
  • 员工列表效果图如下
    ssm整合开发项目实践(上)_第1张图片
    至此通过ajax发送请求获取用户信息实现的用户列表页面已经基本完成,为缩短文章篇幅,改善阅读体验,项目的分页条相关实现,新增、删除用户等功能将在后续文章中推出,请关注后续的文章。本项目的源代码已发到github仓库,建议结合源代码阅读本文,项目源码:UserManagement

    关注我的公众号获取后续精彩内容

欢迎关注我的公众号

你可能感兴趣的:(java,java,spring)