SpringBoot 2.0入门(1)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012124438/article/details/83001195

1.在eclipse中创建一个Maven工程

在这里插入图片描述

创建名为”helloworld” 类型为Jar工程项目。

2.pom文件引入依赖

在pom中加入如下代码:

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies> 

1)spring-boot-starter-parent作用
在pom.xml中引入spring-boot-start-parent,spring官方的解释是stater poms,它可以提供dependency management,也就是说依赖管理,引入以后在申明其它dependency的时候就不需要version了,后面可以看到。

2)spring-boot-starter-web作用
springweb 核心组件

3)spring-boot-maven-plugin作用
如果我们要直接Main启动spring,那么以下plugin必须要添加,否则是无法启动的。如果使用maven 的spring-boot:run的话是不需要此配置的。(我在测试的时候,如果不配置下面的plugin也是直接在Main中运行的。)

3.编写HelloWorld服务

创建package命名为com.itma.controller(根据实际情况修改)
创建HelloController类,内容如下

@RestController
@EnableAutoConfiguration
public class HelloController {
	@RequestMapping("/hello")
	public String index() {
		return "Hello World";
	}	
	public static void main(String[] args) {
		SpringApplication.run(HelloController.class, args);
	}

	
}

运行程序Run as java application,Springboot默认端口号为8080,我们在浏览器访问http://192.168.3.127:8080/hello (以我的电脑的IP地址为例)

在这里插入图片描述
可以看到就显示出了我们在方法中写的内容。

上面的例子中,我们涉及到了以下几个知识点
1)@RestController
加上RestController 表示修饰该Controller所有的方法返回JSON格式,直接可以编写
Restful接口

2)@EnableAutoConfiguration
注解:作用在于让 Spring Boot 根据应用所声明的依赖来对 Spring 框架进行自动配置
这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring。由于spring-boot-starter-web添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用并相应地对Spring进行设置。

3)SpringApplication.run(HelloController.class, args);
将一个类标识为启动类

4.SpringBoot的几种启动方式

4.1使用SpringApplication.run将一个类标识为启动类
再次贴出上面例子中的代码

@RestController
@EnableAutoConfiguration
public class HelloController {
	@RequestMapping("/hello")
	public String index() {
		return "Hello World";
	}	
public static void main(String[] args) {
		SpringApplication.run(HelloController.class, args);
	}
}

4.2 声明application,并通过@ComponentScan注解声明控制器扫包范围
我们在com.itma包路径下创建一个App.java类

@ComponentScan(basePackages = "com.itma.controller")
@EnableAutoConfiguration
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

}

@ComponentScan注解用于声明控制器扫包范围

在com.itma.controller下新建一个HelloController2

@RestController
@EnableAutoConfiguration
public class HelloController2 {
	@RequestMapping("/hello2")
	public String index() {
		return "Hello World 2222";
	}	
	
	
}

运行项目,访问 http://192.168.3.127:8080/hello2,会打印Hello World 2222

4.3 声明@SpringBootApplication注解
@SpringBootApplication 被 @Configuration、@EnableAutoConfiguration、@ComponentScan 注解所修饰,换言之 Springboot 提供了统一的注解来替代以上三个注解
扫包范围:在启动类上加上@SpringBootApplication注解,当前包下或者子包下所有的类都可以扫到。

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

}

5.静态资源访问

在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。
默认配置
Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:
/static
/public
/resources
/META-INF/resources
举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动程序后,尝试访问http://域名/Test.jpg。如能显示图片,配置成功。
在这里插入图片描述

6.渲染Web页面

在之前的示例中,我们都是通过@RestController来处理请求,所以返回的内容为json对象。那么如果需要渲染html页面的时候,要如何实现呢?

6.1模板引擎
在动态HTML实现上Spring Boot依然可以完美胜任,并且提供了多种模板引擎的默认配置支持,所以在推荐的模板引擎下,我们可以很快的上手开发动态网站。
Spring Boot提供了默认配置的模板引擎主要有以下几种:

•	Thymeleaf
•	FreeMarker
•	Velocity
•	Groovy
•	Mustache

Spring Boot建议使用这些模板引擎,避免使用JSP,若一定要使用JSP将无法实现Spring Boot的多种特性,具体可见后文:支持JSP的配置
当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。

7.使用Freemarker模板引擎渲染web视图

7.1pom文件引入

<!-- 引入freeMarker的依赖包. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

7.2后台代码
在src/main/resources/创建一个templates文件夹,后缀为*.ftl

@RequestMapping("/index")
	public String index(Map<String, Object> map) {
	    map.put("name","美丽的天使...");
		return "index";
	}

7.3前台代码

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
	  ${name}
</body> 
</html>

7.4 Freemarker其他用法

后台代码

@RequestMapping("/freemarkerIndex")
	public String index(Map<String, Object> result) {
		result.put("name", "yushengjun");
		result.put("sex", "0");
		List<String> listResult = new ArrayList<String>();
		listResult.add("zhangsan");
		listResult.add("lisi");
		listResult.add("itmayiedu");
		result.put("listResult", listResult);
		return "index";
	}

前台代码

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>首页</title>
</head>
<body>
	  ${name}
<#if sex=="1">
            男
      <#elseif sex=="2">
            女
     <#else>
        其他      
	  
	  </#if>	  
	 <#list userlist as user>
	   ${user}
	 </#list>
</body> 
</html>

7.5 Freemarker配置
新建application.properties文件

########################################################
###FREEMARKER (FreeMarkerAutoConfiguration)
########################################################
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.prefix=
#spring.freemarker.request-context-attribute=
#spring.freemarker.settings.*=
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/
#comma-separated list
#spring.freemarker.view-names= # whitelist of view names that can be resolved

8.使用JSP渲染Web视图
8.1 pom文件引入以下依赖

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
	</parent>
	<dependencies>
		<!-- SpringBoot web 核心组件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
		</dependency>
	<!-- SpringBoot 外部tomcat支持 -->	
	<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
		</dependency>
	</dependencies>

8.2 在application.properties创建以下配置

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

后台代码

@Controller
public class IndexController {
	@RequestMapping("/index")
	public String index() {
		return "index";
	}
}

注意:创建SpringBoot整合JSP,一定要为war类型,否则会找不到页面.
不要把JSP页面存放在resources// jsp 不能被访问到
在这里插入图片描述

9.全局捕获异常

@ExceptionHandler 表示拦截异常
•	@ControllerAdvice 是 controller 的一个辅助类,最常用的就是作为全局异常处理的切面类
•	@ControllerAdvice 可以指定扫描范围
•	@ControllerAdvice 约定了几种可行的返回值,如果是直接返回 model 类的话,需要使用 @ResponseBody 进行 json 转换
o	返回 String,表示跳到某个 view
o	返回 modelAndView
o	返回 model + @ResponseBody

@ControllerAdvice
public class GlobalExceptionHandler {
	@ExceptionHandler(RuntimeException.class)
	@ResponseBody
	public Map<String, Object> exceptionHandler() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("errorCode", "101");
		map.put("errorMsg", "系統错误!");
		return map;
	}
}

猜你喜欢

转载自blog.csdn.net/u012124438/article/details/83001195