栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringMVC学习(三)----SSM整合

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringMVC学习(三)----SSM整合

SSM整合的步骤---后端编写 1.创建数据库表

2.新建一个maven的项目,webapp的模板

3.修改目录

4.修改pom.xml文件



  4.0.0

  org.example
  SpringMVC_SSM
  1.0-SNAPSHOT
  war

    
    
        
        4.12
        
        5.2.5.RELEASE
        
        3.5.1
        
        1.3.1
        
        1.2.15
        
        5.1.32
        
        1.6.4
        
        1.1.12
        
        5.1.2
        
        1.2
        
        3.0.1
        
        2.0
        
        2.9.6
    


    
        
        
            org.springframework
            spring-context
            ${spring.version}
        
        
            org.springframework
            spring-beans
            ${spring.version}
        
        
            org.springframework
            spring-webmvc
            ${spring.version}
        
        
            org.springframework
            spring-jdbc
            ${spring.version}
        
        
            org.springframework
            spring-aspects
            ${spring.version}
        
        
            org.springframework
            spring-jms
            ${spring.version}
        
        
            org.springframework
            spring-context-support
            ${spring.version}
        
        
            org.springframework
            spring-test
            5.2.5.RELEASE
        
        
        
            org.mybatis
            mybatis
            ${mybatis.version}
        
        
            org.mybatis
            mybatis-spring
            ${mybatis.spring.version}
        
        
            com.github.miemiedev
            mybatis-paginator
            ${mybatis.paginator.version}
        
        
            com.github.pagehelper
            pagehelper
            ${pagehelper.version}
        
        
        
            mysql
            mysql-connector-java
            ${mysql.version}
        
        
        
            com.alibaba
            druid
            ${druid.version}
        

        
        
            junit
            junit
            ${junit.version}
            test
        


        
        
            jstl
            jstl
            ${jstl.version}
        
        
            javax.servlet
            javax.servlet-api
            3.0.1
            provided
        
        
            javax.servlet
            jsp-api
            provided
            ${jsp-api.version}
        
        
        
            com.fasterxml.jackson.core
            jackson-databind
            ${jackson.version}
        

    

    
    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    1.8
                    1.8
                    UTF-8
                
            
        
        
        
            
                src/main/java
                
                    ***.xml
                
                false
            
            
                src/main/resources
                
                    ***.xml
                
                false
            
        
    


5.添加jdbc.properties文件(数据库信息文件)
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/**?useUnicode=true&characterEncoding=utf8
jdbc.username=****
jdbc.password=****
6.添加SqlMapCofig.xml文件(MyBatis的核心配置文件)



    
    
        
    
    
7.添加applicationContext_mapper.xml文件(数据访问层的核心配置文件----Spring控制MyBatis)


    
    
    
    
        
        
        
        
    
    
    
        
        
        
        
        
        
    
    
    
        
    


8.添加applicationContext_service.xml文件(业务逻辑层的核心配置文件----Spring)



    

    
        
    

    
        
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
        
    



    
    

9.添加springmvc文件(界面层----springmvc)



    
    

    
    

10.删除web.xml新建一个版本高一点的web.xml并注册springmvc,设置中文编码并注册spring框架


    
    
        encode
        org.springframework.web.filter.CharacterEncodingFilter
        
        
        
            encoding
            UTF-8
        
        
            forceRequestEncoding
            true
        
        
            forceResponseEncoding
            true
        
    
    
        encode
        /*
        
    
    
    
        springmvc
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:springmvc.xml
        
    
    
        springmvc
        /
    

    
        org.springframework.web.context.ContextLoaderListener
    

    
        contextConfigLocation
        classpath:applicationContext_*.xml
    
11.创建实体类User
package com.ys.pojo;

public class User {
    private Integer userId;
    private String cardType;
    private Integer cardNo;
    private String userName;
    private String userSex;
    private Integer userAge;

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", cardType='" + cardType + ''' +
                ", cardNo=" + cardNo +
                ", userName='" + userName + ''' +
                ", userSex='" + userSex + ''' +
                ", userAge=" + userAge +
                ", userRole='" + userRole + ''' +
                '}';
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getCardType() {
        return cardType;
    }

    public void setCardType(String cardType) {
        this.cardType = cardType;
    }

    public Integer getCardNo() {
        return cardNo;
    }

    public void setCardNo(Integer cardNo) {
        this.cardNo = cardNo;
    }

    public String getUserName() {
        return userName;
    }

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

    public String getUserSex() {
        return userSex;
    }

    public void setUserSex(String userSex) {
        this.userSex = userSex;
    }

    public Integer getUserAge() {
        return userAge;
    }

    public void setUserAge(Integer userAge) {
        this.userAge = userAge;
    }

    public String getUserRole() {
        return userRole;
    }

    public void setUserRole(String userRole) {
        this.userRole = userRole;
    }

    public User(Integer userId, String cardType, Integer cardNo, String userName, String userSex, Integer userAge, String userRole) {
        this.userId = userId;
        this.cardType = cardType;
        this.cardNo = cardNo;
        this.userName = userName;
        this.userSex = userSex;
        this.userAge = userAge;
        this.userRole = userRole;
    }

    public User() {
    }

    private String userRole;
}
12.新建UserMapper.java接口
package com.ys.mapper;

import com.ys.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserMapper {
//    分页
  ListselectUserPage(
          @Param("userName") String userName,//作为筛选的条件
          @Param("userSex") String userSex,//作为筛选的条件
          @Param("startRow") int startRow);
  //startRow用于返回分页时的起始行,在分页的limit中不能有表达式,所以t_user3应该提前算出并返回

//    将数据表中的除主键的其他字段封装在user中
//    增加
    int createUser(User user);

//    删除   根据用户编码做删除(主键)
    int deleteUserById(String userId);

//    获取总行数
    int getRowCount(@Param("userName") String userName,//作为筛选的条件
                    @Param("userSex") String userSex);//作为筛选的条件
}
13.新建UserMapper.xml实现增删改功能




    
        
        
        
        
        
        
        
    

    
        user_id,card_type,card_no,user_name,user_sex,user_age,user_role
    

    
        select count(*) from user
        
            
                and user_name like concat('%',#{userName},'%')
            
            
                and user_sex =#{usersex}
            
        
    

14.新建service接口和实现类
package com.ys.service;

import com.ys.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserService {
//  分页查询
    List selectUSerPage(String userName, String userSex, int startRow);
//增加
    int createUser(User user);
//    删除
     int deleteUserById(String userId);
//    计算总行数
int getRowCount(String userName, String userSex);

}

package com.ys.service.Impl;

import com.ys.mapper.UserMapper;
import com.ys.pojo.User;
import com.ys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    //切记:业务逻辑层一定会有数据访问层的对象
    @Autowired
    UserMapper userMapper;

    @Override
    public List selectUSerPage(String userName, String userSex, int startRow) {
        return userMapper.selectUserPage(userName,userSex,startRow);
    }

    @Override
    public int createUser(User user) {
        return userMapper.createUser(user);
    }

    @Override
    public int deleteUserById(String userId) {
        return userMapper.deleteUserById(userId);
    }

    @Override
    public int getRowCount(String userName, String userSex) {
        return userMapper.getRowCount(userName,userSex);
    }
}
15.新建测试类,完成所有功能的测试

在测试添加功能时,如果出现错误,但是数据库中又出现了该数据,可能是重复提交所造成的修改方法如下:进入下列文件中,取消掉勾选

package test;

import com.ys.pojo.User;
import com.ys.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)//启动Spring容器
@ContextConfiguration(locations = {"classpath:applicationContext_mapper.xml","classpath:applicationContext_service.xml"})
//使用Spring接管测试
public class MyTest {
    @Autowired
    UserService userService;
    @Test
    public void selectUSerPageTest(){
        List list=userService.selectUSerPage("三","男",0);
        list.forEach(user -> System.out.println(user));
    }
    @Test
    public void createUserTest(){
        User user=new User(154568793,"2",3,"4","5",6,"7");
        int list=userService.createUser(user);
        System.out.println(list);
    }

    @Test
    public void deleteUserByIdTest(){
        int list=userService.deleteUserById("154568793");
        System.out.println(list);
    }

    @Test
    public void getRowCount(){
       int list=userService.getRowCount(null,null);
      System.out.println(list);
    }


}

file->setting->Buid,Execution,Deployment->Build Tools->Maven->Runner

 

16.新建控制器,完成所有功能
package com.ys.controller;

import com.ys.pojo.User;
import com.ys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

//@RestController  如果本类中的请求全部都是ajax请求,那么可以使用此注解,
// 则方法上的@ResponseBody注解可以不写  且@RestController是替换的@Controller
@Controller
@RequestMapping("/user")//添加虚拟路径
public class UserController {
    //    界面层必须有业务逻辑层的对象
    @Autowired
    UserService userService;
    //    定义每页的数据条数
    public static final int Page_Size = 5;

    @RequestMapping("/selectUserPage")
    @ResponseBody//ajax请求必须的注解
//    分页查询
    public List selectUserPage(String userName, String userSex, Integer page) {
//        根据页码计算起始行
        int startRow = 0;
        if (page != null) {
            startRow = (page - 1) * Page_Size;
        }
        return userService.selectUSerPage(userName, userSex, startRow);
    }


    //    获取总行数
    @RequestMapping("/getRowCount")
    @ResponseBody
    public int getRowCount(String userName, String userSex) {
        return userService.getRowCount(userName, userSex);
    }

    //    增加
    @RequestMapping("/createUser")
    @ResponseBody
    public int createUser(User user) {
        int userId=(int)(Math.random()*999999999);
        user.setUserId(userId);
        return userService.createUser(user);
    }

    //    删除
    @RequestMapping("/deleteUserById")
    @ResponseBody
    public int createUser(String userId) {
        return userService.deleteUserById(userId);
    }
}
17.浏览器测试功能

 

 

18.完整目录一览

 SSM整合Vue---前端编写(使用Element UI框架)

Element的官网Element - The world's most popular Vue UI framework

在UserController中的@Controller上面一行添加

@CrossOrigin//支持跨域访问,即前后端的端口不一致时也支持访问

安装node.js---默认路径,一直下一步即可

验证node.js 是否安装成功

使用命令行进入到当前要运行的vue的项目的目录下,运行以下命令进行项目搭建.

cd E:vuedemo01  进入到当前项目的目录下

npm i element -ui -S  下载elementUI的框架

npm install  //打包项目

npm install --save vue-axios  //下载跨域访问组件axios

 在idea安装Vue

在SSM整合的项目中,修改Tomcat服务器,并进行启动

 

 

 使用idea打开vuedemo01文件,在新窗口打开,点击配置选择npm进行如下配置后运行Tomcat

 弹出如下页面

 点击UserHome进入页面,前后端完整数据交互

vue项目内容详解

build 项目构建(webpack)相关代码

config 配置目录,包括端口号等。我们初学可以使用默认的。

node_modules npm 加载的项目依赖模块

src 这里是我们要开发的目录,基本上要做的事情都在这个目录里。里面包含了几个目录及文件:

    assets: 放置一些图片,如logo等。

    components: 目录里面放了一个组件文件,可以不用。

    App.vue: 项目入口文件,我们也可以直接将组件写这里,而不使用 components 目录。

    main.js: 项目的核心文件。

static 静态资源目录,如图片、字体等。

test 初始测试目录,可删除

.xxxx文件 这些是一些配置文件,包括语法配置,git配置等。

index.html 首页入口文件,你可以添加一些 meta 信息或统计代码啥的。

package.json 项目配置文件。

README.md 项目的说明文档,markdown 格式

 UserHome.vue解析

UserHome.vue是所有功能实现的组件.与后台跨域访问,分页显示数据,并实现增加,按主键删除,批量删除,更新,多条件查询等功能.

A.首先确定钩子函数中的启动访问函数
	  created() {
	    this.handlePageChange();           ===>分页
	    this.getRowCount();                ===>计算总行数
	  }
B.分页函数解析
		 handlePageChange() {
		 //定义变量,封装将要提交的数据
	     let postData=this.qs.stringify({
	        page:this.currentPage,
	        userName:this.formInline.search1,
	        userSex:this.formInline.search2
	      });
	      this.$axios({                    ==>发出跨域访问的请求,参考$.ajax();
	        method:'post',                 ==>请求提交的方式
	        url:'/api/user/selectUserPage',==>服务器的地址
	        data:postData  //this.qs.stringify==>{"page":1,"userName":"","userSex":""}                               ==>提交的数据
	      }).then(response=>{              ==>成功后进入到这里
	        this.tableData=response.data;  ==>数据绑定,返回的5个用户的json数据,一下子绑定给表格
	      }).catch(error=>{                ==>出错了进入到这里
	        console.log(error);
	      })
	    }
 C.计算总行数函数分析
	      getRowCount() {
	      //创建变量,提取文本框和下拉列表框中的数据
	      let postData=this.qs.stringify({
	        userName:this.formInline.search1,
	        userSex:this.formInline.search2
	      });
	      this.$axios({                  ==>发出跨域访问的请求,参考$.ajax();
	        method:'post',               ==>请求提交的方式
	        url:'/api/user/getRowCount', ==>服务器的地址
	        data:postData                ===>提交的数据
	      }).then(response=>{
	        this.total=response.data;    ==>返回的总行数赋值给变量total
	      }).catch(error=>{
	        console.log(error);
	      })
	    },
D.按主键删除分析
	  //弹出提示框,让用户确定是否删除 
      this.$confirm('删除操作, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'                      ==>黄色的警告图标
      }).then(() => {                        ==>用户点击确定后进入到这里
        let postData = this.qs.stringify({   ==>封装成JSON数据格式
          userId: row.userId,                ==>将要提交的主键值
        });
        this.$axios({                      ==>发出跨域访问的请求,参考$.ajax();
          method: 'post',                    ==>请求提交的方式
          url: '/api/user/deleteUserById',
          data: postData  //{"userId":15968162893439470}
        }).then(response => {                ==>跨域请求成功后进入这里
          this.getRowCount();     ==>计算删除后的总行数,进行分页插件的页码变化
          ...
          this.handlePageChange();            ==>删除后重新分页
          this.$message({                     ==>删除成功后弹框
            type: 'success',
            message: '删除成功!'
          });          
        }).catch(error => {
          console.log(error);
        });

      }).catch(() => {                        ===>用户点击取消后进入到这里
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1007838.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号