App.java
package com.kfit;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.autoconfigure.web.HttpMessageConverters;import org.springframework.context.annotation.Bean;import org.springframework.http.converter.HttpMessageConverter;import com.alibaba.fastjson.serializer.SerializerFeature;import com.alibaba.fastjson.support.config.FastJsonConfig;import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;/** * 在这里我们使用@SpringBootApplication指定这是一个 spring boot的应用程序. *///extends WebMvcConfigurerAdapter@SpringBootApplicationpublic class App{ /** * 在这里我们使用 @Bean注入 fastJsonHttpMessageConvert * @return */ @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { // 1、需要先定义一个 convert 转换消息的对象; FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); //2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据; FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //3、在convert中添加配置信息. fastConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter converter = fastConverter; return new HttpMessageConverters(converter); } /** * 这是springloader的配置方式:-javaagent:.\lib\springloaded-1.2.4.RELEASE.jar -noverify * @param args */ public static void main(String[] args) { /* * 在main方法进行启动我们的应用程序. */ SpringApplication.run(App.class, args); }}
TemplatesController.java
package com.kfit;import java.util.Map;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;/** * 注意: * 1.在Thymeleaf 模板文件中,标签是需要闭合的,3.0之前是需要闭合的 * 2. thymeleaf 3.0+ 是可以不强制要求闭合的。 * * 3. 支持同时使用多个模板引擎,比如:thymeleaf和freemarker 可以并存。 * */@Controller@RequestMapping("/templates")public class TemplatesController { /** * 映射地址是:/templates/hello * http://127.0.0.1:8080/templates/hello */ @RequestMapping("/hello") public String hello(Mapmap){ //返回的是ModelAndView对象; ModelAndView mv = new ModelAndView("hello");//hello是view的名称 return mv; //map.put("name","Andy"); //return "hello"; } @RequestMapping("/helloFtl") public String helloFtl(Map map){ //http://127.0.0.1:8080/templates/helloFtl map.put("name","Andy"); return "helloFtl"; } }
总结.txt
------在spring boot中如何使用模板引擎的步骤:1、在pom.xml文件中添加相应的依赖包,thymeleaf和freemarker;2、在application.properties文件中添加配置信息,开发过程建议关闭缓存;3、编写模板文件,thymeleaf的默认的后缀是.html,freemarker的默认后缀是.ftl;4、编写访问模板文件的controller建立请求映射地址TemplatesController;-----------------------------------同时 我们知道了:thymeleaf和freemarker可以并存使用。----------代码Hello World 之 404 ------1、确认访问地址是否正确: (1)确认端口号,默认是8080,这个可以在启动的控制台进行查看; (2)确认访问的URI地址是否填写正确,这个在启动的控制台查看是否被映射了。2、确定注解是否正确,使用@RestController而不是@Controller, 另外@RestController等价于@Controller和@ResponseBody; 3、确定包的路径是否正确 我们需要知道的是:Spring Boot默认情况下可以扫描到的是 @SpringBootApplication所在的类的同包或者子包下的类。 4、 确定类引入的包的路径是否正确@RestController:import org.springframework.web.bind.annotation.RestController@RequestMapping("/helo33"):import org.springframework.web.bind.annotation.RequestMapping问题的提出:默认的端口号是8080,那么如何进行修改为80或者8081呢?问题的提出:如何配置上下文(项目的名称)? http://127.0.0.1:8080/springboot/hello1、当我们修改了方法的返回值,是能够进行热部署的;2、当我们重新创建了一个方法,是能够进行热部署的;3、当我们重新创建了一个Class,是能够进行热部署的;1、第1节 Spring Boot之Hello World1、新建一个HelloController;2、编写Spring Boot 启动类;3、进行访问测试,默认的端口号是8080;
GlobalDefaultExceptionHandler.java
package com.kfit.config;import javax.servlet.http.HttpServletRequest;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;/** * 1、新建一个Class,这里取名为GlobalDefaultExceptionHandler * 2、在class上添加注解,@ControllerAdvice; * 3、在class中添加一个方法 * 4、在方法上添加@ExcetionHandler拦截相应的异常信息; * 5、如果返回的是View -- 方法的返回值是ModelAndView; * 6、如果返回的是String或者是Json数据,那么需要在方法上添加@ResponseBody注解. */@ControllerAdvicepublic class GlobalDefaultExceptionHandler { @ExceptionHandler(Exception.class) @ResponseBody public String defaultExceptionHandler(HttpServletRequest req,Exception e){ //是返回的String. //ModelAndView -- 介绍 模板引擎...?// ModelAndView mv = new ModelAndView();// mv.setViewName(viewName); return "对不起,服务器繁忙,请稍后再试!"; } }
Cat.java
package com.kfit.demo.bean;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;/** * 创建了一个实体类。 * * 如何持久化呢? * * 1、使用@Entity进行实体类的持久化操作,当JPA检测到我们的实体类当中有 * * @Entity 注解的时候,会在数据库中生成对应的表结构信息。 * * * 如何指定主键以及主键的生成策略? * * 2、使用@Id指定主键. * * * * @author Angel -- 守护天使 * @version v.0.1 * @date 2016年12月17日 */@Entitypublic class Cat { /** * 使用@Id指定主键. * * 使用代码@GeneratedValue(strategy=GenerationType.AUTO) * 指定主键的生成策略,mysql默认的是自增长。 * */ @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id;//主键. private String catName;//姓名. cat_name private int catAge;//年龄. cat_age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCatName() { return catName; } public void setCatName(String catName) { this.catName = catName; } public int getCatAge() { return catAge; } public void setCatAge(int catAge) { this.catAge = catAge; } }
CatController.java
package com.kfit.demo.controller;import javax.annotation.Resource;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.kfit.demo.bean.Cat;import com.kfit.demo.service.CatService;@RestController@RequestMapping("/cat")public class CatController { @Resource private CatService catService; @RequestMapping("/save") public String save(){ Cat cat = new Cat(); cat.setCatName("jack"); cat.setCatAge(3); catService.save(cat); return "save ok."; } @RequestMapping("/delete") public String delete(){ catService.delete(1); return "delete ok"; } @RequestMapping("/getAll") public IterablegetAll(){ return catService.getAll(); } @RequestMapping("/findByCatName") public Cat findByCatName(String catName){ return catService.findByCatName(catName); } @RequestMapping("/findByCatName2") public Cat findByCatName2(String catName){ System.out.println("CatController.findByCatName2()"); return catService.findByCatName2(catName); } @RequestMapping("/selectByCatName") public Cat selectByCatName(String catName){ return catService.selectByCatName(catName); } }
CatDao.java
package com.kfit.demo.dao;import javax.annotation.Resource;import org.springframework.jdbc.core.BeanPropertyRowMapper;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.RowMapper;import org.springframework.stereotype.Repository;import com.kfit.demo.bean.Cat;/** * 使用@Repository注解,标注这是一个持久化操作对象. * 数据库持久化操作类 */@Repositorypublic class CatDao { @Resource private JdbcTemplate jdbcTemplate; public Cat selectByCatName(String catName){ /** * 1、定义一个Sql语句; * 2、定义一个RowMapper. * 3、执行查询方法. */ String sql = "select *from cat where cat_name=?"; RowMapperrowMapper = new BeanPropertyRowMapper<>(Cat.class); Cat cat = jdbcTemplate.queryForObject(sql, new Object[]{catName}, rowMapper); return cat; } }
Cat2Repository.java
package com.kfit.demo.repository;import org.springframework.data.jpa.repository.Query;import org.springframework.data.repository.PagingAndSortingRepository;import org.springframework.data.repository.query.Param;import com.kfit.demo.bean.Cat;//用户数据库的持久化操作public interface Cat2Repository extends PagingAndSortingRepository{ /** * 1/ 查询方法 以 get | find | read 开头. * 2/ 涉及查询条件时,条件的属性用条件关键字连接,要注意的是条件属性以首字母大写。 */ //根据catName进行查询 : 根据catName进行查询. public Cat findByCatName(String catName); /** * 如何编写JPQL语句, * Hibernate -- HQL语句. * JPQL 语句 和HQL语句是类似的. */ @Query("from Cat where catName=:cn") public Cat findMyCatName(@Param("cn")String catName);}
CatRepository.java
package com.kfit.demo.repository;import org.springframework.data.repository.CrudRepository;import com.kfit.demo.bean.Cat;/** * Repository -- 是接口 ,不是class. * @author Angel -- 守护天使 * 用户数据库的持久化操作 */public interface CatRepository extends CrudRepository{}
CatService.java
package com.kfit.demo.service;import javax.annotation.Resource;import javax.transaction.Transactional;import org.springframework.stereotype.Service;import com.kfit.demo.bean.Cat;import com.kfit.demo.dao.CatDao;import com.kfit.demo.repository.Cat2Repository;import com.kfit.demo.repository.CatRepository;@Servicepublic class CatService { @Resource private CatRepository catRepository; @Resource private Cat2Repository cat2Repository; @Resource private CatDao catDao; /** * save,update ,delete 方法需要绑定事务. * * 使用@Transactional进行事务的绑定. * * @param cat */ //保存数据. @Transactional public void save(Cat cat){ catRepository.save(cat); } //删除数据》 @Transactional public void delete(int id){ catRepository.delete(id); } //查询数据. public IterablegetAll(){ return catRepository.findAll(); } public Cat findByCatName(String catName){ return cat2Repository.findByCatName(catName); } public Cat findByCatName2(String catName){ return cat2Repository.findMyCatName(catName); } public Cat selectByCatName(String catName){ return catDao.selectByCatName(catName); }}
hello.html
Insert title here Hello,thymeleaf This is my first thymeleaf demo.
welcome
helloFtl.ftl
Insert title here hello ${name}
application.properties
###########################################################server \u914d\u7f6e\u4fe1\u606f.#########################################################spring boot\u9ed8\u8ba4\u7aef\u53e3\u53f7\u662f8080#server.port = 8081#spring boot\u9ed8\u8ba4\u7684context-path \u662f /#server.context-path = /springboot#server.port=8080#server.address= # bind to a specific NIC#server.session-timeout= # session timeout in seconds#the context path, defaults to '/'#server.context-path=/spring-boot#server.servlet-path= # the servlet path, defaults to '/'#server.tomcat.access-log-pattern= # log pattern of the access log#server.tomcat.access-log-enabled=false # is access logging enabled#server.tomcat.protocol-header=x-forwarded-proto # ssl forward headers#server.tomcat.remote-ip-header=x-forwarded-for#server.tomcat.basedir=/tmp # base dir (usually not needed, defaults to tmp)#server.tomcat.background-processor-delay=30; # in seconds#server.tomcat.max-threads = 0 # number of threads in protocol handler#server.tomcat.uri-encoding = UTF-8 # character encoding to use for URL decoding###########################################################THYMELEAF (ThymeleafAutoConfiguration)#########################################################spring.thymeleaf.prefix=classpath:/templates/#spring.thymeleaf.suffix=.html#spring.thymeleaf.mode=HTML5#spring.thymeleaf.encoding=UTF-8# ;charset=is added#spring.thymeleaf.content-type=text/html # set to false for hot refresh#\u5f00\u53d1\u8fc7\u7a0b\u5efa\u8bae\u5173\u95ed\u7f13\u5b58.spring.thymeleaf.cache=false ###########################################################FREEMARKER (FreeMarkerAutoConfiguration)########################################################spring.freemarker.allow-request-override=falsespring.freemarker.cache=falsespring.freemarker.check-template-location=truespring.freemarker.charset=UTF-8spring.freemarker.content-type=text/htmlspring.freemarker.expose-request-attributes=falsespring.freemarker.expose-session-attributes=falsespring.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###########################################################datasource -- \u6307\u5b9amysql\u6570\u636e\u5e93\u8fde\u63a5\u4fe1\u606f.########################################################spring.datasource.url = jdbc:mysql://localhost:3306/spboot1spring.datasource.username = rootspring.datasource.password = spring.datasource.driverClassName = com.mysql.jdbc.Driverspring.datasource.max-active=20spring.datasource.max-idle=8spring.datasource.min-idle=8spring.datasource.initial-size=10########################################################### Java Persistence Api -- Spring jpa\u7684\u914d\u7f6e\u4fe1\u606f.######################################################### Specify the DBMSspring.jpa.database = MYSQL# Show or not log for each sql queryspring.jpa.show-sql = true# Hibernate ddl auto (create, create-drop, update)spring.jpa.hibernate.ddl-auto = update# Naming strategy#[org.hibernate.cfg.ImprovedNamingStrategy #org.hibernate.cfg.DefaultNamingStrategy]spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy# stripped before adding them to the entity manager)spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
pom.xml
4.0.0 com.kfit spring-boot-hello810 0.0.1-SNAPSHOT jar spring-boot-hello http://maven.apache.org org.springframework.boot spring-boot-starter-parent 1.4.1.RELEASE UTF-8 1.8 org.springframework.boot spring-boot-starter-web com.alibaba fastjson 1.2.15 org.springframework.boot spring-boot-devtools true true mysql mysql-connector-java org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-freemarker org.springframework.boot spring-boot-maven-plugin true compile