zoukankan      html  css  js  c++  java
  • 【Java】SpringBoot入门学习及基本使用

    SpringBoot入门及基本使用

    SpringBoot的介绍我就不多说了,核心的就是“约定大于配置”,接下来直接上干货吧!

    本文的实例: github-LPCloud,欢迎star&fork。

    SpringBoot基础配置

    web.xml保持原样即可:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
        <!--<welcome-file-list>-->
            <!--<welcome-file>index.html</welcome-file>-->
        <!--</welcome-file-list>-->
    </web-app>
    

    pom.xml配置如下:

    <?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>
    
        <groupId>groupId</groupId>
        <artifactId>863Project1</artifactId>
        <version>1.0.0</version>
        <!--以war包形式打包,很关键!-->
        <packaging>war</packaging>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.3.RELEASE</version>
        </parent>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.22</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
        </dependencies>
        <!--支持maven-->
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>
    

    启动入口 SpringBootApplication MainController.java

    package com.springboot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.builder.SpringApplicationBuilder;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.boot.web.support.SpringBootServletInitializer;
    import org.springframework.context.annotation.ComponentScan;
    
    /**
     * Author: puyangsky
     * Date: 17/5/7
     */
    
    @SpringBootApplication
    @EnableConfigurationProperties
    @ComponentScan(basePackages = {"com.springboot"})
    public class Application extends SpringBootServletInitializer {
    
        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(Application.class);
        }
    }
    

    Controller层跳转到页面

    修改appliction.properties,增加以下配置:

    # 配置jsp文件的位置,默认位置为:src/main/webapp
    spring.mvc.view.prefix=/views/
    # 配置jsp文件的后缀
    spring.mvc.view.suffix=.html
    

    因此在Controller层返回一个字符串如“index”可以映射到src/main/webapp/views/index.html,即跳转到该页面。

    静态资源访问

    两种方式可以实现静态资源访问,参考文章

    一、修改application.properties:
    加入以下配置:

    # 默认值为 /**
    spring.mvc.static-path-pattern=
    # 默认值为 classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ 
    spring.resources.static-locations=/static/,这里设置要指向的路径,多个使用英文逗号隔开,
    

    注意这里有个非常坑的地方,SpringBoot默认的classpath为/src/main/resources目录,也就是说在spring.resources.static-locations中配置的地址都是在这个文件夹下面,放在其他地方就无法访问了,直接报404。

    二、自定义配置,增加资源处理器:

    StaticConfig.java

    package com.springboot.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    /**
     * Author: puyangsky
     * Date: 17/5/8
     */
    @Configuration
    public class StaticConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
            super.addResourceHandlers(registry);
        }
    }
    

    中文乱码解决

    向application.properties中添加以下配置,参考文章

    spring.http.encoding.force=true
    spring.http.encoding.charset=UTF-8
    spring.http.encoding.enabled=true
    server.tomcat.uri-encoding=UTF-8
    

    @Autowired、@Resource无法自动注入Bean

    开始我也遇到了这个问题,搜索之后看到这篇文章,其中的原因是启动入口Application.java的位置太深入了,如果没有手动对扫描的包进行配置,如

    @ComponentScan(basePackages = {"com.springboot"})
    

    Spring就不会对相应的层级进行扫描,而只扫描Applciation.java当前及其中的类,所以一种范式就是把入口启动文件放在最外层,或者自己手动配置一下扫描的包。

    前后端交互例子

    实体类:User.java

    package com.springboot.model;
    
    /**
     * Author: puyangsky
     * Date: 17/5/9
     */
    public class User {
        private String email;
        private String password;
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    }
    

    Controller层代码,POST请求,接收json格式,使用@RequestBody将接收到数据转换为User对象,并用@ResponseBody注解将字符串直接返回到前端。

    @Controller
    @RequestMapping("/api")
    public class ApiController {
    
        @RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "application/json")
        @ResponseBody
        String login(HttpServletRequest request, @RequestBody User user) {
            if (user == null)
                return "fail";
            if (user.getEmail().equals("admin@osvt.net") && user.getPassword().equals("123456")){
                request.getSession().setAttribute("user", "admin");
                return "success";
            }else {
                return "fail";
            }
        }
    }
    

    前端页面使用ajax与后端API交互,html文件太长就不全贴上来了只放核心部分,文件地址

    <script>
        $("#submit").click(function () {
            var email = $("#inputEmail").val();
            var pwd = $("#inputPassword").val();
            var user = {"email": email, "password": pwd};
            $.ajax({
                url:"api/login",                 //指定POST的API地址
                type:"POST",
                contentType: 'application/json', //指定json格式
                async:false,                     //默认为异步,false指定为同步
                timeout:1000,
                data: JSON.stringify(user),      //json化对象
                success:function(result){
                    if (result == "success") {
                        $("#loginSuccess").html("登录成功").show().delay(2000).hide(0);
                        setTimeout(function () {
                            window.location.href = "/index";
                        }, 2000);
                    }else {
                        $("#loginSuccess").html("登录失败").show().delay(2000).hide(0);
                        setTimeout(function () {
                            window.location.href = "/login";
                        }, 2000);
                    }
                },
                error:function (xhr,status) {
                    alert("error: " + status);
                    window.location.href = "/login";
                }
            });
        });
    </script>
    

    注意:

    • 如果前后端数据格式没有对上,比如后端实体类参数和前端发送的json数据不匹配,就会报400Error。

    • 我在使用ajax过程中遇到一个诡异的错误:

        org.apache.catalina.connector.ClientAbortException: java.io.IOException: Broken pipe
      

      也没有搜到合适的方式解决,只是说原因是因为后端还在发送数据,前端就将这个连接关闭,比如说页面跳转,那么这个连接肯定就关闭了(http协议底层是TCP连接)。所以我猜测是ajax异步搞的鬼,将ajax的async调为false,即使用同步方式请求后端API,问题就消失了。

  • 相关阅读:
    [iOS 主要框架的总结]
    [无线传感器 网络中的节点定位技术]
    [JAVA 多种方式读取文件]
    [IOS swift对比oc]
    [IOS 静态库]
    [U3D 导出Xcode工程包,用Xcode给U3D脚本传递参数]
    [U3D 添加大地、天空,用第一视角看看自己做的世界]
    [U3D 画起重机,绑脚本和控制它运动的基本操作]
    Flutter 国际化适配
    Error:Unable to resolve dependency for ':app@releaseUnitTest/compileClasspath': Coul完美解决
  • 原文地址:https://www.cnblogs.com/puyangsky/p/6832017.html
Copyright © 2011-2022 走看看