专栏首页JAVA人生/面试技巧Springboot前后端分离开发

Springboot前后端分离开发

.1.springboot前后端分离开发之前要配置好很多东西,这周会详细补充博客内容和遇到的问题的解析

2,按照下面流程走一遍

此时会加载稍等一下

pom.xml显示中加上阿里云镜像可以加速下载配置文件等,或者直接复制我的所有代码

    <!-- druid数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.kude.stu</groupId>
    <artifactId>kudestu</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>kudestu</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- druid数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

记得手动导入配置,如果自动导入以后一旦更改以后会遇到很多麻烦

resources加入配置文件的代码

#数据源配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/stu?useSSL=false&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.initialSize=20
spring.datasource.minIdle=50
spring.datasource.maxActive=500

#上下文配置
server.port=8888
server.servlet.context-path=/stu

#配置jpa
#帮我们自动生成表结构
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

一定要按照这个来定义类

下面是具体的代码

StudentController

package com.kude.stu.kudestu.stu.controller;

import com.kude.stu.kudestu.stu.entity.Student;
import com.kude.stu.kudestu.stu.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/s")
public class StudentController {

    @Autowired
    private StudentService studentService;

    /**
     * 添加学生
     * @param student 要添加的学生对象
     * @return
     */
    @PostMapping("/add")
    public Student save(Student student){
        return studentService.save(student);
    }

    /**
     * 修改学生
     * @param student
     * @return
     */
    @PostMapping("/update")
    public Student update(Student student){
        return studentService.save(student);
    }

    /**
     * 删除学生
     * @param id 要删除的学生id
     * @return
     */
    @GetMapping("/del/{id}")
    public String del(@PathVariable int id){
        studentService.delete(id);
        return "yes";
    }


    @GetMapping("/findByName/{name}")
    public List<Student> findByName(@PathVariable String name){
        return studentService.findStuByName(name);
    }

    @GetMapping("/query")
    public Page<Student> findByPage(Integer page, HttpServletResponse response){

        response.setHeader("Access-Control-Allow-Origin","*");

        if(page==null || page<=0){
            page = 0;
        }else{
            page -= 1;
        }

        return studentService.findAll(page,5);
    }

}

UserController

package com.kude.stu.kudestu.stu.controller;


import com.kude.stu.kudestu.stu.entity.User;
import com.kude.stu.kudestu.stu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 处理用户信息的控制层
 * @author cxf
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 查询用户的方法
     */
    @RequestMapping("/findAll")
    public List<User> findAll(){
        return userService.findAll();
    }

    /**
     * 根据ID查询用户
     */
    @RequestMapping("/query")
    public User findById(int id){
        return userService.findUserById(id);
    }

    /**
     * 注册用户
     */
    @RequestMapping(value = "/reg",method = RequestMethod.POST)
    public User reg(User user){
        return userService.save(user);
    }

    /**
     * 用户登陆
     */
    //@RequestMapping(value = "/login",method = RequestMethod.POST)
    //public User login(String username,String password){
    //return userService.login(username,password);
    //  }


    /**
     * 用户登陆
     */
    @PostMapping("/login")
    public User login(String username,String password){
        return userService.login(username,password);
    }


    //这个分页还是没用判断好,如果页数p超过3以后,回返回全部是空值
    //应对超越页码数的进行限制一下
    /**
     * 分页查询
     */
    @RequestMapping("/page")
    public Page<User> findByPage(Integer p, HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin","*");
        if(p==null || p<=0){
            p = 0;
        }else{
            p-=1;
        }
        return userService.findByPage(p,2);
    }

    /**
     * 修改
     */
    @RequestMapping("/updata")
    public User update(User user){
        return userService.update(user);
    }

    /**
     * 删除
     */
    @RequestMapping("/del")
    public String del(int id){
        userService.delete(id);
        return "yes";
    }
}

StudentDao

package com.kude.stu.kudestu.stu.dao;

import com.kude.stu.kudestu.stu.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;


public interface StudentDao extends JpaRepository<Student,Integer> {

    Student findStudentById(Integer id);

    @Query(name = "findStuByName",nativeQuery = true,value =
            "select * from student where name=:name")
    List<Student> findStuByName(@Param("name") String name);

}

UserDao

package com.kude.stu.kudestu.stu.dao;

import com.kude.stu.kudestu.stu.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface UserDao extends JpaRepository<User,Integer> {

    User findUserById(Integer id);

    //@Query("select id,username,password from user where username=?1 and password=?2")
    // User login(@Param("username") String username, @Param("password") String password);



    //如何两个usernam或者password一样的User用户,回出现500错误
    //这种方法不能用username或者password登入

    @Query(name="login",nativeQuery = true,value =
            "select * from user where username=:username and password=:password")
    User login(@Param("username") String username, @Param("password") String password);

}

Student

package com.kude.stu.kudestu.stu.dao;

import com.kude.stu.kudestu.stu.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface UserDao extends JpaRepository<User,Integer> {

    User findUserById(Integer id);

    //@Query("select id,username,password from user where username=?1 and password=?2")
    // User login(@Param("username") String username, @Param("password") String password);



    //如何两个usernam或者password一样的User用户,回出现500错误
    //这种方法不能用username或者password登入

    @Query(name="login",nativeQuery = true,value =
            "select * from user where username=:username and password=:password")
    User login(@Param("username") String username, @Param("password") String password);

}

User

package com.kude.stu.kudestu.stu.entity;

import javax.persistence.*;

@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String username;
    private String password;

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

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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 User() {
    }
}

StudentService

package com.kude.stu.kudestu.stu.service;

import com.kude.stu.kudestu.stu.entity.Student;
import org.springframework.data.domain.Page;

import java.util.List;

public interface StudentService {

    Student save(Student student);
    Student update(Student student);
    void delete(Integer sid);
    Student findStuById(Integer id);
    List<Student> findStuByName(String name);

    /**
     * 分页查询所有数据
     * @param page 当前页
     * @param pageSize 每页记录数
     * @return
     */
    Page<Student> findAll(int page,int pageSize);

}

StudentServiceImpl

package com.kude.stu.kudestu.stu.service;

import com.kude.stu.kudestu.stu.dao.StudentDao;
import com.kude.stu.kudestu.stu.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;

    @Override
    public Student save(Student student) {
        return studentDao.save(student);
    }

    @Override
    public Student update(Student student) {
        return studentDao.save(student);
    }

    @Override
    public void delete(Integer sid) {
        studentDao.deleteById(sid);
    }

    @Override
    public Student findStuById(Integer sid) {
        return studentDao.findStudentById(sid);
    }

    @Override
    public List<Student> findStuByName(String name) {
        return studentDao.findStuByName(name);
    }

    @Override
    public Page<Student> findAll(int page,int pageSize) {
        Pageable pageable = PageRequest.of(page,pageSize);
        return studentDao.findAll(pageable);
    }
}

UserService

package com.kude.stu.kudestu.stu.service;

import com.kude.stu.kudestu.stu.entity.User;
import org.springframework.data.domain.Page;

import java.util.List;

public interface UserService {

    List<User> findAll();
    User findUserById(Integer id);
    User save(User user);
    User update(User user);
    void delete(int id);
    User login(String username,String password);
    Page<User> findByPage(int page, int limit);


}

UserServiceImpl

package com.kude.stu.kudestu.stu.service;

import com.kude.stu.kudestu.stu.dao.UserDao;
import com.kude.stu.kudestu.stu.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    @Override
    public User findUserById(Integer id) {
        return userDao.findUserById(id);
    }


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

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

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

    @Override
    public User login(String username, String password) {
        return userDao.login(username,password);
    }

    @Override
    public Page<User> findByPage(int page, int pageSize) {
        Pageable pageable = PageRequest.of(page,pageSize,new Sort(Sort.Direction.ASC,"id"));
        return userDao.findAll(pageable);
    }
}

KudestuApplication是自动生成的

package com.kude.stu.kudestu;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class KudestuApplication {

    public static void main(String[] args) {
        SpringApplication.run(KudestuApplication.class, args);
    }

}

在写entity的User和Student的时候,要与要连接的数据库对应数据类型和名字相同

运行

其他内容一并等修改此博客时好好完成

总结:

1.要用到JDK和对应版本的IDEA,Maven,需要在系统中配置

2.用到Navicat premium数据库,Hbuilder前端开发,http://www.bejson.com/在线测试,Postman测试

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Myeclipse为java工程导入外部jar包

    阮键
  • Java岗 面试考点精讲(基础篇01期)

    由于各种操作系统所支持的指令集不是完全一致,所以在操作系统之上加个虚拟机可以来提供统一接口,屏蔽系统之间的差异。

    阮键
  • MySQL性能优化总结

    1. InnoDB支持事务,MyISAM不支持,对于InnoDB每一条SQL语言都默认封装成事务,自动提交,这样会影响速度,所以最好把多条SQL语言放在begi...

    阮键
  • Spring框架(三) JDBCTemplate,声明式事务,自动装载(注解)

     JDBCTemplate 按照标准正常项目的结构 结构图: ? model层 dao层 实现  dao:(DateBase Access Object) 数据...

    二十三年蝉
  • spring中aop不生效的几种解决办法

    先看下这个问题的背景:假设有一个spring应用,开发人员希望自定义一个注解@Log,可以加到指定的方法上,实现自动记录日志(入参、出参、响应耗时这些)

    菩提树下的杨过
  • Springboot分别使用乐观锁和分布式锁(基于redisson)完成高并发防超卖

    在电商中经常会有防超卖的需求,本质上是对一条数据的多线程并发情况下的数据安全性进行控制。

    天涯泪小武
  • Spring boot with Scheduling

    本文节选自《Netkiller Java 手札》 http://www.netkiller.cn/java/spring/boot/index.html 11....

    netkiller old
  • Spring Boot读取配置文件与配置文件优先级

    1)通过注入ApplicationContext 或者 Environment对象来读取配置文件里的配置信息。

    良辰美景TT
  • springBoot 入门(六)—— 整合Spring框架开启自带的任务调度器执行任务(注解方式)

    MickyInvQ
  • spring boot 中使用 hibernate validate 校验

    spring boot 中使用 Hibernate validate 进行入参字段校验,一般用于web 接口入参校验,用起来非常方便。

    潇洒

扫码关注云+社区

领取腾讯云代金券