首页 文章 精选 留言 我的

精选列表

搜索[SpringBoot4],共10000篇文章
优秀的个人博客,低调大师

阿里架构师用一篇文章带你详解SpringBoot注解

一、注解(annotations)列表@SpringBootApplication:包含了@ComponentScan、@Configuration和@EnableAutoConfiguration注解。其中@ComponentScan让Spring Boot扫描到Configuration类并把它加入到程序上下文。 @Configuration 等同于spring的XML配置文件;使用java代码可以检查类型安全。 @EnableAutoConfiguration 自动配置。 @ComponentScan 组件扫描,可自动发现和装配一些Bean。 @Component可配合CommandLineRunner使用,在程序启动后执行一些基础任务。 @RestController注解是@Controller和@ResponseBody的合集,表示这是个控制器bean,并且是将函数的返回值直 接填入HTTP响应体中,是REST风格的控制器。 @Autowired自动导入。 @PathVariable获取参数。 @JsonBackReference解决嵌套外链问题。 @RepositoryRestResourcepublic配合spring-boot-starter-data-rest使用。 二、注解(annotations)详解@SpringBootApplication:申明让spring boot自动给程序进行必要的配置,这个配置等同于:@Configuration ,@EnableAutoConfiguration 和 @ComponentScan 三个配置。 package com.example.myproject; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } @ResponseBody:表示该方法的返回结果直接写入HTTP response body中,一般在异步获取数据时使用,用于构建RESTful的api。在使用@RequestMapping后,返回值通常解析为跳转路径,加上@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如异步获取json数据,加上@responsebody后,会直接返回json数据。该注解一般会配合@RequestMapping一起使用。示例代码: @RequestMapping(“/test”) @ResponseBody public String test(){ return”ok”; } @Controller:用于定义控制器类,在spring 项目中由控制器负责将用户发来的URL请求转发到对应的服务接口(service层),一般这个注解在类中,通常方法需要配合注解@RequestMapping。示例代码: @Controller @RequestMapping(“/demoInfo”) publicclass DemoController { @Autowired private DemoInfoService demoInfoService; @RequestMapping("/hello") public String hello(Map map){ System.out.println("DemoController.hello()"); map.put("hello","from TemplateController.helloHtml"); //会使用hello.html或者hello.ftl模板进行渲染显示. return"/hello"; } @RestController:用于标注控制层组件(如struts中的action),@ResponseBody和@Controller的合集。示例代码: package com.kfit.demo.web; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author Angel(QQ交流群:193341332,QQ:412887952) @version v.0.1 @date 2016年7月29日下午7:26:04 */ @RestController @RequestMapping(“/demoInfo2”) publicclass DemoController2 { @RequestMapping("/test") public String test(){ return"ok"; } @RequestMapping:提供路信息,负责URL到Controller中的具体函数的映射。 @EnableAutoConfiguration:Spring Boot自动配置(auto-configuration):尝试根据你添加的jar依赖自动配置你的Spring应用。例如,如果你的classpath下存在HSQLDB,并且你没有手动配置任何数据库连接beans,那么我们将自动配置一个内存型(in-memory)数据库”。你可以将@EnableAutoConfiguration或者@SpringBootApplication注解添加到一个@Configuration类上来选择自动配置。如果发现应用了你不想要的特定自动配置类,你可以使用@EnableAutoConfiguration注解的排除属性来禁用它们。 @ComponentScan:表示将该类自动发现扫描组件。个人理解相当于,如果扫描到有@Component、@Controller、@Service等这些注解的类,并注册为Bean,可以自动收集所有的Spring组件,包括@Configuration类。我们经常使用@ComponentScan注解搜索beans,并结合@Autowired注解导入。可以自动收集所有的Spring组件,包括@Configuration类。我们经常使用@ComponentScan注解搜索beans,并结合@Autowired注解导入。如果没有配置的话,Spring Boot会扫描启动类所在包下以及子包下的使用了@Service,@Repository等注解的类。 @Configuration:相当于传统的xml配置文件,如果有些第三方库需要用到xml文件,建议仍然通过@Configuration类作为项目的配置主类——可以使用@ImportResource注解加载xml配置文件。 @Import:用来导入其他配置类。 @ImportResource:用来加载xml配置文件。 @Autowired:自动导入依赖的bean @Service:一般用于修饰service层的组件 @Repository:使用@Repository注解可以确保DAO或者repositories提供异常转译,这个注解修饰的DAO或者repositories类会被ComponetScan发现并配置,同时也不需要为它们提供XML配置项。 @Bean:用@Bean标注方法等价于XML中配置的bean。 @Value:注入Spring boot application.properties配置的属性的值。示例代码: @Value(value = “#{message}”) private String message; @Inject:等价于默认的@Autowired,只是没有required属性; @Component:泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。 @Bean:相当于XML中的,放在方法的上面,而不是类,意思是产生一个bean,并交给spring管理。 @AutoWired:自动导入依赖的bean。byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。当加上(required=false)时,就算找不到bean也不报错。 @Qualifier:当有多个同一类型的Bean时,可以用@Qualifier(“name”)来指定。与@Autowired配合使用。@Qualifier限定描述符除了能根据名字进行注入,但能进行更细粒度的控制如何选择候选者,具体使用方式如下: @Autowired @Qualifier(value = “demoInfoService”) private DemoInfoService demoInfoService; @Resource(name=”name”,type=”type”):没有括号内内容的话,默认byName。与@Autowired干类似的事。 三、JPA注解@Entity:@Table(name=”“):表明这是一个实体类。一般用于jpa这两个注解一般一块使用,但是如果表名和实体类名相同的话,@Table可以省略 @MappedSuperClass:用在确定是父类的entity上。父类的属性子类可以继承。 @NoRepositoryBean:一般用作父类的repository,有这个注解,spring不会去实例化该repository。 @Column:如果字段名与列名相同,则可以省略。 @Id:表示该属性为主键。 @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = “repair_seq”):表示主键生成策略是sequence(可以为Auto、IDENTITY、native等,Auto表示可在多个数据库间切换),指定sequence的名字是repair_seq。 @SequenceGeneretor(name = “repair_seq”, sequenceName = “seq_repair”, allocationSize = 1):name为sequence的名称,以便使用,sequenceName为数据库的sequence名称,两个名称可以一致。 @Transient:表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性。如果一个属性并非数据库表的字段映射,就务必将其标示为@Transient,否则,ORM框架默认其注解为@Basic。@Basic(fetch=FetchType.LAZY):标记可以指定实体属性的加载方式 @JsonIgnore:作用是json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都受影响。 @JoinColumn(name=”loginId”):一对一:本表中指向另一个表的外键。一对多:另一个表指向本表的外键。 @OneToOne、@OneToMany、@ManyToOne:对应Hibernate配置文件中的一对一,一对多,多对一。 四、springMVC相关注解@RequestMapping:@RequestMapping(“/path”)表示该控制器处理所有“/path”的UR L请求。RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。 用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。该注解有六个属性: params:指定request中必须包含某些参数值是,才让该方法处理。 headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。 value:指定请求的实际地址,指定的地址可以是URI Template 模式 method:指定请求的method类型, GET、POST、PUT、DELETE等 consumes:指定处理请求的提交内容类型(Content-Type),如application/json,text/html; produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回 @RequestParam:用在方法的参数前面。 @RequestParam String a =request.getParameter(“a”)。 @PathVariable:路径变量。如 RequestMapping(“user/get/mac/{macAddress}”) public String getByMacAddress(@PathVariable String macAddress){ //do something; } 参数与大括号里的名字一样要相同。 五、全局异常处理@ControllerAdvice:包含@Component。可以被扫描到。统一处理异常。 @ExceptionHandler(Exception.class):用在方法上面表示遇到这个异常就执行以下方法。 喜欢这篇文章的可以给笔者点个赞同,关注一下,每天都会分享Java相关文章!还有不定时的福利赠送,包括整理的学习资料,面试题,源码等~~

优秀的个人博客,低调大师

30分钟极速通关react mobx react-router及打通springboot

内容导航 简单开发react 将react与mobx结合开发 使用react-router进行多页面开发 将项目打包到后端项目中进行部署 将完成的项目做成脚手架,避免重复的环境搭建 需要环境 确保node已经安装 确保npm已经安装 创建项目 github项目地址 npx create-react-app test # test 为你需要创建项目的名字,会在命令当前目录下创建test的目录,包含项目所有的文件 你已经完成了创建,开始跑起来 npm start 你可以看到react已经能够在local host:3000访问了,只有一个欢迎页面 目录结构 node_modules 是当前目录安装的模块存放的地方 public index.html 是单页面的入口 src 可存放自己编写的代码,App是默认生成的欢迎页面逻辑,index 是js的主入口 开始更改你的代码 A. react简单开发 1.将App.js的代码更改如下 import React, {Component} from 'react'; import './App.css'; class App extends Component { constructor(props) { super(props) this.state = {todos: [{checked: false, text: "hello"}, {checked: true, text: "world"}]} this.handleClick=this.handleClick.bind(this) } handleClick(index) { let todos = this.state.todos todos[index].checked = !todos[index].checked this.setState({todos:todos}) } render() { let todos = this.state.todos let todosDiv = todos.map((item, index) => { return (<Todo index={index} checked={item.checked} text={item.text} handleClick={this.handleClick}/>) }) return ( <div className="App"> {todosDiv} </div> ); } } class Todo extends Component { constructor(props){ super(props) this.handleClick=this.handleClick.bind(this) } handleClick() { let index = this.props.index this.props.handleClick(index) }; render() { return ( <p><input type={'checkbox'} checked={this.props.checked} onClick={this.handleClick}/> {this.props.text}:{this.props.index} </p> ) } } export default App; 再次npm start一下看看效果吧~ 可以看到我们组件已经能够响应点击了 B. 引入mobx作为状态管理 提出问题 在上面我们可以看到想要更改状态是比较困难的,首先要将handClick方法由子组件传给父组件,再进行处理。如果我们的组件是四五层组件的时候得一步一步的往上级传递,这就会导致组件传递写的很臃肿。这个时候就需要一个将状态(即state这个值)独立开来。 react有很多状态管理的组件,比如redux,mobx。但redux写起来还是不如mobx简单明了。下面我们就来接入mobx。 接入步骤 安装依赖 npm install mobx --save npm install mobx-react --save 启用装饰器语法 # 如果有git的话,要将没有保存的文件上传之后或者删除之后才能跑eject命令 yarn run eject npm install --save-dev babel-preset-mobx 在package.json中找到babel项目,在presets里面增加"mobx" "babel": { "presets": [ "react-app", "mobx" ]}, 加入core-decorators npm install core-decorators --save 在src下增加store.AppStore.js文件 import {action, observable} from "mobx"; class AppStore { @observable todos; constructor() { this.todos = [{checked: false, text: "hello"}, {checked: true, text: "world"}] } @action.bound handleClick(index) { let todos = this.todos todos[index].checked = !todos[index].checked } } export default AppStore; 改写index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import {Provider} from "mobx-react"; import AppStore from './store/AppStore' let rootStore = {} rootStore['app'] = new AppStore() ReactDOM.render( <Provider {...rootStore}> <App/> </Provider>, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister(); 改写App.js import React, {Component} from 'react'; import './App.css'; import {inject, observer} from "mobx-react"; import {autobind} from "core-decorators"; @inject("app") @autobind @observer class App extends Component { constructor(props) { super(props) } render() { let todos = this.props.app.todos let todosDiv = todos.map((item, index) => { return (<Todo index={index}/>) }) return ( <div className="App"> {todosDiv} </div> ); } } @inject("app") @autobind @observer class Todo extends Component { constructor(props) { super(props) } handleClick() { let index = this.props.index this.props.app.handleClick(index) }; render() { let index = this.props.index let todo = this.props.app.todos[index] return ( <p><input type={'checkbox'} checked={todo.checked} onClick={this.handleClick}/> {todo.text}:{index} </p> ) } } export default App; npm start一下,来看看效果吧 简要说明 @inject("app")表示注入在index.js中的rootStore的属性app。是由这个标签来实现动态的注入的 @autobind 将组件之间的绑定自动完成 @observer mobx用来将react组件转换为响应式组件的注解,详情查看mobx的文档 上面可以看出,将原本的state的属性抽离到AppStore中了,对值得更改方法也是直接调用AppStore的方法,从而避免了react组件的一级一级往上传递 C. 引入react-router作为多页面管理 提出问题 上面我们完成了单页面的开发。当需要多个页面时我们就需要使用react-router来对不同路径进行渲染了 接入react-router步骤 安装依赖 npm install react-router mobx-react-router --save 增加新的页面,在src中增加component/Test.js import * as React from "react"; class Test extends React.Component{ render() { return(<p>welcome!</p>) } } export default Test; 更改index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import {Provider} from "mobx-react"; import AppStore from './store/AppStore' import {Route, Router, Switch} from "react-router"; import {RouterStore, syncHistoryWithStore} from "mobx-react-router"; import createHashHistory from "history/createHashHistory" import Test from "./component/Test" let rootStore = {} const hashHistory = createHashHistory() const routerStore = new RouterStore() const history = syncHistoryWithStore(hashHistory, routerStore) rootStore['app'] = new AppStore() routerStore['routing'] = routerStore ReactDOM.render( <Provider {...rootStore}> <Router history={history}> <p>here is the menu</p> <Switch> <Route path={"/test"} component={Test}/> <Route path={"/"} component={App}/> </Switch> </Router> </Provider>, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister(); npm start一下,访问下/#/test,和/#/路径,看看效果吧 简要说明 createHashHistory是单页面的访问,会在url加个#号作为定位,这个对于要打包到后台作为页面时是很方便的。 如果你直接使用node部署的话可以直接使用createBrowserHistory,url就会是没有#号的url。 D. 结合ui框架 接入步骤 找到一个合适的react ui框架,install之后按照ui框架的教程就可以开发一个相对比较好看的页面了 常见的框架有semantic,bootstrap,ant等。 E. 结合maven打包进spring boot项目 提出问题 当我们需要跟spring boot等后端项目结合,而又不想单独部署前端页面时,就需要打包进后端项目了 接入步骤 新建一个多模块的maven项目 按照之前创建的步骤,创建前端的模块,假设模块名字为view,并在前端模块的目录下增加pom.xml <build> <plugins> <plugin> <groupId>com.github.eirslett</groupId> <artifactId>frontend-maven-plugin</artifactId> <version>1.2</version> <executions> &lt;-- Install our node and npm version to run npm/node scripts--> <execution> <id>install node and npm</id> <goals> <goal>install-node-and-npm</goal> </goals> <configuration> &lt;-- 指定node的版本例如 v6.9.1 --> <nodeVersion>${nodeVersion}</nodeVersion> <npmVersion>${npmVersion}</npmVersion> <nodeDownloadRoot>https://npm.taobao.org/mirrors/node/</nodeDownloadRoot> <npmDownloadRoot>http://registry.npmjs.org/npm/-/</npmDownloadRoot> </configuration> </execution> &lt;-- Set NPM Registry --> <execution> <id>npm set registry</id> <goals> <goal>npm</goal> </goals> <configuration> &lt;--<arguments>config set registry https://registry.npmjs.org</arguments>--> <arguments>config set registry https://registry.npm.taobao.org</arguments> </configuration> </execution> &lt;-- Set SSL privilege --> <execution> <id>npm set non-strict ssl</id> <goals> <goal>npm</goal> </goals> &lt;-- Optional configuration which provides for running any npm command --> <configuration> <arguments>config set strict-ssl false</arguments> </configuration> </execution> &lt;-- Install all project dependencies --> <execution> <id>npm install</id> <goals> <goal>npm</goal> </goals> &lt;-- optional: default phase is "generate-resources" --> <phase>generate-resources</phase> &lt;-- Optional configuration which provides for running any npm command --> <configuration> <arguments>install</arguments> </configuration> </execution> &lt;-- Build and minify static files --> <execution> <id>npm run build</id> <goals> <goal>npm</goal> </goals> <configuration> <arguments>run build</arguments> </configuration> </execution> </executions> </plugin> </plugins> </build> 当进行mvn package时就会在目录下生成build目录,包含所有的页面和脚本了。 在spring boot后端项目中,将前端打包好的页面拷贝到后端目录中 <build> <plugins> <plugin> <artifactId>maven-resources-plugin</artifactId> <executions> <execution> <id>Copy App Content</id> <phase>generate-resources</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>src/main/resources/public</outputDirectory> <overwrite>true</overwrite> <resources> <resource> <directory>${project.parent.basedir}/view/build</directory> <includes> <include>static/</include> <include>index.html</include> </includes> </resource> </resources> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> 其中outputDirectory指明要放入的文件夹 directory指明要拷贝哪里的资源文件,需要根据你的前端模块名进行相应的修改 mvn package 一下,后端模块的打包jar里面就会有相应的资源文件啦 F. 前后端联调 步骤 在前端项目package.json中指明接口的代理 "proxy":"http://localhost:8080/" 如果servletPath不为/,则需要在后面补上相应的servletPath 当你的后端项目有设置servletPath的时候,需要相应配置前端的打包的servletPath,否则默认为/的servletpath 方法1: package.json 增加 "homepage": "." 方法2: config.paths.js文件下修改配置 function getServedPath(appPackageJson) { const publicUrl = getPublicUrl(appPackageJson); //将/修改为./ const servedUrl = envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : './'); return ensureSlash(servedUrl, true); } G. 将你创建好的项目做成脚手架 提出问题 如果每个项目都要经历上面的步骤,才能完成,那前期工作量是在太繁琐又重复 借助maven的archetype来帮你自动生成一个初始项目吧 接入步骤 按照上面的流程我们已经建好了项目 在项目目录下执行 mvn archetype:create-from-project,生成的target就是你的脚手架项目 cd target/generated-sources/archetype 目录下,执行mvn install 就把archetype放入了本地仓库了,可以进行使用了 为了deploy到远程仓库中,需要在target/generated-sources/archetype 目录下的pom.xml中加入自己的远程仓库的地址,然后在target/generated-sources/archetype 目录下mvn deploy就可以了 屏蔽掉部分不想打包进archetype的文件 要屏蔽部分文件夹时在pom中加入plugin <plugin> <artifactId>maven-archetype-plugin</artifactId> <version>3.0.1</version> <configuration> <propertyFile>archetype.properties</propertyFile> </configuration> </plugin> 新建archetype.properties文件,配置要忽略的通配符excludePatterns=/.idea/,**.iml 怎么使用archetype 创建项目在idea中,在点击file-> new-> project后弹出的对话框中选择maven 在create from archetype打勾,点击Add archetype加入创建好的archetype 填写对应的groupId,artifaceId,version后在列表中选择已有的archetype 按引导进行后续步骤的创建,然后就会自动生成跟你项目一样的啦 跨store的访问 什么是跨store访问 在上面我们有这样的代码 const routerStore = new RouterStore() rootStore['app'] = new AppStore() routerStore['routing'] = routerStore 有时候我们往往需要在一个store的方法中去访问下别的store的内容,这个时候就是跨store的访问,就需要在初始化时将rootStore传给这个store,通过rootStore去访问,改写index.js rootStore['app'] = new AppStore(rootStore) 改写AppStore.js,增加构造函数 constructor(rootStore) { this.rootStore = rootStore } 这样就可以在AppStore.js的函数中通过this.rootStore 去获取所有store的json,从而访问所有的store了

优秀的个人博客,低调大师

SpringBoot 2.0整合jackson配置日期格式化和反序列化

网上杂七杂八的说法不一,大多数都是抄来抄去,没有实践,近期在项目频繁遇到boot+jackson处理日期的问题,故开此贴。 首先是POM <?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>io.cj.learning</groupId> <artifactId>boot2exam</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>boot2exam</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <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.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 然后是yml文件 (当然yml这东西很多人不喜欢,我也写了个properties版本的) spring: jackson: #参数意义: #JsonInclude.Include.ALWAYS 默认 #JsonInclude.Include.NON_DEFAULT 属性为默认值不序列化 #JsonInclude.Include.NON_EMPTY 属性为 空(””) 或者为 NULL 都不序列化 #JsonInclude.Include.NON_NULL 属性为NULL 不序列化 default-property-inclusion: ALWAYS time-zone: GMT+8 date-format: yyyy-MM-dd HH:mm:ss 上面配置对应的properties文件版本: #jackson相关配置 spring.jackson.date-format = yyyy-MM-dd HH:mm:ss #时区必须要设置 spring.jackson.time-zone= GMT+8 #ALWAYS的意思是即时属性为null,仍然也会输出这个key spring.jackson.default-property-inclusion=ALWAYS 然后来定义一个Controller和JAVA Bean Controller: package io.cj.learning.boot2exam.controller; import io.cj.learning.boot2exam.model.DateFormatTest; import org.springframework.web.bind.annotation.*; import java.text.SimpleDateFormat; import java.util.Date; @RestController @RequestMapping(value="/test") public class TestController { /** * 测试时间序列化, java.util.date 类型 -> String * @return */ @RequestMapping(value="/dateFormatTest", method = RequestMethod.GET) @ResponseBody public DateFormatTest dateFormatTest(){ DateFormatTest dateFormatTest = new DateFormatTest(); dateFormatTest.setIntProperties(100); dateFormatTest.setDateProperties(new Date()); return dateFormatTest; } /** * 测试时间反序列化 String -> java.util.date 类型 */ @RequestMapping(value="/dateFormatTest2" ,method = RequestMethod.POST) public void dateFormatTest2(@RequestBody DateFormatTest model){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(model.getIntProperties()); System.out.println(sdf.format(model.getDateProperties())); System.out.println(model.getStrProperties()); } } Java Bean: package io.cj.learning.boot2exam.model; import java.util.Date; /** * 一个model,里面带一个日期类型 */ public class DateFormatTest { private Integer intProperties; private Date dateProperties; private String strProperties; public Integer getIntProperties() { return intProperties; } public void setIntProperties(Integer intProperties) { this.intProperties = intProperties; } public Date getDateProperties() { return dateProperties; } public void setDateProperties(Date dateProperties) { this.dateProperties = dateProperties; } public String getStrProperties() { return strProperties; } public void setStrProperties(String strProperties) { this.strProperties = strProperties; } } 启动主类: package io.cj.learning.boot2exam; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Boot2examApplication { public static void main(String[] args) { SpringApplication.run(Boot2examApplication.class, args); } } 测试: 试一下,首先是日期序列化, 请求一下试试 然后是反序列化,也请求一个试试:

优秀的个人博客,低调大师

SpringCloud+SpringBoot+mybatis分布式微服务云架构开发Web应用

在完成配置之后,举一个简单的例子,在快速入门工程的基础上,举一个简单的示例来通过Thymeleaf渲染一个页面。 @Controller public class HelloController { @RequestMapping("/") public String index(ModelMap map) { // 加入一个属性,用来在模板中读取 map.addAttribute("host", "http://blog.didispace.com"); // return模板文件的名称,对应src/main/resources/templates/index.html return "index"; } } <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8" /> <title></title> </head> <body> <h1 th:text="${host}">Hello World</h1> </body> </html> 如上页面,直接打开html页面展现Hello World,但是启动程序后,访问http://localhost:8080/,则是展示Controller中host的值:http://blog.didispace.com,做到了不破坏HTML自身内容的数据逻辑分离。 更多Thymeleaf的页面语法,还请访问Thymeleaf的官方文档查询使用。 Thymeleaf的默认参数配置 如有需要修改默认配置的时候,只需复制下面要修改的属性到application.properties中,并修改成需要的值,如修改模板文件的扩展名,修改默认的模板路径等。 # Enable template caching. spring.thymeleaf.cache=true # Check that the templates location exists. spring.thymeleaf.check-template-location=true # Content-Type value. spring.thymeleaf.content-type=text/html # Enable MVC Thymeleaf view resolution. spring.thymeleaf.enabled=true # Template encoding. spring.thymeleaf.encoding=UTF-8 # Comma-separated list of view names that should be excluded from resolution. spring.thymeleaf.excluded-view-names= # Template mode to be applied to templates. See also StandardTemplateModeHandlers. spring.thymeleaf.mode=HTML5 # Prefix that gets prepended to view names when building a URL. spring.thymeleaf.prefix=classpath:/templates/ # Suffix that gets appended to view names when building a URL. spring.thymeleaf.suffix=.html spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved. 支持JSP的配置Spring Boot并不建议使用,但如果一定要使用,可以参考此工程作为脚手架:JSP支持 完整项目的源码来源 技术支持1791743380

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册