Springboot學習(一)

發展史html

        從Spring3.x開始提供了Java配置方式,使用Java配置方式能夠更好的理解你配置的Bean,如今咱們就處於這個時代,而且Spring4.x和Spring boot都推薦使用java配置的方式。能夠徹底替代xml配置。java

Springboot介紹mysql

它是全新的框架,主要就是爲了簡化spring的搭建及應用程序的開發的。web

springboot特性:spring

springboot-HelloWorld實現sql

建立Maven項目(打包方式是war),項目結構:apache

pom.xml中的依賴:json

<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>com.test</groupId>
  <artifactId>springbootTest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build/>
  <parent>
      <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.6.RELEASE</version>
  </parent>  
  <dependencies>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>    
          <groupId>org.apache.maven.plugins</groupId>    
          <artifactId>maven-resources-plugin</artifactId>    
          <version>2.4.3</version>
      </dependency>
  </dependencies>
</project>tomcat

使用的JDK是JDK7。使用的是springboot內置的tomcatspringboot

Controller類:

package test1;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class Controller1 {
    @RequestMapping(value="/hello")
    @ResponseBody
    public String hello(){
        return "hello world!";
    }
}

主類:

package test1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class, args);
    }
}

注意:主類默認會掃描同包下或者子包下的類,因此創建的類放置的位置要注意。

解釋用到的註解:

(1)Controller中使用的註解比較熟悉

(2)主類中使用的註解:@SpringBootApplication 能夠啓動一個類

訪問url:http://localhost:8080/hello

 

注意:

springboot有本身使用的tomcat,端口是8080

springboot訪問Controller添加後綴

前面測試的例子中Controller中沒有添加後綴,訪問URL也沒有添加後綴。

如今添加訪問URL的後綴,作法:

(1)在src/main/java中添加application.properties文件,在文件中添加:

server.servlet-path=*.html

(2)Controller不變

@RequestMapping(value="/hello")
    @ResponseBody
    public String hello(){
        return "a";
    }

(3)訪問的URL:http://localhost:8080/hello.html中添加訪問的後綴

springboot添加攔截器

建立一個攔截器類,注意仍是以前說的,springboot默認掃描的是與主類同包下的類或者子包下的類,因此這個攔截器類要放在與主類同包下:

package test1;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration //申明這是一個配置
public class MySrpingMVCConfig extends WebMvcConfigurerAdapter{
    // 自定義攔截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor handlerInterceptor = new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                    throws Exception {
                System.out.println("自定義攔截器............");
                return true;
            }
            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                    ModelAndView modelAndView) throws Exception {
            }
            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                    Exception ex) throws Exception {
            }
        };
        registry.addInterceptor(handlerInterceptor).addPathPatterns("/**");
    }
}
springboot返回Json格式數據

返回json格式的數據有兩種方式:

(1)傳統springmvc的作法

package test1;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class Controller1 {
    @RequestMapping(value="/hello")
    @ResponseBody
    public String hello(){
        return "a";
    }
}

(2)springboot提供的返回Json格式的@RestController註解

package test1;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller1 {
    @RequestMapping(value="/hello")
    public String hello(){
        return "a";
    }
}

使用這個註解,這個Controller中的全部方法返回的都是json格式的數據。

springBoot項目屬性配置

springboot使用的配置文件是application.properties中的,這個文件放在src/main/resources下。他就是至關於咱們的web項目的web.xml文件,可是這裏的是更增強大的。

1.application.properties默認配置

訪問的是8080端口,路徑是/,沒有後綴

2.配置application.properties

(1)修改URL訪問的端口:添加server.port=8888

 訪問的URL:http://localhost:8888/hello

(2)修改URL訪問的後綴:添加server.servlet-path=*.html

Controller中的@RequestMapping(value="/hello")不變,訪問的URL:localhost:8888/hello.html

(3)添加訪問Controller的路徑:

第一種方式:直接在Controller中添加:@RequestMapping(value="/context/hello")

第二種方式:在application.properties中添加server.context-path=/context,Controller中仍是原來的@RequestMapping(value="/hello")

springboot自定義屬性

先看一下pom.xml中使用的springboot版本:

<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>com.test</groupId>
  <artifactId>springbootTest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build/>
  <parent>
      <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.6.RELEASE</version>
  </parent>
  <dependencies>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>    
          <groupId>org.apache.maven.plugins</groupId>    
          <artifactId>maven-resources-plugin</artifactId>    
          <version>2.4.3</version>
      </dependency>
  </dependencies>
</project>

我使用的是JDK7,使用JDK8會報錯。

當咱們想要使用key-value的時候,有兩種方式:

(1)能夠把屬性放在application.properties中

普通key-value的使用:

好比在application.properties中添加一個key-value:test=spring boot \u4F60\u5927\u7237(自動編碼的)(spring boot 你大爺)。注意這個文件application.properties的編碼不是utf-8,不要改變這個。

在Controller中的使用:

package test1;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller1 {
    
    @Value("${test}")
    private String test;
    
    @RequestMapping(value="/hello")
    public String hello(){
        return "a:"+test;
    }
}

帶有前綴的key-value的使用:

好比在application.properties中添加一個key-value:mysql.name=hello。

在Controller中的使用:

package test1;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller1 {
    
    @Value("${mysql.name}")
    private String test;
    
    @RequestMapping(value="/hello")
    public String hello(){
        return "a:"+test;
    }
}

(2)也能夠放在一個配置類(ConfigrationProperties屬性)中,實際上這個類被掃描以後,裏面的key-value仍是被放在application.properties中的

建立配置類(注意放在src/main/java下,由於springboot默認掃描的是與主類同包或子包下):

package test1;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix="mysql")//屬性前綴
public class MysqlProperties {
    private String name="myname";
    private String age="myage";
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
}
Controller使用:

package test1;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller1 {
    @Resource
    private MysqlProperties test;
    
    @RequestMapping(value="/hello")
    public String hello(){
        return "name:"+test.getName()+"</br>"+"age:"+test.getAge();
    }
}
application.properties配置文件中不用作什麼配置。

springboot的freemark支持(模板)

(1)pom.xml中添加freemarker支持

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

(2)Controller使用

package test1;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
@RestController
public class Controller1 {
    
    @RequestMapping(value="/hello")
    public ModelAndView hello(){
        ModelAndView mode = new ModelAndView();
        mode.addObject("message","spring boot 你大爺");
        mode.setViewName("a");//頁面的名字
        return mode;
    }
}
(3)application.properties文件

server.context-path=/context(不變,這裏是URL訪問Controller的路徑的配置,與freemarker無關)

(4)頁面

在src/main/resources下建立templates文件夾(springboot能夠識別這個名字的文件夾)

首先建立一個a.html,裏面添加的內容是:

而後將a.html文件更名爲a.ftl。

(5)訪問的URL:http://localhost:8080/context/hello

相關文章
相關標籤/搜索