spring-boot3代码

Posted 672530440

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring-boot3代码相关的知识,希望对你有一定的参考价值。

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
@SpringBootApplication
public 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(Map<String,Object> map){
        //返回的是ModelAndView对象;
        ModelAndView mv = new ModelAndView("hello");//hello是view的名称
        return mv;
        
        //map.put("name","Andy");
        //return "hello";
    }
    
    @RequestMapping("/helloFtl")
    public String helloFtl(Map<String,Object> 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/hello


1、当我们修改了方法的返回值,是能够进行热部署的;
2、当我们重新创建了一个方法,是能够进行热部署的;
3、当我们重新创建了一个Class,是能够进行热部署的;


1、第1节 Spring Boot之Hello World
1、新建一个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注解.
 */
@ControllerAdvice
public 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日
 */
@Entity
public 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 Iterable<Cat> getAll(){
        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注解,标注这是一个持久化操作对象.
 * 数据库持久化操作类
 */
@Repository
public class CatDao {
    
    @Resource
    private JdbcTemplate jdbcTemplate;
    
    public Cat selectByCatName(String catName){
        
        /**
         * 1、定义一个Sql语句;
         * 2、定义一个RowMapper.
         * 3、执行查询方法.
         */
        String sql = "select *from cat where cat_name=?";
        RowMapper<Cat> rowMapper = 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<Cat, Integer>{
    
    
    /**
     * 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<Cat, Integer>{

}

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;

@Service
public 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 Iterable<Cat> getAll(){
        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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
     <h1>
         Hello,thymeleaf
         <br />
         This is my first thymeleaf demo.
         
         
         <hr />
         
         welcome <span th:text="${name}"></span>
         
     </h1>
</body>
</html>

helloFtl.ftl

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

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=<encoding> 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=false
spring.freemarker.cache=false
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




########################################################
###datasource -- \\u6307\\u5b9amysql\\u6570\\u636e\\u5e93\\u8fde\\u63a5\\u4fe1\\u606f.
########################################################
spring.datasource.url = jdbc:mysql://localhost:3306/spboot1
spring.datasource.username = root
spring.datasource.password = 
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10


########################################################
### Java Persistence Api --  Spring jpa\\u7684\\u914d\\u7f6e\\u4fe1\\u606f.
########################################################
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.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

<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>com.kfit</groupId>
    <artifactId>spring-boot-hello810</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-hello</name>
    <url>http://maven.apache.org</url>


    <!-- spring boot 父节点依赖,引入这个之后相关的引入就不需要添加version配置,spring boot会自动选择最合适的版本进行添加。 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
    </parent>



    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!-- 指定一下jdk的版本 ,这里我们使用jdk 1.8 ,默认是1.6 -->
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <!-- spring-boot-starter-web: MVC,AOP的依赖包.... -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!-- <version></version> 由于我们在上面指定了 parent(spring boot) -->
        </dependency>


        <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-loader</artifactId> 
            </dependency> -->



        <!-- 添加fastjson 依赖包. -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.15</version>
        </dependency>

        <!-- spring boot devtools 依赖包. -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>true</scope>
        </dependency>

        <!-- 添加MySQL数据库驱动依赖包. -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- 添加Spring-data-jpa依赖. -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- 引入了spring-data-jpa,不需要引入 <dependency> <groupId>org.springframework.boot</groupId> 
            <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> -->

        <!-- 添加thymeleaf的依赖. -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>



        <!-- freemarker的依赖配置信息 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>


    </dependencies>

    <!-- 构建节点. -->
    <build>
        <plugins>


            <!-- 在这里添加springloader plugin <plugin> <groupId>org.springframework.boot</groupId> 
                <artifactId>spring-boot-maven-plugin </artifactId> <dependencies> <dependency> 
                <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId> 
                <version>1.2.4.RELEASE</version> </dependency> </dependencies> <executions> 
                <execution> <goals> <goal>repackage</goal> </goals> <configuration> <classifier>exec</classifier> 
                </configuration> </execution> </executions> </plugin> -->

            <!-- 这是spring boot devtool plugin -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <!--fork : 如果没有该项配置,肯呢个devtools不会起作用,即应用不会restart -->
                    <fork>true</fork>
                </configuration>
            </plugin>


        </plugins>
        
        <defaultGoal>compile</defaultGoal>
    </build>


</project>

 

以上是关于spring-boot3代码的主要内容,如果未能解决你的问题,请参考以下文章

使用片段时 Intellij 无法正确识别 Thymeleaf 模型变量

VSCode自定义代码片段3——url大全

VSCode自定义代码片段3——url大全

VSCode自定义代码片段3——url大全

sublime text 3 添加代码片段

sublime text 3 添加 javascript 代码片段 ( snippet )