SpringBoot基本配置

简介:Spring Boot 是由Pivota团队提供的全新框架,目的就是简化我们的开发,我们以前的Spring xml配置+注解开发相当于动车,那么我们的SpringBoot就把我们拉到了高铁时代,我们可以使用大量的注解 + 少量的配置类来实现项目的开发。

SpringBoot的特点

  1. 开发非常快速

  2. 绝对没有代码生成,也无XML配置

  3. 快速创建独立运行的Spring项目于主流的框架集成

  4. 使用嵌入式Servlet容器,应用无需打成war包

  5. 由starters(场景启动器)自动依赖与版本控制

  6. 大量的自动配置,简化开发,也可以修改默认值

  7. 准生产环境的运行时应用监控

  8. 与云计算天然集成

  9. 与Spring Cloud(Alibaba)微服务框架天然继集成

创建一个简单的SpringBoot工程

1.创建一个maven项目

2.导入Spring boot父工程

 <!--继承SpringBoot工程的父工程: 父工程管理项目常见的依赖的版本-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/>
    </parent>

SpringBoot 提供了一个名为spring-boot-starter-parent父类工程,我们不需要担心版本问题了,但是我们需要别的版本或者别的依赖直接导入即可。

3. 导入spring boot 的 web启动器

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

为了让springBoot帮我们完成各种自动配置,我们必须引入SpringBoot提供的自动配置依赖,我们称之为启动器。因为我么你是web项目 所以我们引入web启动器,这时候我们会发现出现大量依赖,这就是自动引入的依赖。

 

4.启动类

我们的SpringBoot项目通过main函数启动即可,创建一个启动类:

public class App {
    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(App.class);
        springApplication.run(args);
    }
}

5.控制器

@RestController
public class HelloController {
​
    @GetMapping("hello")
    public String hello(){
        return "hello, spring boot!";
    }
}

启动测试

 

端口默认是 8080 直接访问即可。

SpringBoot 和 MyBatis-plus 整合

导入依赖

<!--导入MyBatis的场景启动器-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
​
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
​
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>
​
导入mybatis-plus的配置再application.propertis中
​
#mybatisplus 配置
#驼峰命名法
mybatis-plus.configuration.map-underscore-to-camel-case=true 
#日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#取别名
mybatis-plus.type-aliases-package=com.test.pojo

加入Mapper接口

public interface SingerMapper {
    List<Singer> findSingers();
}

依次创建service,serviceimpl,controller...当然也可使用mybatisplus自动生成代码。

使用swagger2构建restful apis

我们开发前后端分离的项目就需要多个人员开发,传统的做法是创建一份RESTFUL API文档来记录接口细节,但是接口众多不便于管理,修改接口的时候也要修改接口文档,所以我们的swagger就帮我们做了很多事情,使得开发更加简单。

下面我们尝试使用Spring MVC来实现一组对User对象操作的RESTful API,配合注释详细说明在Spring MVC中如何映射HTTP请求、如何传参、如何编写单元测试。

 

@Controller:修饰class,用来创建处理http请求对象
@RestController:是@Controller和@ResponseBody的整合,包含了JSON
@RequestMpping:配置url映射
​
加入swagger2依赖
        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.7.0.RELEASE</version>
        </dependency>

配置swagger2

swagger.base-package=com.bruceliu.controller

添加文档内容

在完成上述内容后就可以生成接口文档了,但是的文档主要针对请求本身,而描述主要来源于函数等命名产生,对客户并不友好,我们需要通过注解来增加说明。

@ApiImpLicitParms,@ApiImplicitParam

 @ApiOperation("通过id获取歌手信息")
    @ApiImplicitParam(name = "id",value = "歌手id",required = false,dataType = "Integer")
    @GetMapping("{id}")
    public ResultCommon getOne(@PathVariable("id") Integer id){
        return ResultCommon.success(ResultCode.SUCCESS,singerService.getById(id));
    }

在启动类或者控制层添加注解

@SpringBootApplication
@MapperScan("com.test.mapper")//扫描mapper层 底层使用到jdk动态代理实现生成对象
@EnableSwagger2Doc
public class App {
    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(App.class);
        springApplication.run(args);
    }
}

这样我们就成成功了,可以通过swagger进行调试。

 

整合Thymeleaf

导入依赖

<dependency> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

在配置文件中配置thymeleaf

# thymeleaf 
spring.thymeleaf.prefix=classpath:/templates/ 
spring.thymeleaf.check-template-location=true 
spring.thymeleaf.suffix=.html 
spring.thymeleaf.encoding=UTF-8 
spring.thymeleaf.content-type=text/html 
spring.thymeleaf.mode=HTML5 
spring.thymeleaf.cache=false

新建编辑控制层代码controller,在request添加name属性,返回前端我们就可以通过thymeleaf取值显示

@Controller 
public class HelloController {
    
    @RequestMapping("/hello") 
    public String hello(HttpServletRequest request, @RequestParam(value = "name", defaultValue = "springboot-thymeleaf") String name) { 
        request.setAttribute("name", name); 
        return "hello"; 
    } 
}

在页面中取出后台存的值

 <p th:text="'hello, ' + ${name} + '!'" /> 

实现前后端分离跨站请求

配置过滤器

//配置过滤器,解决跨域问题
@Configuration
public class CorsConfig {

    /**
     * 跨域的配置信息
     * @return
     */
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); //允许任何域名使用
        corsConfiguration.addAllowedHeader("*"); //允许任何头
        corsConfiguration.addAllowedMethod("*"); //允许任何方法(post、get等)
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        //向Spring容器中注入一个过滤器
        return new CorsFilter(source);
    }
}

前端取值和跨域访问,异步

在前端页面中取值
 $(function () {
            $.getJSON("http://localhost:8080/singer/list",function (result) {
                if (result.code==200){
                    for(var i=0;i<result.data.length;i++){
                        var singer=result.data[i];
                        $("#bb").append(" <tr id='"+singer.id+"'>\n" +
                            "          <td>"+singer.id+"</td>\n" +
                            "          <td>"+singer.name+"</td>\n" +
                            "          <td>"+singer.age+"</td>\n" +
                            "          <td>"+singer.birthday+"</td>\n" +
                            "          <td>"+singer.works+"</td>\n" +
                            "          <td>"+singer.sex+"</td>\n" +
                            "          <td>"+singer.idcard+"</td>\n" +
                            "          <td> <a href='update.html?id="+singer.id+"'>更新</a>\n" +
                            "               <a href='javascript:deleteSinger("+singer.id+");'>删除</a></td>\n" +
                            "      </tr>");
                    }
                }else {
                    alert("请求失败");
                }
            })
        });

delete请求带id跳后台

 function deleteSinger(id) {
            if (confirm("确定删除吗")){
            $.post("http://localhost:8080/singer/"+ id +"?_method=delete",function (result) {
                    if (result.code==200){
                        $("#"+id).fadeOut(1000,function (){
                            alert("删除成功");
                        })
                    }else {
                        alert("删除失败");
                    }
                });
            }
        };   

delete请求

  function addSinger() {
            let date = $("#addForm").serialize();
            $.post("http://localhost:8080/singer/add",date,function (result) {
                if (result.code==200){
                    alert("新增成功")
                    location.href="singers.html";
                }else {
                    alert("新增失败")
                }
            })

        }

update数据回显,先跳后台根据藏得id查找对象进行回显

  $(function () {
            var id = window.location.href.split("=")[1];
            $.getJSON("http://localhost:8080/singer/"+id,function (result) {
                if (result.code==200){
                    var singer = result.data;
                    $("[name='id']").val(singer.id); //更新藏值
                    $("[name='name']").val(singer.name);
                    $("[name='age']").val(singer.age);
                    $("[name='birthday']").val(singer.birthday);
                    $("[name='works']").val(singer.works);
                    $("[name='idcard']").val(singer.idcard);
                    if(singer.sex=='女'){
                        $("[name='sex']:eq(1)").prop("checked",true);
                    }
                }else {
                    alert("服务器异常");
                }
            })
        });

put请求跳后台进行修改

        function updateSinger() {
            var date = $("#updateForm").serialize()+"&_method=put";
            $.post("http://localhost:8080/singer/update",date,function (result) {
                if (result.code==200){
                    alert("修改成功");
                    location.href="singers.html";
                }else {
                    alert("修改失败");
                }
            },"json");
        };
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值