SpringBoot系列(5)---SpringBoot-Web和SpringBoot基礎

筆者所參考的書籍是SpringBoot實戰,其理論性說得不多,內容上也不是非常詳細。但是說到的內容也足夠平時使用了,以下就是我根據SpringBoot實戰學到的一些東西,希望分享給大家,併成爲我以後回憶這門技術的筆記。

開始SpringBoot之前,我建議大家還是從Spring官網上按照自己的需要下載一個基礎包,https://start.spring.io 。在這個筆記當中只需要用到web 和 websocket。



導入到項目當中,然後我們就開始小試牛刀!


一、SpringBoot Web 小試牛刀

可以看到導入之後會有一個DemoApplication的類,這個類會發現有一個@SpringBootApplication。目前這個類就是我們在上幾遍說到的配置類,當然SpringBoot讓我這種懶人非常興奮,因爲他將我們會用到的東西都配置上去了。而且最重要的是他的自動配置的,會根據當前有什麼包和當前的環境去判斷應該配置什麼。目前我的maven有:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
顯然我是一個Web項目,所以Spring已經自動幫我們配置上了SpringMVC的支持,而且我們連最基本的ComponentScan都不用配,Spring都爲我們辦妥了。

然後我們想嘗試創建一個Controller然後我們使用@ResponseBody在頁面直接返回一個字符串。當然你可以直接使用@RestController 就不用寫@ResponseBody了(@RestController 等於 @Controller @ResponseBody的混合體,可以這樣理解)

@Controller
public class TestController {

    @RequestMapping("/")
    public @ResponseBody String index(){
        return "test";
    }

}

OK,到這裏Web容器呢···· 嗯SpringBoot 在 spring-boot-starter-web 做好了一個內嵌在SpringBoot上的Tomcat,當然也可以使用其他Jetty等等的其他Web容器,這個後面說。明顯看到我們的項目當中在resources目錄下會有一個application.properties配置文件。springBoot基本的配置都會寫到這裏,例如服務器的端口和contextpath等等都會在這裏去配置。

#Servlet容器配置
server.port=8080
server.context-path=/boot
server.session.timeout=10800
#server.error.path=/error
目前我配置了 8080端口、context-path爲/boot 、session超時時間爲3小時、錯誤頁面error(但是我沒有使用)

現在可以訪問了一下我們的第一個測試路徑了,http://localhost:8080/boot/


二、雜項配置

SpringBoot已經爲我們自動配置的大部分的日常配置,還有一些自定義操作還是需要我們親自動手。例如我們啓動SpringBoot時候的console顯現一個大大的Spring,又例如我們通過profile去控制當前運行環境等等。


1、配置SpringBoot的banner

配置SpringBoot的banner,我們在SpringBoot當中看的console輸出可以通過在resource目錄下創建banner.txt 在banner.txt中編寫自己的banner。

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.4.RELEASE)

當然如果我們不希望有BANNER的輸出,也可以通過在main方法中將banner禁用:

public static void main(String[] args) {
   SpringApplication application = new SpringApplication(DemoApplication.class);
   application.setBannerMode(Banner.Mode.OFF);
   application.run(args);
}

2、配置SpringBoot的Profile

Profile如果不熟悉的同學可以看看我之前的筆記:SpringBoot系列(1)---無配置文件配置基礎1 。

我們需要創建不同環境的application-{profile}.properties,然後配置不同profile環境的配置即可。例如我配置兩個環境,開發環境和生成環境,我就會創建application-dev.properties和application-prod.properties 兩個文件(在resources目錄下創建)。在不同的properties文件當中配置不同的server.port  開發環境是8080  生產環境是80。 

 application-prod.properties

server.port=80
server.context-path=/

application-dev.properties

server.port=8080
server.context-path=/boot

最後按照當前我們的實際環境在application.properties中配置profile的值:

spring.profiles.active=dev


3、用戶自定義配置

我們還可以在application.properties配置文件當中配置我們自定義的屬性,然後通過@value注入到我們的bean或者是controller當中。

myprperties.developer.name=tony
然後在我們的bean中配置:

@Controller
public class TestController {

    @Value("${myprperties.developer.name}")
    private String developerName;


4、日誌配置

SpringBoot 支持多種日誌框架,默認情況下SpringBoot使用LogBack作爲日誌框架,配置SpringBoot 日誌級別和日誌文件位置,可以通過application.properties進行如下配置:

#日誌配置
logging.file=/Users/yanzhichao/Desktop/log.log
logging.level.org.springframework.web=DEBUG


5、配置文件導入

SpringBoot是不提倡使用xml配置文件的,當然如果你必要去使用xml配置文件也是允許的通過@ImportResource導入所需的xml配置文件,但是筆者並沒有進行相關的測試,沒有別的,就因爲Spring不推薦我就不測這個功能了。有事件的同學可以測測然後在評論說下測試結果,看看能不能用。

@ImportResource({"classpath:application.xml"})
@SpringBootApplication
public class DemoApplication extends WebMvcConfigurerAdapter {

6、favicon配置

favicon就是瀏覽器標籤頁的icon

禁用favicon,在application.properties進行如下配置:

spring.mvc.favicon.enabled=false
替換自己的favicon只需要在resources目錄下、resources/static目錄下 、resources/public目錄下 隨便一個目錄添加自定義的favicon.ico即可


三、Thymeleaf 模板引擎

由於SpringBoot內嵌的Tomcat對支持JSP存在問題,在SpringBoot-web目前官方推薦使用Thymeleaf模板引擎。筆者也是對這個thymeleaf不是非常熟悉,也是僅僅會用而已。不過應該已經夠用了,講解Thymeleaf不是本文的重點我也是簡簡單單的說一說。

當然我們當需要使用Thymeleaf的時候第一反應是需要添加一個viewResolver。但是重磅消息是,Spring已經幫我們完成了這個任務。

也許你會問我們不需要去配置資源文件或者模板的路徑嗎?真的不用配置,Spring在默認情況下所有靜態資源一律映射到resources目錄下的static目錄。而模板一律映射到resources目錄下的templates目錄當中。所以實際上我們不需要配置任何的靜態資源路徑映射和thymeleaf的viewResolver。當然我們還是可以 配置一下(在application.properties上進行配置):

#Thymeleaf配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

在controller當中還是老規矩:

@RequestMapping("/userList.html")
public ModelAndView userList(){
    ModelAndView modelAndView = new ModelAndView("userList");
    modelAndView.addObject("users",getUserList());
    return modelAndView;
}

然後在templates目錄下創建userList.html的模板文件:

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Title</title>
</head>
<body>
    <table>
        <tr th:each="user_item : ${users}">
            <td th:text="${user_item.userId}"></td>
            <td th:text="${user_item.username}"></td>
            <td th:text="${user_item.userpwd}"></td>
        </tr>
    </table>
</body>
</html>


四、SpringMVC配置

SpringMVC在之前的筆記當中已經用了比較大的篇幅去介紹,事實上在SpringBoot當中也基本上一致。當然SpringBoot也是幫我們已經配置好常用的配置了。還記得我們以前說的WebMvcConfigurerAdapter嗎?不記得就回憶一下:SpringBoot系列(3)---無配置文件SpringMVC

同理在SpringBoot當中也是繼承WebMvcConfigurerAdapter然後對相應的方法進行重寫來對SpringMVC進行配置,我們可以直接在配置類當中繼承WebMvcConfigurerAdapter也可以另外創建一個配置類對SpringMVC進行配置,但是需要添加@Configuration的annotation。

@Configuration
public class MyWebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private HttpMessageConverters httpMessageConverters;

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        super.addViewControllers(registry);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(httpMessageConverters.getConverters());
    }
}
雖然我什麼都沒有配,就打個樣而已。但是需要注意的是,我們通過這種方式去配置是在SpringBoot自動配置的基礎上進行配置,如果我們想去除SpringBoot的默認配置需要添加@EnableWebMvc,但是一般情況下沒有這個必要。


五、靜態資源

剛剛在thymeleaf講解的時候已經說過,SpringBoot會自動映射靜態資源,以下就是會映射的目錄:

classpath:/META-INF/resources/index.html

classpath:/resources/index.html

classpath:/static/index.html

classpath:/public/index.html


六、Servlet\Filter\ServletListener配置

Servlet和Filter、ServletListener 就沒有什麼好說的,按護理畫瓢吧 兄弟們~~ ServletListener我就沒有測試了,自己動手豐衣足食!

//  @Bean
// public ServletListenerRegistrationBean listenerRegistrationBean(){
//    return new ServletListenerRegistrationBean();
// }

   @Bean
   public FilterRegistrationBean myFilter(){
      FilterRegistrationBean registrationBean = new FilterRegistrationBean(new MyFilter());
      registrationBean.addUrlPatterns("/index");
      return registrationBean;
   }

   @Bean
   public ServletRegistrationBean myServlet(){
      return new ServletRegistrationBean(new MyServlet(),"/myServlet");
   }


七、Tomcat和Servlet容器 配置

由於SpringBoot的Servlet容器是內嵌在Jar包當中的,所以我們可以通過兩種手段去進行配置,第一通過application.properties 第二通過實現EmbeddedServletContainerCustomizer接口。

1、通過application.properties:

#Tomcat 配置
server.tomcat.uri-encoding=utf-8
我看了一下沒有什麼好配置的SpringBoot默認的值已經配好了,我只是做個演示因爲SpringBoot默認的encoding也是配置爲UTF-8。

如果是通過intellij 進行開發的可以有提示,server.tomcat開頭就有提示了,按照自己需要進行相關的配置。


2、通過代碼配置

以下是通用Servlet容器的配置

@Component
public class CustomServletContainer implements EmbeddedServletContainerCustomizer {
    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.setPort(8888);
        container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,"/error_404.html"));
        container.setSessionTimeout(3, TimeUnit.HOURS);
    }
}

Tomcat特定配置需要創建特定containerFactory的bean,在配置類創建bean:

@Bean
public EmbeddedServletContainerFactory servletContainerFactory(){
   TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
   factory.setPort(8888);
   factory.setUriEncoding(Charset.forName("utf-8"));
   return factory;
}

一般情況我們通過application.properties 已經能夠滿足大部分的配置了,如果有特殊的配置可以通過代碼的方式進行定義。


八、啓用其他WEB容器替換TOMCAT 

這個也是沒有什麼難度改改maven就好

<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>

九、SSL配置

首先創建一個證書

keytool -genkey -alias TONY -keyalg RSA -keystore ./server.keystore  

【需要注意的是,一定要指定keyalg RSA 否則會出現ERR_SSL_VERSION_OR_CIPHER_MISMATCH 錯誤 導致無法訪問

application.properties配置如下:

#SSL
server.ssl.key-store=server.keystore
server.ssl.key-store-password=123456
server.ssl.key-store-type=JKS
server.ssl.key-alias=TONY
server.ssl.enabled=true
注意:證書文件一定要放在項目的根目錄下,即和你的pom.xml文件的同級目錄。

一般情況下用戶不會指定訪問https,所以做跳轉基本上是配置SSL的標配。現在就說說這個“標配”應該怎樣配。

@SpringBootApplication
public class DemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }

   @Bean
   public Connector httpConnector(){
      Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
      connector.setScheme("http");
      connector.setPort(8080);
      connector.setSecure(false);
      connector.setRedirectPort(8443);
      return connector;
   }

   @Bean
   public EmbeddedServletContainerFactory servletContainerFactory(){
      TomcatEmbeddedServletContainerFactory containerFactory = new TomcatEmbeddedServletContainerFactory(){

         @Override
         protected void postProcessContext(Context context) {
            super.postProcessContext(context);
            SecurityConstraint constraint = new SecurityConstraint();
            constraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/*");
            constraint.addCollection(collection);
            context.addConstraint(constraint);
         }
      };
      containerFactory.addAdditionalTomcatConnectors(httpConnector());
      return containerFactory;
   }

}

可以看到我們創建了一個connector 端口爲8080,並重定向到8443端口。這樣就能完成http跳轉到https,這樣對於用戶HTTPS來說是透明的,不需要用戶手動指定。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章