Springboot1学习(一)快速入门

本文指导读者快速掌握Spring Boot基础知识,包括创建项目、启动方式、静态资源、异常处理、模板引擎(FreeMarker)、整合JPA和MyBatis。适合有一定Spring MVC基础的学习者。
摘要由CSDN通过智能技术生成

拖了好久,终于开始学springboot,馒馒来吧。

打实基础,脚踏实地,馒馒来,一身轻松

看了看还有好多没学完…

先学springboot1吧,磨刀不误砍柴功



springboot概述

支离破碎的语言随便写一下吧,反正都不看概述的。捂脸

在这里插入图片描述

目前spingboot主流
敏捷开发
无需tomcat,内置了tomcat
减少xml配置,改用properties
springcloud+springboot微服务技术
springboot底层封装springmvc

微服务基于springcloud(http协议,Restful+http),springcloud基于springboot

云里雾里

快速入门

创建maven项目

引入依赖,在pom.xml中引入spring-boot-start-parent,它可以提供依赖管理,引入以后在申明其它dependency的时候就不需要version了,spring-boot-starter-web是springweb核心组件

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.3.RELEASE</version>
	</parent>
	<dependencies>
	  <!--SpringBoot web 组件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>

写第一个接口

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@EnableAutoConfiguration
public class HelloController {

    @RequestMapping("/index")
    public String index() {
        return "Hello World";
    }
    @RequestMapping("/getMap")
    public Map<String,Object> getMap(){
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("msg", "Hello World");
        return map;
    }

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

这里有几个要说明的

@RestController
在上加上RestController 表示修饰该Controller所有的方法返回JSON格式,直接可以编写Restful接口

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

SpringApplication.run(HelloController.class, args);
标识为启动类,第一种启动方式,只启动当前接口

Springboot默认端口号为8080

启动主程序
在这里插入图片描述

打开浏览器访问http://localhost:8080/index,可以看到页面输出Hello World

在这里插入图片描述

第二种启动方式

@ComponentScan(basePackages = “ch1.controller”)
控制器扫包范围

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

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

项目中不要写多个main函数,打包会找不到入口

静态资源访问

在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。
默认配置
Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:
/static
/public
/resources
/META-INF/resources

举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动程序后,尝试访问http://localhost:8080/D.jpg。如能显示图片,配置成功。

为什么我用http://localhost:8080/static/D.jpg就访问不到呢?

原理有谁清楚吗

全局异常捕获

web开发时,请求500返回一个系统错误的页面

常用的注解有:

@ExceptionHandler(RuntimeException.class)
表示拦截运行异常

@ControllerAdvice
是 controller 的一个辅助类,最常用的就是作为全局异常处理的切面类
可以指定扫描范围
约定了几种可行的返回值,

如果是要 json 返回结果就加上 @ResponseBody
返回 String,表示跳到某个 view
返回 modelAndView
返回 model + @ResponseBody

创建全局捕获异常类

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

全局捕获异常用到的是哪一种通知?

异常通知

SpringAop通知分为五类:前置通知、正常返回通知、异常返回通知、返回通知、环绕通知。

FreeMarker页面渲染

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

springboot优先模板引擎,不建议使用jsp。若一定要使用JSP将无法实现Spring Boot的多种特性

什么是模板引擎?
即动态的html实现。

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

  • Thymeleaf
  • FreeMarker
  • Velocity
  • Groovy
  • Mustache

当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径

引入jar包

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

创建index.ftl

this is hello world index.ftl

${name}

创建正常MVC接口

// 正常接口请求 MVC
@Controller
public class IndexController {
    @RequestMapping("/indexController")
    public String indexController(Map<String, Object> result) {
        result.put("name", "likeghee");
        result.put("sex", "0");
        List<String> listResult = new ArrayList<String>();
		listResult.add("zhangsan");
		listResult.add("lisi");
		result.put("userlist", listResult);
        System.out.println("indexController");
        // 返回view
        return "index";
    }

}

访问http://localhost:8080/indexController页面
在这里插入图片描述

freemarker其他用法

	<#if sex=="1">
            男
     <#elseif sex=="2">
            女
     <#else>
        其他      
	  
	 </#if>	  
	 <#list userlist as user>
	   ${user}
	 </#list>

在这里插入图片描述
Freemarker配置

新建application.properties文件
在这里插入图片描述

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

整合jsp

整合jsp一般的项目不会用到的

创建SpringBoot整合JSP,一定要为war类型,否则会找不到页面.

也就是说要打包成war

<packaging>war</packaging>

添加jar包

    <packaging>war</packaging>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.3.RELEASE</version>
	</parent>
	<dependencies>
		<!-- SpringBoot 核心组件 -->
		<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>
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
		</dependency>
	</dependencies>

在application.properties添加配置文件

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

在main目录下面创建/webapp/WEB-INF/jsp
在这里插入图片描述

/jsp下面再创建index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
jsp整合
</body>
</html>

写接口,跳转到index视图

// 正常接口请求 MVC
@Controller
public class IndexController {
    @RequestMapping("/indexController")
    public String indexController(Map<String, Object> result) {
        System.out.println("indexController");
        return "index";
    }

}

访问接口进行测试
在这里插入图片描述

整合jdbcTemplate

引入jar包

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>

添加application.properties配置

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

创建UserService类进行测试

@Service
public class UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void createUser(String id, String name, Integer age) {
        System.out.println("createUser");
        jdbcTemplate.update("insert into user0 values(?,?,?);", id, name, age);
    }
}

建立UserController

@RestController
public class UserController {
    @Autowired
    private UserService userService;


    @RequestMapping("/createUser")
    public String createUser(String id, String name, String password) {
        userService.createUser(id, name, password);
        return "success";
    }
}

启动项注意添加扫包
不然会报错的:org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘userController’: Injection of autowired dependencies failed;

Could not autowire field: private ch1.service.UserService ch1.controller.UserController.userService

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

访问接口测试
在这里插入图片描述

非常so easy

整合springjpa

jpa是啥?
springjpa对hibernate进行封装

引入jar包

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

我同时引入了jdbctemplate和jpa会发生冲突吗?
不会的,项目整合了什么jdbc框架是不会有冲突的

使用hibernate需要将实体类进行关联映射

建立User类

@Data
@Entity(name = "user0")
public class User {
    @Id
    String id;
    @Column
    String name;
    @Column
    String pwd;
    
}

建立dao层

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserDao extends JpaRepository<User, String> {
}

写Controller

@RestController
public class UserController {
    @Autowired
    private UserDao userDao;

    @RequestMapping("/getUser")
    public User getUser(String id){
        return userDao.findOne(id);
    }
}

APP启动类添加扫包范围

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;


@ComponentScan(basePackages = {"ch1.controller", "ch1.service"})
@EnableAutoConfiguration
@EnableJpaRepositories(basePackages = {"ch1.dao"})
@EntityScan(basePackages = {"ch1.entity"})
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

访问接口进行测试
在这里插入图片描述

整合mybatis

添加依赖

		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.1.1</version>
		</dependency>

数据源依赖

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.21</version>
		</dependency>

添加配置

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

添加pojo

@Data
public class Article {

    int id;
    String title;
    String body;
}

添加mapper层,mybatis有注解版本和xml版本,xml版本太low了,使用注解版

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface ArticleMapper {
    @Select("SELECT * FROM articles WHERE title = #{title}")
    Article findByName(@Param("title") String title);
    @Insert("INSERT INTO articles(title, body) VALUES(#{title}, #{body})")
    int insert(@Param("title") String title, @Param("body") Integer body);
}

直接写Controller层,就跳过Service层了,加快一下进度

@RestController
@RequestMapping("/ArticleController")
public class ArticleController {
    @Autowired
    private ArticleMapper articleMapper;
    @RequestMapping("/findByName")
    public Article findByName(String title){
        return articleMapper.findByName(title);
    }
    @RequestMapping("/insert")
    public int insert(String title,String body){
        return articleMapper.insert(title, body);
    }
}

添加扫包@MapperScan

@ComponentScan(basePackages = {"ch1.controller", "ch1.service"})
@EnableAutoConfiguration
@EnableJpaRepositories(basePackages = {"ch1.dao"})
@EntityScan(basePackages = {"ch1.entity"})
@MapperScan(basePackages = {
    "ch1.mapper"
})
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

测试接口
在这里插入图片描述
在这里插入图片描述

检查数据库
在这里插入图片描述


很快啊,真的太快了,有spring和springmvc基础入门springboot太轻松了…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值