Day24、SpringBoot

SpringBoot

HelloWorld

第一个http接口

@RestControllerpublic class HelloController {
    @RequestMapping("/hello")    
    public String hello() {        
        return "Hello World";    
    }    
}
package com.example.springboot01helloword.controller;

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

@Controller
@RequestMapping("/hello")
public class HelloController {
    @GetMapping("/hello")
    @ResponseBody
    public String hello(){
        return "hello world!";
    }
}

yaml文件赋值

/*
@ConfigurationProperties作用:
将配置文件中配置的每一个属性的值,映射到这个组件中;告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定参数 prefix = “person” : 将配置文件中的person下面的所有属性一一对应*/
@Component //注册bean
@ConfigurationProperties(prefix = "person")
public class Person {    
    private String name;    
    private Integer age;    
    private Boolean happy;    
    private Date birth;    
    private Map<String,Object> maps;    
    private List<Object> lists;    
    private Dog dog;}
person:
  name: qinjiang
  age: 3
  happy: false
  birth: 2000/01/01
  maps: {k1: v1,k2: v2}
  lists:
   - code
   - girl
   - music
  dog:
    name: 旺财
    age: 1

配置文件占位符

person:    
    name: qinjiang${random.uuid} # 随机uuid    
    age: ${random.int}  # 随机int    
    happy: false    
    birth: 2000/01/01    
    maps: {k1: v1,k2: v2}    
    lists:      
        - code      
        - girl      
        - music    
	dog:      
		name: ${person.hello:other}_旺财      
		age: 1

Thymeleaf

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>hello</h1>
<div th:text="${msg}"></div>
</body>
</html>
package com.yrz.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {

    @RequestMapping("/test")
    public String test(Model model){
        model.addAttribute("msg","hello,springboot");
        return "test";
    }
}

Spring Boot

pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-java8time</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

application.yml

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
  web:
    resources:
      static-locations: classpath:/templates
mybatis:
  type-aliases-package: com.yrz.pojo
  mapper-locations: classpath:mybatis/mapper/*.xml

pojo.User

package com.yrz.pojo;

import lombok.*;

@Data
@NoArgsConstructor
@AllArgsConstructor

public class User {
    private Long id;
    private int age;
    private String username;
    private String password;

    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 int getAge() {
        return age;
    }

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

    public String getPassword() {
        return password;
    }

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

pojo.Result

package com.yrz.pojo;

public class Result<T> {

    private String msg;
    private boolean success;
    private T detail;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public T getDetail() {
        return detail;
    }

    public void setDetail(T detail) {
        this.detail = detail;
    }

    @Override
    public String toString() {
        return "Result{" +
                "msg='" + msg + '\'' +
                ", success=" + success +
                ", detail=" + detail +
                '}';
    }
}

mapper.UserMapper

package com.yrz.mapper;

import com.yrz.pojo.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserMapper {
    @Select("select * from t_user")
    List<User> findAll();
    @Select(value = "select * from t_user where username=#{username}")
    @Results({
            @Result(property = "username",column = "username"),
            @Result(property = "password",column = "password")
    })
    List<User> findByName(@Param("username") String username);
    @Insert("insert into t_user (id,username,age,password) values (#{id},#{username},#{age},#{password})")
    void addUser(User user);
    @Update("update t_user set username=#{username},age=#{age} where id = #{id}")
    void updateUser(User user);
    @Delete("delete from t_user where id = #{id}")
    void deleteUser(Long id);
    @Insert("insert into t_user values(#{id},#{username},#{password})")
    //加入该注解可以保存对象后,查看对象插入id
    @Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")
    void regist(User user);
    @Select("select id from t_user where username=#{username} and password=#{password}")
    Long login(User user);
}

service.UserService

package com.yrz.service;

import com.yrz.pojo.Result;
import com.yrz.pojo.User;

import java.util.List;

public interface UserService {

    boolean addUser(User user);

    boolean updateUser(User user);

    boolean deleteUser(Long id);

    List<User> findUserByName(String username);

    List<User> findAll();

    Result regist(User user);

    Result login(User user);
}

service.UserServiceImpl

package com.yrz.service;

import com.yrz.mapper.UserMapper;
import com.yrz.pojo.Result;
import com.yrz.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = RuntimeException.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean addUser(User user) {
        boolean result = false;
        try {
            userMapper.addUser(user);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public boolean updateUser(User user) {
        boolean result = false;
        try {
            userMapper.updateUser(user);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public boolean deleteUser(Long id) {
        boolean result = false;
        try {
            userMapper.deleteUser(id);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public List<User> findUserByName(String username) {
        return userMapper.findByName(username);
    }

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

    //    注册
    @Override
    public Result regist(User user) {
        Result result = new Result();
        result.setSuccess(false);
        result.setDetail(null);
        try {
            List<User> byName = userMapper.findByName(user.getUsername());
            if (byName != null) {
                result.setMsg("此用户已存在");
            } else {
                userMapper.regist(user);
                result.setMsg("注册成功");
                result.setSuccess(true);
                result.setDetail(user);
            }
        } catch (Exception e) {
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    //    登录
    @Override
    public Result login(User user) {
        Result result = new Result();
        result.setSuccess(false);
        result.setDetail(null);
        try {
            Long userId= userMapper.login(user);
            if(userId == null){
                result.setMsg("用户名或密码错误");
            }else{
                result.setMsg("登录成功");
                result.setSuccess(true);
                user.setId(userId);
                result.setDetail(user);
            }
        } catch (Exception e) {
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}

controller.UserController

package com.yrz.controller;

import com.yrz.pojo.Result;
import com.yrz.pojo.User;
import com.yrz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {
    @Autowired
   private UserService userService;

    @PostMapping("/regist")
    public Result regist(User user){
        return userService.regist(user);
    }

    @PostMapping("/login")
    public Result login(User user){
        return userService.login(user);
    }

    @GetMapping("/findall")
   public List<User> findAll(){
        return userService.findAll();
   }

   @PostMapping("/adduser")
    public boolean addUser(@RequestBody User user){
        return userService.addUser(user);
    }

    @PutMapping("/updateuser")
    public boolean updateUser(User user){
        return userService.updateUser(user);
    }

    @DeleteMapping("/deleteuser/{id}")
    public boolean deleteUser(@PathVariable("id") Long id){
        return userService.deleteUser(id);
    }

    @GetMapping("/findbyname/{username}")
    public List<User> findByName(@PathVariable("username")String username){
        return userService.findUserByName(username);
    }
}
上一篇:Photoshop CS3教程:飘逸的纱巾


下一篇:Photoshop处理照片为梦幻烟雨水乡