ssm笔记

ssm笔记,第1张

ssm笔记 aop笔记 1. 通过xml配置aop
  1. 创建maven web工程

  2. pom.xml文件导入依赖

       
      
        UTF-8
        1.7
        1.7
        
        4.3.14.RELEASE
    
        
        1.7.22
        1.2.17
    
    
      
    
      
        
          junit
          junit
          4.12
          test
        
    
        
          log4j
          log4j
          ${log4j.version}
        
        
        
          org.springframework
          spring-aop
          ${spring.version}
        
    
        
          org.springframework
          spring-aspects
          ${spring.version}
        
    
        
        
          org.aspectj
          aspectjweaver
          1.8.13
        
    
    
    
        
          org.springframework
          spring-beans
          ${spring.version}
        
    
        
          org.springframework
          spring-context
          ${spring.version}
        
    
        
          org.springframework
          spring-context-support
          ${spring.version}
        
    
        
          org.springframework
          spring-expression
          ${spring.version}
        
    
        
          org.springframework
          spring-instrument
          ${spring.version}
        
    
        
          org.springframework
          spring-instrument-tomcat
          ${spring.version}
        
    
        
          org.springframework
          spring-jdbc
          ${spring.version}
        
    
        
          org.springframework
          spring-jms
          ${spring.version}
        
    
        
          org.springframework
          spring-messaging
          ${spring.version}
        
    
        
          org.springframework
          spring-orm
          ${spring.version}
        
    
        
          org.springframework
          spring-oxm
          ${spring.version}
        
    
        
          org.springframework
          spring-test
          ${spring.version}
        
    
        
          org.springframework
          spring-tx
          ${spring.version}
        
    
        
          org.springframework
          spring-web
          ${spring.version}
        
    
        
          org.springframework
          spring-webmvc
          ${spring.version}
        
    
    
        
        
          org.mybatis
          mybatis
          3.4.6
        
    
        
        
          org.mybatis
          mybatis-spring
          1.3.2
        
    
        
          mysql
          mysql-connector-java
          5.1.45
        
    
    
    
        
        
          commons-fileupload
          commons-fileupload
          1.3.2
        
        
          commons-io
          commons-io
          2.2
        
        
          taglibs
          standard
          1.1.2
        
    
        
          javax
          javaee-api
          8.0
          provided
        
    
    
        
          javax
          javaee-web-api
          8.0
          provided
        
        
          net.sf.json-lib
          json-lib
          2.1
          jdk15
        
        
          javax.servlet
          jstl
          1.2
        
    
    
        
        
        
          com.github.pagehelper
          pagehelper
          5.1.2
        
        
        
          com.github.jsqlparser
          jsqlparser
          0.9.5
        
    
        
        
          org.apache.poi
          poi-ooxml
          3.14-beta1
        
        
          org.apache.poi
          poi-ooxml-schemas
          3.14-beta1
        
        
          org.apache.poi
          poi
          3.14-beta1
        
        
          org.apache.httpcomponents
          httpclient
          4.5.2
        
    
        
        
          org.apache.xmlbeans
          xmlbeans
          2.6.0
        
    
    
        
          com.alibaba
          druid
          1.1.10
        
    
    
    
      
      
       
    
    1. 编写相应的javaBean类
package com.zjj.pojo;

public class Printer {

    public void print(){
        System.out.println("打印机正在打印。。。。。");
    }
}

package com.zjj.pojo;

public class Logger {

    public void loggerBefore(){
        System.out.println("方法开始执行了。。。。。");
    }

    public void loggerAfter(){
        System.out.println("方法执行完毕了。。。。。");
    }
}

package com.zjj.pojo;

import java.util.Date;

public class Timer {

    Date date=new Date();
    public void showTime(){
        System.out.println("当前时间是: "+date);
    }
}
4. 创建spring配置文件,编写相应配置



    
    
    
    

    
    

        
        
        
        
            
            
        

        
        
            
            
        



    

   

5. 测试相应代码 ,单元测试
import com.zjj.pojo.Printer;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestAop1 {

    @Test
    public void test1(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        Printer printer= (Printer) ctx.getBean("p");
        printer.print();
    }
}

2. 通过注解配置aop
  1. 创建maven web工程 同上

  2. 在pom.xml文件里面引入依赖 同上

  3. 编写相应的javaBean类

    package com.zjj.pojo;
    
    import org.springframework.stereotype.Component;
    
    @Component
    public class Printer {
    
        public void print(){
            System.out.println("打印机正在打印。。。。。");
        }
    }
    
    

package com.zjj.pojo;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Aspect
@Order(2)
public class Timer {

    Date date=new Date();

    @Around("execution(* com.zjj.pojo.*.*(..))")
    public void showTime(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("开始时间是: "+date);
        joinPoint.proceed();//在此方法上面的逻辑之前Before 之后的逻辑之后After
        System.out.println("结束时间是: "+date);
    }
}

package com.zjj.pojo;


import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Order(1)
public class Logger {

    @Before("execution(* com.zjj.pojo.*.*(..))")
    public void loggerBefore(){
        System.out.println("方法开始执行了。。。。。");
    }

    @After("execution(* com.zjj.pojo.*.*(..))")
    public void loggerAfter(){
        System.out.println("方法执行完毕了。。。。。");
    }
}

  1. 创建spring配置文件,编写配置,并添加相应注解

    
    
    
        
        
    
        
        
    
       
    
    
  2. 测试相应代码 ,单元测试

import com.zjj.pojo.Printer;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestAop2 {

    @Test
    public  void test2(){

        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        Printer printer = ctx.getBean(Printer.class);
        printer.print();
    }
}

=========================================================================================================

SpringJDBC: 正常jdbc连接数据库流程:
  1. 注册驱动 修建仓库
  2. 获取连接 修路
  3. 获取Statement或者PreparedStatement对象 造车
  4. 执行sql *** 作 拉货
  5. 处理结果集 查询的时候会有结果集 卸货
  6. 关闭资源 车毁了,路砸了

spring框架: http://www.spring.io

使用spring data jdbc流程:
  1. 创建maven web project

  2. pom.xml文件导入相关依赖

  3. 创建application.xml文件 spring配置文件

    application.xml

    
    
    
        
            
            
            
            
            
            
            
            
        
    
        
        
            
        
    
        
        
       
    
    
  4. 创建实体类,dao层代码,service层代码,编写相应逻辑

    ​ User:

    package com.zjj.pojo;
    
    public class User {
    
        Long id;
        String username;
        String password;
        Integer isAdmin;
    
        public User() {
        }
    
        public User(Long id, String username, String password, Integer isAdmin) {
            this.id = id;
            this.username = username;
            this.password = password;
            this.isAdmin = isAdmin;
        }
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public Integer getIsAdmin() {
            return isAdmin;
        }
    
        public void setIsAdmin(Integer isAdmin) {
            this.isAdmin = isAdmin;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", username='" + username + ''' +
                    ", password='" + password + ''' +
                    ", isAdmin=" + isAdmin +
                    '}';
        }
    }
    
    

    UserDao:

    package com.zjj.dao;
    
    import com.zjj.pojo.User;
    
    
    import java.util.List;
    
    public interface UserDao {
        public List queryAll();
    
        public User queryoneById(Long id);
    
        public void addOne(User user);
    
        public void updateOne(User user);
    
        public void deleteoneById(Long id);
    }
    
    
  5. dao实现类里面 注入 JdbcTemplate

    UserDaoImpl:

    package com.zjj.dao.impl;
    
    import com.zjj.dao.UserDao;
    import com.zjj.pojo.User;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.RowMapper;
    import org.springframework.stereotype.Repository;
    
    import java.util.List;
    import java.util.Map;
    
    @Repository
    public class UserDaoImpl implements UserDao {
    
        @Autowired
        private JdbcTemplate jdbcTemplate;
        
    
        @Override
        public List queryAll() {
            String sql="select * from tb_user";
            //将查询出来的结果集合pojo实体类对应
            RowMapper rowMapper=new BeanPropertyRowMapper<>(User.class);
            return jdbcTemplate.query(sql, rowMapper);
    
        }
    
        @Override
        public User queryoneById(Long id) {
            String sql="select * from tb_user where id=?";
            //将查询出来的结果集合pojo实体类对应
            RowMapper rowMapper=new BeanPropertyRowMapper<>(User.class);
            //参数可变参数 和sql语句占位符个数及位置保持一致
            return jdbcTemplate.queryForObject(sql, rowMapper, id);
    
        }
    
        @Override
        public void addOne(User user) {
    
            String sql="INSERT INTO `tb_user` (`id`, `username`, `password`, `isadmin`) VALUES (?, ?, ?, ?)";
            jdbcTemplate.update(sql,user.getId(),user.getUsername(),user.getPassword(),user.getIsAdmin());
    
    
        }
    
        @Override
        public void updateOne(User user) {
    
            String sql="UPDATE `tb_user` SET  `username`=?, `password`=?, `isadmin`=? WHERe (`id`=?)";
            jdbcTemplate.update(sql,user.getUsername(),user.getPassword(),user.getIsAdmin(),user.getId());
        }
    
        @Override
        public void deleteoneById(Long id) {
            String sql="delete from tb_user where id=?";
            jdbcTemplate.update(sql,id);
        }
    }
    
    
  6. 实现增删改查相应 *** 作

UserService:

package com.zjj.service;

import com.zjj.pojo.User;

import java.util.List;

public interface UserService {

    public void queryAll();

    public void queryoneById(Long id);

    public void addOne(User user);

    public void updateOne(User user);

    public void deleteoneById(Long id);
}

UserServiceImpl:

package com.zjj.service.impl;

import com.zjj.dao.UserDao;
import com.zjj.pojo.User;
import com.zjj.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
    private UserDao userDao;
    @Override
    public void queryAll() {
        List users = userDao.queryAll();
        System.out.println(users);

    }

    @Override
    public void queryoneById(Long id) {
        User user = userDao.queryoneById(id);
        System.out.println(user);
    }

    @Override
    public void addOne(User user) {

        userDao.addOne(user);

    }

    @Override
    public void updateOne(User user) {
        userDao.updateOne(user);
    }

    @Override
    public void deleteoneById(Long id) {
        userDao.deleteoneById(id);
    }
}

7.单元测试

package test;

import com.zjj.pojo.User;
import com.zjj.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test1 {

    @Test
    public void testQueryAll(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService= ctx.getBean(UserService.class);
        userService.queryAll();
    }

    @Test
    public void testQueryOne(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService= ctx.getBean(UserService.class);
        userService.queryoneById(1L);
    }

    @Test
    public void testAddOne(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService= ctx.getBean(UserService.class);

        User user=new User(7L,"曹浩","111111",1);
        //注意主键 不能重复  唯一非空
        userService.addOne(user);
    }
    @Test
    public void testUpdateOne(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService= ctx.getBean(UserService.class);

        User user=new User(7L,"孙权","222222",0);
        //注意主键 不能重复  唯一非空
        userService.updateOne(user);
    }

    @Test
    public void testDeleteOne(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService= ctx.getBean(UserService.class);


        //注意主键 不能重复  唯一非空
        userService.deleteoneById(7L);
    }
}

增加AOP切入功能:

在service层增删改查逻辑里面切入时间日志:

  1. 编写切面类

    package com.zjj.pojo;
    
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.springframework.stereotype.Component;
    
    import java.util.Date;
    
    @Component
    @Aspect
    public class Logger {
    
        Date date=new Date();
    
        @Around("execution(* com.zjj.service.impl.*.*(..))")
        public void logger(ProceedingJoinPoint joinPoint) throws Throwable {
    
            System.out.println("开始执行时间是: "+date);
            joinPoint.proceed();
            System.out.println("执行结束时间是: "+date);
    
        }
    }
    
    
  2. 配置切面注解支持

     
        
    
  3. 测试调用

      @Test
        public void testQueryAll(){
            ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService userService= ctx.getBean(UserService.class);
            userService.queryAll();
        }
    
  4. 运行结果

    开始执行时间是: Mon Mar 29 11:21:56 CST 2021
    [User{id=1, username='张三', password='123456', isAdmin=0}, User{id=2, username='李四2', password='111111', isAdmin=1}, User{id=3, username='wangwu', password='111111', isAdmin=0}, User{id=5, username='武松', password='7843784', isAdmin=1}, User{id=6, username='武松', password='7843784', isAdmin=1}]
    执行结束时间是: Mon Mar 29 11:21:56 CST 2021
    
Spring事务 事务概念:

一系列 *** 作指令的集合,组成一个事务。成功同时成功,有一个不成功就都不成功。

特征:

数据库事务 transanction 正确执行的四个基本要素。

ACID: 原子性(Atomicity)、一致性(Correspondence)、隔离 性(Isolation)、持久性(Durability)。

(1)原子性:整个事务中的所有 *** 作,要么全部完成,要么全部不完成,不可能停滞在中间某个环节。事务在执行过程中发生错误,会被回滚(Rollback)到事务开始前的状态,就像这个事务从来没有执行过一样。
(2)一致性:在事务开始之前和事务结束以后,数据库的完整性约束没有被破坏。
(3)隔离性:隔离状态执行事务,使它们好像是系统在给定时间内执行的唯一 *** 作。如果有两个事务,运行在相同的时间内,执行 相同的功能,事务的隔离性将确保每一事务在系统中认为只有该事务在使用系统。这种属性有时称为串行化,为了防止事务 *** 作间的混淆, 必须串行化或序列化请 求,使得在同一时间仅有一个请求用于同一数据。
(4)持久性:在事务完成以后,该事务所对数据库所作的更改便持久的保存在数据库之中,并不会被回滚。

两种实现方式: 基于xml方式实现声明式事务
  1. pom文件里面添加事务的依赖

      
          org.springframework
          spring-tx
          ${spring.version}
        
        
    
  2. 在xml配置文件配置事务的相关配置

    applicationContext.xml

        
        
            
        
    
        
        
            
            
                
                
                
                
            
        
    
        
        
            
            
            
            
        
    
    
  3. UserServiceImpl里面编写方法

    @Override
        public void addTwo() {
            User user1=new User(7L,"张飞","123456",1);
            User user2=new User(1L,"刘备","123456",0);
            userDao.addOne(user1);//正常可以执行成功
            userDao.addOne(user2);//主键重复 必定添加失败 报错
            //由于切入了事务,user1和user2都一起失败  事务 要么一起成功 要么一起失败
        }
    
  4. Test单元测试

      @Test
        public void testAddTwo(){
            ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService userService= ctx.getBean(UserService.class);
    
    
    
            userService.addTwo();
        }
    

​ 最终结果user1和user2都没有添加成功,因为user2失败,所以一起失败! 事务要么一起成功,要么一起失败

基于注解方式来实现声明式事务
  1. pom.xml文件引入spring-tx依赖 同上

  2. 在applicatiionContext.xml文件里面配置事务管理器及事务的注解支持

     	
        
        
            
        
    
        
        
    
  3. 在要事务 *** 作的类上面配置注解

    UserServiceImpl

    @Service
    @Transactional
    public class UserServiceImpl implements UserService {
    ...
    }
    
  4. 单元测试调用

      @Test
        public void testAddTwo(){
            ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService userService= ctx.getBean(UserService.class);
    
    
    
            userService.addTwo();
        }
    

    结果同上,全部没有添加进去,因为事务 一起失败

MyBatis笔记: 什么是MyBatis?
  1. 基于java的数据库持久化框架。 使用java开发,做数据持久化。
  2. 它是一个轻量级,半自动的orm持久化框架。一个轻量级,一个orm框架(Hibernate)数据库表和对象映射。
  3. 通过映射xml来完成数据 *** 作。在映射文件里面写sql语句

ORM: Object Relation Mapping 对象关系映射

mybatis环境搭建:

使用maven工程,mybatis是对jdbc的封装

0. 数据库表 1. 创建maven project 2. pom.xml 文件里面引入 mybatis和mysql依赖
 

        
        
            org.mybatis
            mybatis
            3.4.6
        

        
        
            mysql
            mysql-connector-java
            5.1.45
        
        
        
        
            junit
            junit
            4.12
            test
        
    
3. 创建实体类, dao接口

User:

package com.zjj.pojo;

public class User {
    
    private Long id;
    private String username;
    private String password;
    private Integer isadmin;

    public User() {
    }

    public User(Long id, String username, String password, Integer isadmin) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.isadmin = isadmin;
    }

    public Long getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

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

    public Integer getIsadmin() {
        return isadmin;
    }

    public void setIsadmin(Integer isadmin) {
        this.isadmin = isadmin;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + ''' +
                ", password='" + password + ''' +
                ", isadmin=" + isadmin +
                '}';
    }
}

UserDao:

package com.zjj.dao;

import com.zjj.pojo.User;

public interface UserDao {

    public User findUserById(Long id);
}

4. 创建并配置mybatis配置文件

需要先引入mybatis-3-config.dtd文件

settings---->Schemas and DTDs------>右边点击 + 新建 ------>d框 uri 输入 http://mybatis.org/dtd/mybatis-3-config.dtd file 选择本机mybatis-3-config.dtd文件 ---->apply—>ok

创建数据库连接的properties文件 db.properties,配置数据库连接相关信息

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/b?characterEncoding=utf-8&userSSL=false
jdbc.username=root
jdbc.password=123456

创建mybatis-config.xml 配置文件





    
    
        
    
    
    

    
    
        
    

    
        
            
            
                
                
                
                
            
        
    
    
    
        
    
    


5. 创建并配置mybatis映射文件

UserMapper.xml




    
        select * from tb_user where id= #{id}
    

    
    
        select * from tb_stu
    




  • mybatis-config.xml配置文件中引入映射文件

       
        
           
            
        
    
  • 单元测试

    package test;
    
    import com.zjj.dao.StudentDao;
    import com.zjj.dao.UserDao;
    import com.zjj.pojo.Student;
    import com.zjj.pojo.User;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    public class TestStu {
    
        private SqlSession session;
    
        @Before
        public void getSqlSession() throws IOException {
            //加载配置文件 并读取  通过IO流
            //1. 获取输入流
            InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
            session = sqlSessionFactory.openSession();
        }
    
        @Test
        public void testQueryAll() throws IOException {
    
            //获取接口对象
            StudentDao studentDao = session.getMapper(StudentDao.class);
            List students = studentDao.queryAllStudents();
            System.out.println(students);
        }
    
        @After
        public void close(){
            session.close();
        }
    
    }
    
    
  • 一对一关系:

    通过resultMap标签中的association属性来配置

    1. 数据库表 tb_stu 学生表 和 tb_clazz 班级表

      ​ tb_stu表新增字段cid

      ​ tb_clazz表

      ​ int cid 主键 varchar cname 班级名称 varchar classroom 班级教室号

    2. 实体类 Student 和 Clazz 类

      Student:

      public class Student {
      
          private Integer stuId;
          private String stuName;
          private Date birthday;
          private String address;
          private Clazz clazz;
          
          .....
      }
      

      Clazz:

      public class Clazz {
      
          private Integer id;
          private String className;
          private String classRoom;
          .....
      }    
      
    3. 接口方法

      StudentDao:

       //连表查询
          public List  queryAllStudentsInfo();
      
    4. 映射文件配置

      	
              
              
              
              
              
              
          
      
          
              
              
              
          
      
      
          
              select * from tb_stu
          
      
          
              select * from tb_teacher t,tb_stu s where t.tid=s.tid and t.tid=#{id}
          
      
      
      
      
      
    5. 单元测试

      package test;
      
      import com.zjj.dao.StudentDao;
      import com.zjj.dao.UserDao;
      import com.zjj.pojo.Student;
      import com.zjj.pojo.Teacher;
      import com.zjj.pojo.User;
      import org.apache.ibatis.io.Resources;
      import org.apache.ibatis.session.SqlSession;
      import org.apache.ibatis.session.SqlSessionFactory;
      import org.apache.ibatis.session.SqlSessionFactoryBuilder;
      import org.junit.After;
      import org.junit.Before;
      import org.junit.Test;
      
      import java.io.IOException;
      import java.io.InputStream;
      import java.util.List;
      
      public class TestStu {
      
          private SqlSession session;
      
          @Before
          public void getSqlSession() throws IOException {
              //加载配置文件 并读取  通过IO流
              //1. 获取输入流
              InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
              SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
              session = sqlSessionFactory.openSession();
          }
      
          @Test
          public void testQueryAll() throws IOException {
      
      
      
              //获取接口对象
              StudentDao studentDao = session.getMapper(StudentDao.class);
              List students = studentDao.queryAllStudents();
              System.out.println(students);
      
          }
      
          @Test
          public void testQueryAllInfo() throws IOException {
              //获取接口对象
              StudentDao studentDao = session.getMapper(StudentDao.class);
              List students = studentDao.queryAllStudentsInfo();
              System.out.println(students);
          }
      
          @Test
          public void testQueryTeacherById() throws IOException {
              //获取接口对象
              StudentDao studentDao = session.getMapper(StudentDao.class);
              Teacher teacher = studentDao.queryTeacherById(1);
              System.out.println(teacher);
          }
      
          @After
          public void close(){
              session.close();
          }
      
      }
      
      
    MyBatis配置日志显示SQL语句:

    可以将mybatis执行过程中的sql语句直接在控制台上显示出来,需要相应配置:

    1. pom.xml文件里面引入log4j的依赖

      pom.xml

       
       
           org.apache.logging.log4j
           log4j-core
           2.9.1
       
      
    2. 在resource目录下创建log4j的属性配置文件 log4j.properties,放在resource下面的跟根目录,直接复制即可

      log4j.properties

      log4j.rootLogger=debug,stdout,logfile
      log4j.appender.stdout=org.apache.log4j.ConsoleAppender
      log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
      
      log4j.logger.com.ibatis=DEBUG
      log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
      log4j.logger.com.ibatis.common.jdbc.scriptRunner=DEBUG
      log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
      log4j.logger.Java.sql.Connection=DEBUG
      log4j.logger.java.sql.Statement=DEBUG
      log4j.logger.java.sql.PreparedStatement=DEBUG
      
      
    3. mybatis配置文件中 配置日志

      mybatis-config.xml

       
              
       
      
    4. 单元测试,查看结果

      idea的控制台会显示sql语句及参数

      Created connection 996796369.
      ==>  Preparing: select * from tb_user where username like "%武%" 
      ==> Parameters: 
      <==    Columns: id, username, password, isadmin
      <==        Row: 5, 武松, 7843784, 1
      <==        Row: 6, 武松, 7843784, 2
      <==      Total: 2
      [User{id=5, name='武松', pass='7843784', isadmin=1}, User{id=6, name='武松', pass='7843784', isadmin=2}]
      Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@3b69e7d1]
      Returned connection 996796369 to pool.
      
    动态SQL:
    1. if test 判断

      if test 就是if判断 test为判断的条件
      
    2. where if test where标签

      where 标签相当于sql语句中的where关键字,但能去除第一个多余的and 或者 or
      
    3. trim if test 自定义标签 ,可以实现 where或set的效果

      trim为自定义标签 prefix前缀是什么 trim就相当于哪个标签的作用 prefixOverrides 值为and 或者 or
      
    4. set if test 修改

      set 标签相当于sql语句中的set关键字,但能去除最后一个多余的,
      
    5. foreach 循环

      foreach 循环
          属性:
          item: 集合中的每个元素
          index: 下标
          collection: 集合 值为 list/array/map
          separator: 每个元素的分隔符
          open: 整个循环以什么开头
          close: 整个循环以什么结尾
      

    例子:

    UserDao接口:

    package com.zjj.dao;
    
    import com.zjj.pojo.User;
    import org.apache.ibatis.annotations.Param;
    
    import java.util.List;
    
    
    public interface UserDao {
        //模糊查询
        public List queryStudentsByMohu(@Param("mohu") String mohu);
        //模糊查询
        public List queryStudentsByMohu2(@Param("mohu") String mohu);
        //查询 直接查询
        public List queryStudentsByUsernameAndAdmin(User user);
        //查询 属性不为空根聚这个属性查询,为空则不根据这个属性查询 if test
        public List queryStudentsByUsernameAndAdmin2(User user);
        //查询 属性不为空根聚这个属性查询,为空则不根据这个属性查询 where if test
        public List queryStudentsByUsernameAndAdmin3(User user);
        //查询 属性不为空根聚这个属性查询,为空则不根据这个属性查询 trim if test
        public List queryStudentsByUsernameAndAdmin4(User user);
        //更新 属性不为空则更新,为空则不更新这个字段 set if test
        public void updateUser(User user);
        //根据id的集合查询所有
        public List queryStudentsByIds(List ids);
        //批量添加
        public void insertBatch(List users);
    
    }
    
    

    UserMapper.xml

    
    
    
    
        
    
        
    
            
            
            
            
            
    
        
    
    
        
            select * from tb_user where username like "%${mohu}%" or password like "%${mohu}%"
        
    
        
            select * from tb_user where 1=1
            
                and username=#{name}
            
            
                and isadmin=#{isadmin}
            
    
        
    
        
        
            select * from tb_user
            
                
                    and username=#{name}
                
                
                    and isadmin=#{isadmin}
                
            
        
    
        
        
    
            update tb_user
            
    
                
                     username=#{name},
                
                
                     password=#{pass},
                
                
                     isadmin=#{isadmin}
                
    
            
            where id=#{id}
        
    
        
        
        
        当前页${page.pageNum}|${page.pages}总页数
        
        
        每页显示条记录
    
    
    
    
    
  • 修改登录成功之后跳转到分页的逻辑

    登录成功之后跳转到分页的逻辑,并且登录成功之后吧登陆的用户信息c存到HttpSession对象里面,

    进而可以在首页展示登录用户的信息

    UserController

    @RequestMapping("/login")
    public String login(User user, HttpServletRequest request){
        User htUser = userService.login(user);
        //判断是否登录成功
        if(htUser!=null){
            HttpSession session = request.getSession();
            session.setAttribute("user",htUser);
            return "redirect:listpage";
        }
        //return "redirect:login.jsp";  重定向
       // return "forward:login.jsp";  请求转发
        return "redirect:login.jsp";
    }
    
  • 浏览器访问测试

    http://localhost:8080/stuManage_war/login.jsp

  • demo4: 实现学生信息的增删改查功能

    项目目录结构:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EInfLP8k-1634699919016)(imagecrud01.png)]

    思路:

    添加:

    ​ 由于add.jsp位于WEB-INF目录底下,WEB-INF下的文件内容客户端浏览器无法直接访问,所以需要经过后台中转下

    添加学生信息------>toAdd的后台controller------->add.jsp
    ----->用户输入添加数据,点击添加按钮,跳转到后台add的controller------>
    添加成功,回到listpage分页列表;失败,回到add.jsp继续添加
    

    删除:

    根据id来删除该行的数据信息

    删除------> delete 删除的后台controller
    ------->删除成功,回到listpage分页列表
    

    修改:

    修改功能需要用户再原数据的基础之上吧原数据修改成新数据,所以需要先获取原数据,获取原数据的过程就是查询单个的过程,所以修改时需要先根据id来查询单个

    修改------>load 后台查询单个------>回到update.jsp 原数据回显到修改页面
    -------->   点击修改按钮,实现修改功能-------->update 后台修改功能------>修改成功,回到listpage分页列表
    

    步骤:

    1. dao层及映射文件配置

      StudentDao:

      package com.zjj.dao;
      
      import com.zjj.pojo.Student;
      
      import java.util.List;
      
      public interface StudentDao {
      
          //查询所有
          public List queryAllStudents();
          //查询单个
          public Student queryStudentById(int id);
          //添加学生
          public int addStudent(Student student);
          //修改学生
          public int updateStudent(Student student);
          //删除学生
          public int deleteStudentById(int id);
      }
      

      StudentMapper.xml:

      
      
          
          
              
              
              
              
              
          
      
          
          
              select * from tb_stu where sid=#{id}
          
      
          
              UPDATE tb_stu SET sname=#{stuName}, birthday=#{birthday}, address=#{address}, photo=#{photo} WHERe sid=#{id}
          
      
          
              delete from tb_stu where sid=#{id}
          
      
      
    2. service层及实现类代码

      StudentService:

      package com.zjj.service;
      
      import com.github.pagehelper.PageInfo;
      import com.zjj.pojo.Student;
      
      import java.util.List;
      
      public interface StudentService {
          //查询所有
          public List queryAllStudents();
          //分页查询
          public PageInfo queryStudentsByPage(int currentPage, int pageSize);
      
          //查询单个
          public Student queryStudentById(int id);
          //添加学生
          public boolean addStudent(Student student);
          //修改学生
          public boolean updateStudent(Student student);
          //删除学生
          public boolean deleteStudentById(int id);
      }
      

      StudentServiceImpl:

      package com.zjj.service.impl;
      
      import com.github.pagehelper.PageHelper;
      import com.github.pagehelper.PageInfo;
      import com.zjj.dao.StudentDao;
      import com.zjj.pojo.Student;
      import com.zjj.service.StudentService;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Service;
      import org.springframework.transaction.annotation.Transactional;
      
      import java.util.List;
      
      @Service
      @Transactional
      public class StudentServiceImpl implements StudentService {
      
          @Autowired
          private StudentDao studentDao;
          @Override
          public List queryAllStudents() {
              return studentDao.queryAllStudents();
          }
      
          @Override
          public PageInfo queryStudentsByPage(int currentPage, int pageSize) {
              //传入参数:当前页和每页条数
              PageHelper.startPage(currentPage,pageSize);
              List students = studentDao.queryAllStudents();
              //通过包装获取分页所需的其他值
              PageInfo pageInfo = new PageInfo<>(students);
      
      
              return pageInfo;
          }
      
          @Override
          public Student queryStudentById(int id) {
              return studentDao.queryStudentById(id);
          }
      
          @Override
          public boolean addStudent(Student student) {
              int row = studentDao.addStudent(student);
              if(row>0){
                  return true;
              }
              return false;
          }
      
          @Override
          public boolean updateStudent(Student student) {
              int row = studentDao.updateStudent(student);
              if(row>0){
                  return true;
              }
              return false;
          }
      
          @Override
          public boolean deleteStudentById(int id) {
              int row = studentDao.deleteStudentById(id);
              if(row>0){
                  return true;
              }
              return false;
          }
      }
      
    3. controller层代码

      StudentController:

      package com.zjj.controller;
      
      
      import com.github.pagehelper.PageInfo;
      import com.zjj.pojo.Student;
      import com.zjj.service.StudentService;
      import com.zjj.util.LoadUtil;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Controller;
      import org.springframework.ui.Model;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.multipart.MultipartFile;
      
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import java.util.List;
      
      @Controller
      public class StudentController {
      
          @Autowired
          private StudentService studentService;
      
        
      
          @RequestMapping("list")
          public String listAllStudents(Model model){
              List students = studentService.queryAllStudents();
              model.addAttribute("list",students);
              return "forward:/stulist.jsp";
          }
      
          @RequestMapping("listpage")
          public String listAllStudents(Integer currentPage,Integer pageSize,Model model){
              if(currentPage==null){
                  currentPage=1;
              }
              if(pageSize==null){
                  pageSize=3;
              }
              PageInfo page = studentService.queryStudentsByPage(currentPage, pageSize);
      
              model.addAttribute("page",page);
              return "stulistpage";
          }
      
          @RequestMapping("add")
          public String addStudent(Student student, MultipartFile img){
              String photo = LoadUtil.uploadPhoto(img);
              student.setPhoto(photo);
              boolean flag = studentService.addStudent(student);
              if(flag){
                  return "redirect:listpage";
              }
              return "redirect:toadd";
          }
         
      
          @RequestMapping("toadd")
          public String toAdd(){
      
              return "add";
          }
      
          @RequestMapping("update")
          public String updateStudent(Student student){
              boolean flag = studentService.updateStudent(student);
      
              return "redirect:listpage";
          }
      
          @RequestMapping("delete")
          public String deleteStudent(int id){
              studentService.deleteStudentById(id);
              return "redirect:listpage";
          }
          @RequestMapping("load")
          public String loadStudent(int id, Model model){
              Student student = studentService.queryStudentById(id);
              model.addAttribute("s",student);
              return "update";
          }
      }
      
    4. 日期类型的格式转换器代码编写及配置

      由于add或update是有日期类型的数据,而springmvc无法直接取到日期类型的数据,所以需要自定义一个日期类型的格式转换器

      DateFormatter:

      package com.zjj.convert;
      
      import org.springframework.format.Formatter;
      
      import java.text.ParseException;
      import java.text.SimpleDateFormat;
      import java.util.Date;
      import java.util.Locale;
      
      public class DateFormatter implements Formatter {
          //日期格式化对象
          private SimpleDateFormat dateFormat;
      
          public SimpleDateFormat getDateFormat() {
              return dateFormat;
          }
      
          public void setDateFormat(SimpleDateFormat dateFormat) {
              this.dateFormat = dateFormat;
          }
      
          //解析
          @Override
          public Date parse(String s, Locale locale) throws ParseException {
              return dateFormat.parse(s);
          }
          //显示
          @Override
          public String print(Date date, Locale locale) {
              return dateFormat.format(date);
          }
      }
      

      spring-mvc.xml:

      
      
          ......
      
      
      
      
      
          
          
              
                  
                      
                  
              
      
          
      
      
    5. 前端页面

      stulistpage.jsp:

          
              编号
              学生姓名
              生日
              地址
              头像
              添加学生信息
      
          
      
          
              
                  ${s.id}
                  ${s.stuName}
                  
                      
                  
                  ${s.address}
                  
                      
                  
                  
                      修改
                      删除
                   
                  
      
              
      
          
      
      

      add.jsp:

      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      
      
          Title
      
      
      
      
      添加学生

    ​ update.jsp:

    <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
    
    
        Title
    
    
    
    
    修改学生

    1. 浏览器访问测试效果
    demo5: 使用拦截器实现用户未经登录不能访问主逻辑功能
    1. 创建LoginInterceptor,实现HandlerInterceptor接口

      3个方法,拦截的时机不同:

      boolean preHandle(): 方法执行之前拦截; 返回值true表示放行,false表示拦截

      void postHandle(): 方法接收请求之后,解析视图之前拦截

      void afterCompletion(): 方法执行完毕,视图渲染结束之后执行

      package com.zjj.inter;
      
      import com.zjj.pojo.User;
      import org.springframework.web.servlet.HandlerInterceptor;
      import org.springframework.web.servlet.ModelAndView;
      
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import javax.servlet.http.HttpSession;
      
      public class LoginInterceptor implements HandlerInterceptor {
          //方法执行之前拦截
          @Override
          public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
              HttpSession session = httpServletRequest.getSession();
              User user = (User) session.getAttribute("user");
              //true 放行 false拦截
              if(user!=null){
                  return true;
              }
              httpServletResponse.sendRedirect("login.jsp");
              return false;
          }
          //方法接收请求之后,解析视图之前拦截
          @Override
          public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
      
          }
          //方法执行完毕,视图渲染结束之后执行
          @Override
          public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
      
          }
      }
      
    2. 在springmvc配置文件里面进行拦截器的配置

      spring-mvc.xml

      
          
      
               
    3. 在springmvc xml中配置国际化信息

      默认中文

      
          
      
      
          
          
      
      
    4. jsp中登录页面

      login.jsp

      注意:需要引入spring的标签库:<%@ taglib prefix=“spring” uri=“http://www.springframework.org/tags”%>

      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
      
      
          Title
      
      
      
    5. 一般中文是默认语言,所以需要设置英文成默认语言,以win10为例

      设置 —》 时间和语言 —》左侧选择 区域和语言

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iMxKGDbG-1634699919017)(imagei18n.png)]

    没有英文的就需要添加语言

    到此就实现了国际化,效果如下:

    中文状态下:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TZVxnESs-1634699919018)(imagezh_CN.png)]

    切换英文:

    刷新浏览器:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FPL4w3dq-1634699919019)(imageen.png)]

    SpringBoot环境搭建: 1.项目目录结构

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BHOimtwR-1634699919020)(imageboot01.png)]

    2.新建maven工程

    注意: maven project: 不是maven web project

    3.添加依赖
    
    
        4.0.0
    
        org.example
        springboot-0100
        1.0-SNAPSHOT
    
        
            spring-boot-starter-parent
            org.springframework.boot
            2.1.4.RELEASE
        
    
        
            
                org.springframework.boot
                spring-boot-starter-web
            
        
    
    
    
    
    4. 编写application.properties文件

    在resources根目录底下,文件名固定,不能改

    application.properties: 是SpringBoot的全局配置文件

    server.port=8181
    
    5. 编写main方法

    Application:

    package com.zjj;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class,args);
        }
    }
    
    6. 编写controller

    HelloController:

    package com.zjj.controller;
    
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class HelloController {
    
        @RequestMapping("hello")
        public String hello(){
            return "hello world!!!!";
        }
    }
    
    7. 启动main方法 8.浏览器访问测试

    http://localhost:8181/hello

    运行效果:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ft7QV8Tv-1634699919021)(imageboot02.png)]

    注意:

    浏览器访问的端口号和配置文件的端口号一致,

    main方法所在的类必须在所有组件的父包里面,这样它会自动扫描

    springboot里面内置了tomcat;直接启动main方法即启动tomcat服务器

    SpringBoot+MyBatis实现增删改查 1. 设计数据库表

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EzHVEo7R-1634699919022)(imageboot04.png)]

    2. 新建maven project

    注意:不是maven web project,不需要勾选那个复选框

    3. pom文件添加依赖

    
    
    
      4.0.0
    
      com.bw
      stuManage-boot
      1.0-SNAPSHOT
      war
    
    
      
        spring-boot-starter-parent
        org.springframework.boot
        2.1.4.RELEASE
      
    
    
      
        
          org.springframework.boot
          spring-boot-starter-web
        
    
        
          org.springframework.boot
          spring-boot-starter-test
        
    
        
          org.mybatis.spring.boot
          mybatis-spring-boot-starter
          2.1.3
        
    
        
          mysql
          mysql-connector-java
        
    
        
          org.projectlombok
          lombok
        
      
    
    
    
    
    spring-boot-starter-parent org.springframework.boot 2.1.4.RELEASE

    表示父工程是个SpringBoot项目,继承它自己就成为一个SpringBoot工程了

    4. 配置项目配置信息 application.yml

    配置文件有两种格式: properties和yml

    properties:里面格式是键值对

    yml: 一定要注意缩进;相同层次的缩进必须保持相同,否则会有语法问题

    server:
      port: 8989
    
    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/b?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
        username: root
        password: 123456
    
    mybatis:
      type-aliases-package: com.zjj.pojo
      mapper-locations: classpath:mapper/*Mapper.xml
    logging:
      level:
        com:
          zjj:
            dao: debug
    
    5. 编写main方法

    SpringBoot项目的启动类,必须加上注解@SpringBootApplication

    @MapperScan(“com.zjj.dao”): 表示扫描dao层

    package com.zjj;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    @MapperScan("com.zjj.dao")
    public class MyApplication {
        public static void main(String[] args) {
            SpringApplication.run(MyApplication.class,args);
        }
    }
    
    6. 编写pojo实体类
    package com.zjj.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import org.springframework.format.annotation.DateTimeFormat;
    
    import java.util.Date;
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Student {
        private Integer id;
        private String stuName;
    
        @DateTimeFormat(pattern="yyyy-MM-dd")
        private Date birthday;
        private String address;
        private String photo;//头像
    
    }
    
    7. 编写dao层代码及映射文件

    接口上面必须加注解@Mapper

    package com.zjj.dao;
    
    import com.zjj.pojo.Student;
    import org.apache.ibatis.annotations.Mapper;
    
    import java.util.List;
    
    @Mapper
    public interface StudentDao {
    
        //查询所有
        public List queryAllStudents();
    
        public int addStudent(Student student);
    
        public int deleteStudentById(Integer id);
    
        public int updateStudent(Student student);
    
        public Student queryoneStudentById(Integer id);
    }
    

    StudentMapper.xml映射文件,位于resources/mapper目录底下

    
    
        
        
            
            
            
            
            
        
    
        
        
             select * from tb_stu where sid=#{id}
        
    
        
            INSERT INTO `tb_stu` (`sid`, `sname`, `birthday`, `address`, `photo`) VALUES (0, #{stuName}, #{birthday}, #{address}, #{photo})
        
    
        
            UPDATE tb_stu SET  `sname`=#{stuName},  `birthday`=#{birthday}, `address`=#{address}, `photo`=#{photo} WHERe `sid`=#{id}
        
    
        
            delete from tb_stu where sid=#{id}
        
    
    
    8. 编写service层代码及实现类

    Service接口:

    package com.zjj.service;
    
    import com.zjj.pojo.Student;
    
    import java.util.List;
    
    public interface StudentService {
        public List queryAllStudents();
    
        public boolean addStudent(Student student);
    
        public boolean deleteStudentById(Integer id);
    
        public boolean updateStudent(Student student);
    
        public Student queryoneStudentById(Integer id);
    }
    

    Service实现类: 注解上面的注解 @Service @Transactional

    package com.zjj.service.impl;
    
    import com.zjj.dao.StudentDao;
    import com.zjj.pojo.Student;
    import com.zjj.service.StudentService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import java.util.List;
    
    @Service
    @Transactional
    public class StudentServiceImpl implements StudentService {
    
        @Autowired
        private StudentDao studentDao;
        @Override
        public List queryAllStudents() {
            return studentDao.queryAllStudents();
        }
    
        @Override
        public boolean addStudent(Student student) {
            int row = studentDao.addStudent(student);
            if(row>0){
                return true;
            }
            return false;
        }
    
        @Override
        public boolean deleteStudentById(Integer id) {
            int row = studentDao.deleteStudentById(id);
            if(row>0){
                return true;
            }
            return false;
        }
    
        @Override
        public boolean updateStudent(Student student) {
            int row = studentDao.updateStudent(student);
            if(row>0){
                return true;
            }
            return false;
        }
    
    
        @Override
        public Student queryoneStudentById(Integer id) {
            return studentDao.queryoneStudentById(id);
        }
    
    
    }
    
    9. 编写controller层代码及实现类

    @RestController 表示返回json数据到浏览器上面

    package com.zjj.controller;
    
    
    import com.zjj.pojo.Student;
    import com.zjj.service.StudentService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    
    @RestController
    public class StudentController {
    
        @Autowired
        private StudentService studentService;
    
        @GetMapping
        public List listAllStudents(){
            return studentService.queryAllStudents();
    
        }
    
        @GetMapping("/{id}")
        public Student loadStudentById(@PathVariable int id){
            return studentService.queryoneStudentById(id);
    
        }
    
        @PostMapping
        public boolean addStudent(@RequestBody Student student){
           return studentService.addStudent(student);
        }
    
        @PutMapping
        public boolean updateStudent(@RequestBody Student student){
            return studentService.updateStudent(student);
    
        }
    
        @DeleteMapping("{id}")
        public boolean deleteStudentById(@PathVariable int id){
            return studentService.deleteStudentById(id);
        }
    
    }
    
    10. 启动main方法

    SpringBoot内置Tomcat,启动main方法即启动tomcat

    SpringBoot对jsp支持不好,一般SpringBoot项目使用前后端分离

    11.使用PostMan访问测试效果

    下载PostMan测试软件

    Vue语法:

    参考文档: https://www.runoob.com/vue2/vue-tutorial.html

    环境: nodejs

    前端开发工具: Visual Studio Code

    自行下载安装:

    nodejs安装步骤参考网上教程,需要配置环境变量;

    VSC: 安装成功后 安装两个插件:

    扩展 菜单搜索 Chinese Language 中文插件 Live Server服务器 安装即可

    vue-demo:

    需要下载并引入vue.min.js vue的库文件

    
    
    
        
        
        document
    
    
    
        
    
            vue语法
            您的生日是:{{
                new Date(birthday).getFullYear() + '-'+ new Date(birthday).getMonth()+ '-' + new Date(birthday).getDay()
                }}
            
            您的生日是:{{birth}} 
    
            欢迎您: {{name}}
    num:{{num}}
    num:
    num1: {{num1}} num2: {{num2}} 请输入第一个数: 请输入第二个数: 和是:{{sum}} {{add2()}} 求和:
    地址: 取对象属性: name: {{person.name}} age: {{person.age}} address: {{person.address}}
    取数组: {{arr}} 循环遍历:


    {{num}}

    {{num1}}

    编号 姓名 年龄 添加 {{s.id}} {{s.name}} {{s.age}} 删除 修改
    使用VUE搭建前端页面,实现前后端对接:

    注意:

    页面需要引入3个库文件:

    vue的库文件, ajax的库文件, 日期处理的库文件

    stulist: 列表页面

    
    
    
        
        
        document
    
    
    
        
                学生列表
               
                
                    
                        编号
                        学生姓名
                        生日
                        地址
                        头像
                        添加学生
                    
                   
                    
                        {{s.id}}
                        {{s.stuName}}
                        
                            {{moment(s.birthday).format("YYYY-MM-DD")}}
                        
                        {{s.address}}
                        {{s.photo}}
                        
                            
                            
                            
                        
                    
                
        
        
    
    
    
    
    
    
    

    add.html: 添加页面

    
    
    
        
        
        document
    
    
    
        
                添加学生
               
                
                    
                        学生姓名
                        
                        
                    
                    
                        生日
                        
                        
                    
                    
                        地址
                        
                        
                    
                    
                        头像
                        
                        
                    
                    
                    
                        
                        
                            
                            
    
                        
                        
                    
    
              
                
                
        
        
    
    
    
    
    
    
    

    update.html: 修改页面

    
    
    
        
        
        document
    
    
    
        
                修改学生
               
                
                    
                        学生编号
                                   
                    
                    
                        学生姓名
                        
                        
                    
                    
                        生日
                        
                        
                    
                    
                        地址
                        
                        
                    
                    
                        头像
                        
                        
                    
                    
                    
                        
                            
                        
                                                              
                            
                        
                        
                    
    
              
                
                
        
        
    
    
    
    
    
    
    

    前端直接右键 live-server 服务器运行打开即可

    后台Controller上加个注解: @CrossOrigin 解决跨域问题

    什么是跨域问题? 百度一下

    欢迎分享,转载请注明来源:内存溢出

    原文地址: http://outofmemory.cn/zaji/4024625.html

    (0)
    打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
    上一篇 2022-10-22
    下一篇 2022-10-22

    发表评论

    登录后才能评论

    评论列表(0条)

    保存