Spring Boot快速入门

安装

安装依赖

maven是一个依赖管理工具,我们利用maven进行构建。创建一个maven项目,在pom.xml里面添加依赖项

<?xml version="1.0" encoding="UTF-8"?>
<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>1.0</groupId><artifactId>SpringBoot</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.2.RELEASE</version></parent><properties><java.version>1.8</java.version></properties><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></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

,接着在idea里面import change,或者执行mvn install来下载依赖。

启动

在src根目录创建一个包,然后将项目的代码放进去。(注:App类不能直接放在src根目录,否则将无法正常启动)

package App;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@SpringBootApplication
public class App {public static void main(String[] args) {SpringApplication.run(App.class, args);}
}

运行

点击RUN,即可运行。如果是正常启动,控制台会输出

 

路由

什么是路由?

路由是什么?路由即我们浏览器上的地址,我们通过路由与服务器进行信息交互。例如:https://search.bilibili.com/all?keyword=老友记。在这个例子中,我们访问https://search.bilibili.com/all,并且参数是老友记,直观意思是搜索keyword是老友记的视频。也可以这么理解,https://search.bilibili.com/all是一个函数,keyword是参数,通过调用函数来获得对应的结果。

匹配方法和路由

在Spring Boot中,我们需要指定哪一个路由对应哪一个方法。

我们在一个Controller里面通过@RequestMapping注解来匹配路径和对应的方法,以下是代码例子。

@RestController
@RequestMapping("test")
public class IndexController {@RequestMapping("index")public String fun(){return "hello Spring boot";} }

@RestController注解的作用是表示这一个类是一个控制器类,并且返回的对象会自动转换为JSON(如果返回字符串则还是字符串形式)。@RequestMapping作用是匹配路由和方法,当它加在类上的时候,就是给该类的所有路径前加一层,但它加在方法上的时候,表示该路径匹配该方法。在这个例子中访问http://localhost:8080/hello/index,页面即打印hello Spring boot。

返回Json对象

进一步,如果我们想要返回JSON对象,怎么办呢?

@RestController注解的类会自动转换对象为JSON的,如果只是用@Controller修饰类,则要在方法前加上@ResponseBody。以下演示如何返回Json对象。

 @RequestMapping("person")public Object testJson(){return new Person("Overflow",18);}

在之前的控制器上加上以上代码,Person是我们自己定义的类。在浏览器上打开即可以看到Json字符串

{"name":null,"age":18}。

指定请求方法

如果我们想指定路由的请求方法,我们可以在@RequestMapping指定method,method可以是单个对象,也可以是数组形式。

@RequestMapping( value = "index",method ={RequestMethod.GET,RequestMethod.POST} )

以上例子说明该路由请求可以用GET和POST访问。如果不特别指定,则任何方法都可以访问该路由。

 接受路由参数

只有单纯的路由是不够的,路由可以附带参数对服务器,那么我们绑定的方法要如何接受这些参数呢?

在Spring Boot里,我们只需要结合注解即可,以下介绍几种例子

1、匹配路由中的参数

 @RequestMapping("/person/{name}")public Object testJson(@PathVariable(name = "name")String name)

2、获得get 或者post方法的参数

get方法路径就是 http:localhost:8080/hello/data?name=Tom

post方法要把参数放在form-data中

@RequestMapping(value = "/data",method={RequestMethod.GET,RequestMethod.POST})public Object accessData(@RequestParam(name="name") String name){return name;}

3、接受Json对象

当参数比较多的时候,可以将参数解释为一个对象。注意该类一定要有一个默认的构造方法。

@RequestMapping(value = "/json")public Object accessJsonData(Person person){return person.getName();}

4、接收HttpServletRequest对象

事实上以上的接收参数方法都是框架封装HttpServletRequest对象,而我们获得这个对象的方法很简单,只需要在函数的参数列表里面声明就好,Spring框架会为我们的方法注入该对象。

  @RequestMapping(value = "/servlet")public Object selvlet(HttpServletRequest request){return request.getRequestURL();}

 

Session和Cookie

cookie的作用

cookie是存储在浏览器端的数据。通常用于保存客户端的状态信息。

Session的作用

Http请求,与普通的程序不一样,他是没有状态的。但是许多应用需要记录用户的状态,例如用户的登录信息等等,这时候就利用session技术来存储。当浏览器与服务器进行交互,服务器会分配一个SessionID给浏览器,浏览器会把这个ID保存在cookie里,然后每一次发送请求的时候都会将这一个sessionID附上,然后服务器就可以获得该ID的相关数据。

Map<String,Map<String,Object>> Session

Session的使用类似于以上的代码说明,一个SessionID对应一个Map来存储数据。

当然在Spring Boot里面,不需要手动地调用sessionID,就能获取对应该ID的HttpSession对象。

@RequestMapping(value = "/sessionAndCookie")public Object sessionAndCookie(HttpSession session, HttpCookie cookie)

 

与数据库交互数据

什么是ORM?

数据库的数据是通过字段来存储信息的,如果Java类的属性能够与数据库的字段互相映射,那么我们就可以像操作Java对象一样操作数据库数据,方便的进行增删查改操作。

SpringBoot与MySQL进行数据交互

添加依赖

在原来的pom.xml里面添加以下依赖

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

在resource文件夹新建一个application.properties文件,这是一个配置文件

spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/你的数据库名称
spring.datasource.username=username
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto的作用,在这里我直接引用文档的解释

Here, spring.jpa.hibernate.ddl-auto can be noneupdatecreatecreate-drop, refer to the Hibernate documentation for details.

  • none This is the default for MySQL, no change to the database structure.

  • update Hibernate changes the database according to the given Entity structures.

  • create Creates the database every time, but don’t drop it when close.

  • create-drop Creates the database then drops it when the SessionFactory closes.

创建与数据库表对应的Entity类

 

@Entity
@Table(name = "user")
public class User
{@Idpublic int id;public String username;public String password;public int power;
}

注解解释,@Entity注解表示该类是一个与数据库映射的类,@Table表示这个类绑定的是user表,@Id表示id是主键。

创建Repository类

这个类是与数据库进行交互用的,我们要继承Spring框架给我们提供的一个接口,CrudRepository<>,在使用的时候Spring框架会为我们自动注入相关的方法,方便我们进行增删查改

public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {<S extends T> S save(S var1);<S extends T> Iterable<S> save(Iterable<S> var1);T findOne(ID var1);boolean exists(ID var1);Iterable<T> findAll();Iterable<T> findAll(Iterable<ID> var1);long count();void delete(ID var1);void delete(T var1);void delete(Iterable<? extends T> var1);void deleteAll();
}

解释以上相关的函数

save(S var)    传入对象即可保存在数据库对象,如果我们的对象有指定ID,则会更新相应ID的记录

delete(ID var1)  传入ID即可删除对应ID的记录

构造查询方法

以下是我们的UserRepository的例子

public interface UserRepository extends CrudRepository<User,Long>
{//1、通过函数名来进行查询
    User findByUsername(String username);List<User> findUsersByUsername(String username);//2、通过指定HQL语句进行查询@Query("select u from User u where u.username= :username and u.password= :password")User findUser(@Param("username") String name,@Param("password") String password);
}

查询方式有两种

一种是Spring Data提供的通过一定规范的函数名进行查询

另一种是利用@Query注解,指定HQL,来实现复杂的查询

大家看到这里可能会疑惑,为什么只需要定义方法名,而不需要写具体的方法体呢。这是Spring框架的优势,因为对象都是由Spring来管理,因此只需要给与必要的信息给框架识别,框架就能够构建一个继承你的接口的函数,接着按照Spirng自动载入的方法,将该对象引入类中即可。

 

在Controller类里使用Repository类

@RestController
@RequestMapping("user")
public class UserController
{@AutowiredUserRepository userRepository;@RequestMapping("find/{name}")public Object findUser(@PathVariable("name")String name){return userRepository.findByUsername("hello");}@RequestMapping("check/{name}/{password}")public Object checkUser(@PathVariable("name") String name,@PathVariable("password") String password){return userRepository.findUser(name, password);}
}

利用@AutoWired即可自动载入我们定义的UserRepository

 参考资料

1、http请求方法:http://www.runoob.com/http/http-methods.html

2、spring boot文档:http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/

3、spring data jpa文档:http://docs.spring.io/spring-data/jpa/docs/2.0.0.M4/reference/html/#jpa.query-methods

4、spring boot guide:https://spring.io/guides/gs/rest-service/

转载于:https://www.cnblogs.com/alisonyu/p/7100699.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/416465.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

前端学习(2465):ajax发送请求

原文链接&#xff1a;https://www.cnblogs.com/0x29a/p/11231950.html 1. 创建XMLHttpRequest异步对象 步骤一代码引自&#xff1a;https://www.w3school.com.cn/ajax/ajax_xmlhttprequest_create.asp var xhr; if (window.XMLHttpRequest){// code for IE7, Firefox, Chrome, …

mysql数据库with ur_Python使用MySQL数据库(新)

一&#xff0c;安装mysql如果是windows用户&#xff0c;mysql的安装非常简单&#xff0c;直接下载安装文件&#xff0c;双击安装文件一步一步进行操作即可。Linux 下的安装可能会更加简单&#xff0c;除了下载安装包进行安装外&#xff0c;一般的linux仓库中都会有mysql&#x…

洛谷——P1067 多项式输出

https://www.luogu.org/problem/show?pid1067#sub 题目描述 一元 n 次多项式可用如下的表达式表示&#xff1a; 其中&#xff0c;aixi称为 i 次项&#xff0c;ai 称为 i 次项的系数。给出一个一元多项式各项的次数和系数&#xff0c;请按照如下规定的格式要求输出该多项式&…

前端学习(2467):在前端页面中引入百度地图

走在前端的大道上 插槽&#xff0c;也就是slot&#xff0c;是组件的一块HTML模板&#xff0c;这块模板显示不显示、以及怎样显示由父组件来决定。 实际上&#xff0c;一个slot最核心的两个问题在这里就点出来了&#xff0c;是显示不显示和怎样显示。 由于插槽是一块模板&…

pm961 mysql_Oracle GoldenGate学习之--异构平台同步(Mysql到Oracle)

Oracle GoldenGate学习之--异构平台同步(Mysql到Oracle)如图所示&#xff1a;源端采用Mysql库&#xff0c;目标端采用Oracle库一、OGG安装配置(源端)1、OGG下载https://edelivery.oracle.com/EPD/Download/get_form?egroup_aru_number14841438https://edelivery.oracle.com/EP…

转:在csv中维护变量参数

问题&#xff1a; 1、我的变量表多&#xff0c;通过之前的csv获取的方式&#xff0c;或者用户变量来维护&#xff0c;比较麻烦 2、我想在脚本之外维护我的变量数据&#xff0c;脱离脚本 解决方案&#xff1a; 1、csv的配置如图&#xff0c;队列是变量名称&#xff0c;第二列是变…

前端学习(2471):vue-echarts和echarts的区别:

vue-echarts和echarts的区别&#xff1a; vue-echarts是封装后的vue插件&#xff0c; 基于 ECharts v4.0.1 开发&#xff0c;依赖 Vue.js v2.2.6&#xff0c;功能一样的只是把它封装成vue插件 这样更方便以vue的方式去使用它。echarts就是普通的js库&#xff0c; vue-echarts特…

前端学习(2474):页面布局

request.js <template> <div class"artical-container"><!--卡片--><el-card class"filter-card"><div slot"header" class"clearfix"><!--面包屑导航--><el-breadcrumb separator-class&quo…

linuxsed替换字符串后保存_Numpy运用-文件读写、存储及字符串处理

问题列举&#xff1a;Numpy文件读取Numpy文件存储Numpy字符串操作1、文件读取可以使用genfromtxt读取txt或者csv文件可以使用loadtxt读取txt或者csv文件两个函数功能类似&#xff0c;genfromtxt针对的更多是结构化数据注&#xff1a;delimiter表示的是以&#xff0c;分隔数据&a…

mysql5.1win7_免安装版mysql5.1.57在win7下成功配置

mysql下载回来之后解压到D:/mysql-5.1.57-win32&#xff0c;把D:/mysql-5.1.57-win32/bin加入到系统环境变量Path中。然后需要简单的配置mysql数据库&#xff0c;把my-small.ini改名为my.ini(其他的几个文件也可以直接拿过来修改一下名字)&#xff0c;编辑文件my.ini&#xff0…

前端学习(2476):表单数据绑定处理

request.js <template> <div class"artical-container"><!--卡片--><el-card class"filter-card"><div slot"header" class"clearfix"><!--面包屑导航--><el-breadcrumb separator-class&quo…

sizeof小览

sizeof小览 一、文章来由—一道面试题迁出的探究 我发现我已经形成一种习惯写来由了&#xff0c;以后看博客的时候能够让我回顾起为什么出现这个问题&#xff0c;我用什么方法解决的&#xff0c;既然形成习惯就让这个习惯保持下去吧。今天实验室师姐在看书&#xff0c;一处不解…

前端学习(2477):封装数据接口

request.js <template> <div class"artical-container"><!--卡片--><el-card class"filter-card"><div slot"header" class"clearfix"><!--面包屑导航--><el-breadcrumb separator-class&quo…

前端学习(2478):请求提交

request.js <template> <div class"artical-container"><!--卡片--><el-card class"filter-card"><div slot"header" class"clearfix"><!--面包屑导航--><el-breadcrumb separator-class&quo…