• 简单的springboot应用,日志,静态资源配置


    1.新建Maven项目

    2.pom文件

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <project xmlns="http://maven.apache.org/POM/4.0.0"
     3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     5     <modelVersion>4.0.0</modelVersion>
     6 
     7     <groupId>com.springboot</groupId>
     8     <artifactId>springboot</artifactId>
     9     <version>1.0-SNAPSHOT</version>
    10 
    11     <!-- Spring boot 父引用-->
    12     <parent>
    13         <groupId>org.springframework.boot</groupId>
    14         <artifactId>spring-boot-starter-parent</artifactId>
    15         <version>1.4.1.RELEASE</version>
    16     </parent>
    17     <dependencies>
    18         <!-- Spring boot 核心web-->
    19         <dependency>
    20             <groupId>org.springframework.boot</groupId>
    21             <artifactId>spring-boot-starter-web</artifactId>
    22         </dependency>
    23         <dependency>
    24             <groupId>org.projectlombok</groupId>
    25             <artifactId>lombok</artifactId>
    26             <version>1.16.18</version>
    27         </dependency>
    28         <dependency>
    29             <groupId>com.alibaba</groupId>
    30             <artifactId>fastjson</artifactId>
    31             <version>1.2.28</version>
    32         </dependency>
    33         <dependency>
    34             <groupId>org.springframework.boot</groupId>
    35             <artifactId>spring-boot-starter-logging</artifactId>
    36         </dependency>
    37     </dependencies>
    38 
    39     <build>
    40         <plugins>
    41             <plugin>
    42                 <groupId>org.springframework.boot</groupId>
    43                 <artifactId>spring-boot-maven-plugin</artifactId>
    44                 <executions>
    45                     <execution>
    46                         <goals>
    47                             <goal>repackage</goal>
    48                         </goals>
    49                     </execution>
    50                 </executions>
    51                 <configuration>
    52                     <executable>true</executable>
    53                 </configuration>
    54             </plugin>
    55         </plugins>
    56     </build>
    57     
    58 </project>

     3.项目的结构

    4.SpringbootApplication.java

     1 package com.springboot;
     2 
     3 import org.springframework.boot.SpringApplication;
     4 import org.springframework.boot.autoconfigure.SpringBootApplication;
     5 
     6 /**
     7  * @author luoxianwei
     8  * @date 2018/4/24
     9  */
    10 @SpringBootApplication
    11 public class SpringbootApplication {
    12     public static void main(String[] args) {
    13         SpringApplication.run(SpringbootApplication.class,args);
    14     }
    15 }

     5.application.properties

    1 server.port=8081
    2 server.servlet-path=/
    3 spring.resources.static-locations=classpath:/static/,classpath:/templates/
    4 spring.mvc.view.suffix=.html
    5 #配置日志
    6 #配置日志在resource下的logback.xml文件中
    7 #在控制台输出彩色日志
    8 spring.output.ansi.enabled=always

    6.日志文件配置logback.xml

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!--
     3     Copyright 2010-2011 The myBatis Team
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7         http://www.apache.org/licenses/LICENSE-2.0
     8     Unless required by applicable law or agreed to in writing, software
     9     distributed under the License is distributed on an "AS IS" BASIS,
    10     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11     See the License for the specific language governing permissions and
    12     limitations under the License.
    13 -->
    14 <configuration>
    15     <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
    16     <property name="LOG_HOME" value="E:/workspace/selfPractices/springboot/log" />
    17 
    18 
    19     <!-- 彩色日志 -->
    20     <!-- 彩色日志依赖的渲染类 -->
    21     <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
    22     <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
    23     <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
    24     <!-- 彩色日志格式 -->
    25     <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}" />
    26     <!-- Console 输出设置 -->
    27     <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    28         <encoder>
    29             <pattern>${CONSOLE_LOG_PATTERN}</pattern>
    30             <charset>utf8</charset>
    31         </encoder>
    32     </appender>
    33 
    34     <!-- 不用彩色控制台输出 -->
    35     <!--<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">-->
    36     <!--<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">-->
    37     <!--&lt;!&ndash;格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符&ndash;&gt;-->
    38     <!--<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>-->
    39     <!--</encoder>-->
    40     <!--</appender>-->
    41     <!-- 按照每天生成日志文件 -->
    42     <appender name="DAYINFO"  class="ch.qos.logback.core.rolling.RollingFileAppender">
    43         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
    44             <!--日志文件输出的文件名-->
    45             <FileNamePattern>${LOG_HOME}/TestSpringBoot_info.log.%d{yyyy-MM-dd}.log</FileNamePattern>
    46             <!--日志文件保留天数-->
    47             <MaxHistory>30</MaxHistory>
    48         </rollingPolicy>
    49         <filter class="ch.qos.logback.classic.filter.LevelFilter">
    50             <level>info</level>
    51             <onMatch>ACCEPT</onMatch>
    52             <onMismatch>DENY</onMismatch>
    53         </filter>
    54         <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
    55             <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
    56             <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
    57         </encoder>
    58         <!--日志文件最大的大小-->
    59         <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
    60             <MaxFileSize>10MB</MaxFileSize>
    61         </triggeringPolicy>
    62     </appender>
    63 
    64     <appender name="DAYERROR"  class="ch.qos.logback.core.rolling.RollingFileAppender">
    65         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
    66             <!--日志文件输出的文件名-->
    67             <FileNamePattern>${LOG_HOME}/TestSpringBoot_error.log.%d{yyyy-MM-dd}.log</FileNamePattern>
    68             <!--日志文件保留天数-->
    69             <MaxHistory>30</MaxHistory>
    70         </rollingPolicy>
    71         <filter class="ch.qos.logback.classic.filter.LevelFilter">
    72             <level>error</level>
    73             <onMatch>ACCEPT</onMatch>
    74             <onMismatch>DENY</onMismatch>
    75         </filter>
    76         <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
    77             <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
    78             <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
    79         </encoder>
    80         <!--日志文件最大的大小-->
    81         <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
    82             <MaxFileSize>10MB</MaxFileSize>
    83         </triggeringPolicy>
    84     </appender>
    85 
    86     <!-- 日志输出级别 -->
    87 
    88     <root level="INFO">
    89         <appender-ref ref="STDOUT" />
    90         <appender-ref ref="DAYERROR" />
    91         <appender-ref ref="DAYINFO" />
    92     </root>
    93 </configuration>

    7.controller

    TestController

     1 package com.springboot.controller;
     2 
     3 import org.springframework.stereotype.Controller;
     4 import org.springframework.web.bind.annotation.RequestMapping;
     5 import org.springframework.web.bind.annotation.ResponseBody;
     6 
     7 import java.util.Map;
     8 
     9 /**
    10  * @author luoxianwei
    11  * @date 2018/4/24
    12  */
    13 @Controller
    14 public class TestController {
    15 
    16     /**
    17      * 返回json字符串
    18      * @return
    19      */
    20     @RequestMapping("/")
    21     @ResponseBody
    22     public String hello(){
    23         return "Hello World!";
    24     }
    25 
    26     /**
    27      * https://blog.csdn.net/wangb_java/article/details/71775637
    28      * 静态页面
    29      * spring boot项目只有src目录,没有webapp目录,会将静态访问(html/图片等)映射到其自动配置的静态目录,如下
    30      * /static
    31      * /public
    32      * /resources
    33      * /META-INF/resources
    34      *
    35      *动态页面
    36      * 动态页面需要先请求服务器,访问后台应用程序,然后再转向到页面,比如访问JSP。spring boot建议不要使用JSP,
    37      * 默认使用Thymeleaf来做动态页面。
    38      *  在pom.xml  中添加Thymeleaf组件
    39      * templates目录为spring boot默认配置的动态页面路径。
    40      *
    41      */
    42     /**
    43      * 这是请求static下的index页面
    44      * 注意:@RequestMapping("/index")中的url和return的值不能一样会报如下错误
    45      * javax.servlet.ServletException: Circular view path [/index.html]: would dispatch back to the current handler URL [/index.html] again.
    46      * Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
    47      * 参考网址:https://blog.csdn.net/huijianpang/article/details/61193445
    48      * @return
    49      */
    50     @RequestMapping("/index")
    51     public String index(){
    52         return "/index.html";
    53     }
    54 
    55 }

    TestBootController

     1 package com.springboot.controller;
     2 
     3 import com.alibaba.fastjson.JSON;
     4 import com.springboot.model.User;
     5 import com.springboot.service.TestInterFace;
     6 import lombok.extern.slf4j.Slf4j;
     7 import org.springframework.beans.factory.annotation.Autowired;
     8 import org.springframework.stereotype.Controller;
     9 import org.springframework.web.bind.annotation.RequestMapping;
    10 import org.springframework.web.bind.annotation.ResponseBody;
    11 
    12 
    13 @Slf4j
    14 @Controller
    15 public class TestBootController {
    16 
    17     @Autowired
    18     private TestInterFace testInterFace;
    19 
    20     @RequestMapping("/num")
    21     @ResponseBody
    22     public int home() {
    23         int i = testInterFace.testInterFace();
    24         log.info("获取数据 {}",JSON.toJSONString(i));
    25         return i;
    26     }
    27 
    28     @RequestMapping("/get")
    29     @ResponseBody
    30     public User getUser(String id) {
    31         long currentTimeMillis = System.currentTimeMillis();
    32         log.info("### 获取用户信息开始 ###");
    33         log.info("请求参数id : {}",id );
    34         User user = testInterFace.testUser();
    35         log.info("### 获取用户信息结束,总耗时 {}ms ###",System.currentTimeMillis()-currentTimeMillis);
    36         return testInterFace.testUser();
    37     }
    38 
    39 
    40 }
  • 相关阅读:
    提示“此Flash Player与您的地区不相容,请重新安装Flash”的解决办法
    python中安装并使用redis
    linux安装flash player来播放视频
    安装redis
    centos6.5安装无线网卡驱动并配置wifi
    centos安装java的jdk
    001-python简介
    源码
    进程间通信之综述
    图的概念
  • 原文地址:https://www.cnblogs.com/jcjssl/p/9380201.html
Copyright © 2020-2023  润新知