您现在的位置是:首页 >其他 >springboot网站首页其他

springboot

coleak 2024-06-17 10:47:00
简介springboot

优点

1.可以快速独立的创建Spring及主流框架集成的项目。
2.使用了嵌入式的Servlet容器,无需生成WAR包
3.我们在使用SpringBoot进行开发时可以使用Starts启动依赖,而SpringBoot会自动地把所需要的其他相关技术jar包导入.
4.大量的自动配置,极大地简化了我们的开发。
5.无需XML文件的大量编写,也不会生成代码,底层是利用SpringBoot写好的API来调用实现,开箱即用
6.SpringBoot也有运维监控项目的功能
7.SpringBoot与云计算的集成

框架整合及配置

版本

java8+Maven+springboot-2.7.11+lombok

路由

package com.example.entity;

import lombok.Data;

@Data
public class Student {
        int sid;
        String name;
        String sex;
    }

package com.example.controller;

import com.example.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MainController {

    @RequestMapping("/index")
    @ResponseBody
    public String index()
    {
        return "coleak";
    }
    @RequestMapping("/student")
    @ResponseBody
    public Student student(){
        Student student = new Student();
        student.setName("小明");
        student.setSex("男");
        student.setSid(10);
        return student;
    }
}
return object时返回json数据
{"sid":10,"name":"小明","sex":"男"}

application.properties

server.port=80
coleak.age=19
#spring.main.banner-mode=off
#spring.banner.image.location=col.jpg
logging.level.root=error
    @Value("${coleak.age}")
    int age;

    @RequestMapping("/index")
    @ResponseBody
    public String index()
    {
        return "coleak"+"年龄是:"+age;
    }

在这里插入图片描述

安全配置

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
spring:
  security:
    user:
      name: coleak
      password: passwd
      roles:
        - user
        - admin

Using generated security password: ccf78226-a571-4119-aa86-24331d99a2d6

登录后出现JSESSIONID

application.yml格式

server:
  port: 80
coleak:
  age: 19

权限配置

package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().hasRole("user")
                .and()
                .formLogin();
    }
}

Mybatis框架

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.23</version>
</dependency>
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .userDetailsService(service)
            .passwordEncoder(new BCryptPasswordEncoder());
}

@Service
public class UserAuthService implements UserDetailsService {

    @Resource
    MainMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserData data = mapper.findUserByName(username);
        if(data == null) throw new UsernameNotFoundException("用户 "+username+" 登录失败,用户名不存在!");
        return User
                .withUsername(data.getUsername())
                .password(data.getPassword())
                .roles(data.getRole())
                .build();
    }
}

@Mapper
public interface MainMapper {
    @Select("select * from users where username = #{username}")
    UserData findUserByName(String username);
}

操作简化

- parent
- starter
- 引导类
- 内嵌tomcat
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>
</dependencies>

REST开发

路径+请求方式来访问资源称为Restful

package com.example.bt3.UserController;

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

import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@RestController
public class Controller {

    @GetMapping(value = "/student/{id}/{age}")
    public Object student(@PathVariable("id") Integer id,
                          @PathVariable("age") Integer age) {
        Map<String,Object> map=new HashMap<>();
        map.put("id",id);
        map.put("age",age);
        return map;
    }

    @DeleteMapping(value = "/student/detail/{id}/{status}")
    public Object student2(@PathVariable("id") Integer id,
                           @PathVariable("status") Integer status) {
        Map<String,Object> map=new HashMap<>();
        map.put("id",id);
        map.put("status",status);
        return map;
    }

    @DeleteMapping(value = "/student/{id}/detail/{phone}")
    public Object student3(@PathVariable("id") Integer id,
                           @PathVariable("phone") Integer phone) {
        Map<String,Object> map=new HashMap<>();
        map.put("id",id);
        map.put("phone",phone);
        return map;
    }

    @PostMapping(value = "/student/{id}")
    public String addStudent(@PathVariable("id") Integer id) {
        return "add student ID: " + id;
    }

    @PutMapping(value = "/student/{id}")
    public String updateStudent(@PathVariable("id") Integer id) {
        return "update student ID: " + id;
    }
}

//或者下面的形式
@RestController
public class Controller {

    @RequestMapping(value = "/student/{id}/{age}",method=RequestMethod.GET)
    @ResponseBody
    public Object student(@PathVariable Integer id,
                          @PathVariable Integer age) {
        Map<String,Object> map=new HashMap<>();
        map.put("id",id);
        map.put("age",age);
        return map;
    }
package com.itheima.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//Rest模式
@RestController
//@RestController=@ResponseBody+@Controller
@RequestMapping("/books")
public class BookController {
    @GetMapping
//@GetMapping=@RequestMapping(method=RequestMethod.GET)
    public String getById(){
        System.out.println("springboot is running...");
        return "springboot is running...";
    }
}

问题解决

1.Maven加载pom的lombok一直出问题,且下载失败,需要设置Http Proxy挂代理解决
在这里插入图片描述

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。