SpringBoot

案例一

 1、导入依赖

</properties>
    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.1.RELEASE</version>

</parent>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
<dependency> <!-- spring-boot-starter-web是为我们提供了包括mvc,aop等需要的一些jar --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- 因为我们已经配置了 parent 中的version 所以这里不需要指定version了 --> </dependency>

 

  2、创建FirstController类

@RestController
public class FirstController {


    @RequestMapping("/firstController")
    public String firstController(){
        System.out.println("第一个请求");
        return "Hello SpringBoot";
    }
}

3创建StartSpringBoot 测试类

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

控制台输出

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

2019-12-10 16:19:28.638  INFO 12836 --- [           main] com.wdksft.StartSpringBoot               : Starting StartSpringBoot on LAPTOP-98IAV276 with PID 12836 (E:\San\SpringBoot\springboot(1)\springboot\target\classes started by s in E:\San\SpringBoot\springboot(1)\springboot)
2019-12-10 16:19:28.647  INFO 12836 --- [           main] com.wdksft.StartSpringBoot               : No active profile set, falling back to default profiles: default
2019-12-10 16:19:28.904  INFO 12836 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1c1bced: startup date [Tue Dec 10 16:19:28 CST 2019]; root of context hierarchy
2019-12-10 16:19:32.255  INFO 12836 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2019-12-10 16:19:32.278  INFO 12836 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2019-12-10 16:19:32.280  INFO 12836 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.5
2019-12-10 16:19:32.574  INFO 12836 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-12-10 16:19:32.574  INFO 12836 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3683 ms
2019-12-10 16:19:33.083  INFO 12836 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2019-12-10 16:19:33.095  INFO 12836 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-12-10 16:19:33.096  INFO 12836 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-12-10 16:19:33.097  INFO 12836 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-12-10 16:19:33.098  INFO 12836 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2019-12-10 16:19:33.992  INFO 12836 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1c1bced: startup date [Tue Dec 10 16:19:28 CST 2019]; root of context hierarchy
2019-12-10 16:19:34.159  INFO 12836 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/firstController]}" onto public java.lang.String com.wdksft.cotroller.FirstController.firstController()
2019-12-10 16:19:34.171  INFO 12836 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2019-12-10 16:19:34.172  INFO 12836 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2019-12-10 16:19:34.250  INFO 12836 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-12-10 16:19:34.250  INFO 12836 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-12-10 16:19:34.300  INFO 12836 --- [           main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in exceptionHan
2019-12-10 16:19:34.372  INFO 12836 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-12-10 16:19:34.794  INFO 12836 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2019-12-10 16:19:34.990  INFO 12836 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2019-12-10 16:19:35.002  INFO 12836 --- [           main] com.wdksft.StartSpringBoot               : Started StartSpringBoot in 7.743 seconds (JVM running for 11.854)

网页访问

 

 

二、SpringBoot静态资源访问

  1、在resources文件下创建static包,再static下创建img包

  

 

  

     三、SpringBoot解决异常问题

  1、在Controller类中定义一个异常

    

@RestController
public class FirstController {


    @RequestMapping("/firstController")
    public String firstController(){
        int result=5/0;
        System.out.println("第一个请求");
        return "Hello SpringBoot";
    }
}

2. 定义异常类

@ControllerAdvice
public class ExceptionHan {
    @org.springframework.web.bind.annotation.ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Map<String,Object> exceHandler(){
        Map<String,Object> map=new HashMap<>();
        map.put("error","500");
        map.put("msg","异常");
        return map;

    }

  3、结果如下

    

四、SpringBoot使用freemarker

  1、导入依赖freemarker

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

  2、配置application.propertiesleuk文件

## Freemarker 配置
spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.request-context-attribute=request
spring.freemarker.prefix=/
spring.freemarker.suffix=.ftl

  3、在resources包下创建templates包并创建holle.ftl模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SpringBoot整合FreeMarker</title>
</head>
<body>
    欢迎:
  ` ${name}

    <#list stulist as stu>
        ${stu.stu_name}
    </#list>

    <#if 1==1>
        等等等等!!!
    </#if>

    <#list userList as user>
        ${user}
    </#list>
</body>
</html>

  4、创建StartSpringBoot启动类

package com.freemarker;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

  5、创建Controller类freemarkerController类

package com.freemarker.Controller;

import com.freemarker.entity.student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/free")
public class freemarkerController {
    @RequestMapping("/freeFirst")
    public String freeFirst(ModelMap map){
        map.put("name","张三");
        return "hello"; //找templates/name.ftl
    }

    @RequestMapping("/freeSecond")
    public String freeSecond(ModelMap map){
        List<String> list=new ArrayList<>();
        list.add("张三");
        list.add("李四");
        list.add("王五");
        map.put("userList",list);
        return "hello";
    }

    @RequestMapping("/freeThread")
    public String freeThread(ModelMap map){
        List<student> list=new ArrayList<>();
        student stu=new student();
        stu.setStu_id(1);
        stu.setStu_name("小王");
        list.add(stu);
        map.put("stulist",list);
        return "hello";
    }
}

  6、页面访问实现效果如下

    

posted @ 2019-12-10 16:46  听风忆雪  阅读(174)  评论(0编辑  收藏  举报