springboot(二):web综合开发

xiaoxuelilei xiaoxuelilei     2022-12-04     428

关键词:

SpringBoot ( 二 ) :web 综合开发

来源:纯洁的微笑,

www.ityouknow.com/springboot/2016/02/03/springboot(二)-web综合开发.html

如有好文章投稿,请点击 → 这里了解详情


上篇文章介绍了Spring boot初级教程 :《 spring boot(一):入门篇 》,方便大家快速入门、了解实践Spring boot特性;本篇文章接着上篇内容继续为大家介绍spring boot的其它特性(有些未必是spring boot体系桟的功能,但是是spring特别推荐的一些开源技术本文也会介绍),对了这里只是一个大概的介绍,特别详细的使用我们会在其它的文章中来展开说明。


web开发


spring boot web开发非常的简单,其中包括常用的json输出、filters、property、log等。


json 接口开发


在以前的spring 开发的时候需要我们提供json接口的时候需要做那些配置呢?


  • 添加 jackjson 等相关jar包

  • 配置spring controller扫描

  • 对接的方法添加@ResponseBody


就这样我们会经常由于配置错误,导致406错误等等,spring boot如何做呢,只需要类添加 @RestController 即可,默认类中的方法都会以json的格式返回。


@RestController

public class HelloWorldController

    @RequestMapping("/getUser")

    public User getUser()

        User user=new User();

        user.setUserName("小明");

        user.setPassWord("xxxx");

        return user;

   


如果我们需要使用页面开发只要使用 @Controller ,下面会结合模板来说明。


自定义Filter


我们常常在项目中会使用filters用于录调用日志、排除有XSS威胁的字符、执行权限验证等等。Spring Boot自动添加了OrderedCharacterEncodingFilter和HiddenHttpMethodFilter,并且我们可以自定义Filter。


两个步骤:


  1. 实现Filter接口,实现Filter方法

  2. 添加@Configurationz 注解,将自定义Filter加入过滤链


好吧,直接上代码。


@Configuration

public class WebConfiguration

    @Bean

    public RemoteIpFilter remoteIpFilter()

        return new RemoteIpFilter();

   

     

    @Bean

    public FilterRegistrationBean testFilterRegistration()

 

        FilterRegistrationBean registration = new FilterRegistrationBean();

        registration.setFilter(new MyFilter());

        registration.addUrlPatterns("/*");

        registration.addInitParameter("paramName", "paramValue");

        registration.setName("MyFilter");

        registration.setOrder(1);

        return registration;

   

     

    public class MyFilter implements Filter

        @Override

        public void destroy()

            // TODO Auto-generated method stub

       

 

        @Override

        public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)

                throws IOException, ServletException

            // TODO Auto-generated method stub

            HttpServletRequest request = (HttpServletRequest) srequest;

            System.out.println("this is MyFilter,url :"+request.getRequestURI());

            filterChain.doFilter(srequest, sresponse);

       

 

        @Override

        public void init(FilterConfig arg0) throws ServletException

            // TODO Auto-generated method stub

       

   


自定义Property


在web开发的过程中,我经常需要自定义一些配置文件,如何使用呢?


配置在application.properties中。


com.neo.title=纯洁的微笑

com.neo.description=分享生活和技术


自定义配置类


@Component

public class NeoProperties

    @Value("$com.neo.title")

    private String title;

    @Value("$com.neo.description")

    private String description;

 

    //省略getter settet方法

 


log配置


配置输出的地址和输出级别:


logging.path=/user/local/log

logging.level.com.favorites=DEBUG

logging.level.org.springframework.web=INFO

logging.level.org.hibernate=ERROR


path为本机的log地址,logging.level 后面可以根据包路径配置不同资源的log级别。


数据库操作


在这里我重点讲述mysql、spring data jpa的使用,其中mysql 就不用说了大家很熟悉,jpa是利用Hibernate生成各种自动化的sql,如果只是简单的增删改查,基本上不用手写了,spring内部已经帮大家封装实现了。


下面简单介绍一下如何在spring boot中使用。


1、添加相jar包


<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

 <dependency>

    <groupId>mysql</groupId>

    <artifactId>mysql-connector-java</artifactId>

</dependency>


2、添加配置文件


spring.datasource.url=jdbc:mysql://localhost:3306/test

spring.datasource.username=root

spring.datasource.password=root

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

 

spring.jpa.properties.hibernate.hbm2ddl.auto=update

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

spring.jpa.show-sql= true


其实这个hibernate.hbm2ddl.auto参数的作用主要用于:自动创建|更新|验证数据库表结构,有四个值:


  1. create: 每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。

  2. create-drop :每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。

  3. update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据 model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等 应用第一次运行起来后才会。

  4. validate :每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。


dialect 主要是指定生成表名的存储引擎为InneoDB show-sql 是否打印出自动生产的SQL,方便调试的时候查看。


3、添加实体类和Dao


@Entity

public class User implements Serializable

 

    private static final long serialVersionUID = 1L;

    @Id

    @GeneratedValue

    private Long id;

    @Column(nullable = false, unique = true)

    private String userName;

    @Column(nullable = false)

    private String passWord;

    @Column(nullable = false, unique = true)

    private String email;

    @Column(nullable = true, unique = true)

    private String nickName;

    @Column(nullable = false)

    private String regTime;

 

    //省略getter settet方法、构造方法

 


dao只要继承JpaRepository类就可以,几乎可以不用写方法,还有一个特别有尿性的功能非常赞,就是可以根据方法名来自动的生产SQL,比如findByUserName 会自动生产一个以 userName 为参数的查询方法,比如 findAlll 自动会查询表里面的所有数据,比如自动分页等等。


Entity中不映射成列的字段得加@Transient 注解,不加注解也会映射成列。


public interface UserRepository extends JpaRepository<User, Long>

    User findByUserName(String userName);

    User findByUserNameOrEmail(String username, String email);


4、测试


@RunWith(SpringJUnit4ClassRunner.class)

@SpringApplicationConfiguration(Application.class)

public class UserRepositoryTests

 

    @Autowired

    private UserRepository userRepository;

 

    @Test

    public void test() throws Exception

        Date date = new Date();

        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);        

        String formattedDate = dateFormat.format(date);

         

        userRepository.save(new User("aa1", "aa@126.com", "aa", "aa123456",formattedDate));

        userRepository.save(new User("bb2", "bb@126.com", "bb", "bb123456",formattedDate));

        userRepository.save(new User("cc3", "cc@126.com", "cc", "cc123456",formattedDate));

 

        Assert.assertEquals(9, userRepository.findAll().size());

        Assert.assertEquals("bb", userRepository.findByUserNameOrEmail("bb", "cc@126.com").getNickName());

        userRepository.delete(userRepository.findByUserName("aa1"));

   

 


当让 spring data jpa 还有很多功能,比如封装好的分页,可以自己定义SQL,主从分离等等,这里就不详细讲了。


thymeleaf模板


Spring boot 推荐使用来代替jsp,thymeleaf模板到底是什么来头呢,让spring大哥来推荐,下面我们来聊聊。


Thymeleaf 介绍


Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。


好了,你们说了我们已经习惯使用了什么 velocity,FreMaker,beetle之类的模版,那么到底好在哪里呢? 比一比吧 Thymeleaf是与众不同的,因为它使用了自然的模板技术。这意味着Thymeleaf的模板语法并不会破坏文档的结构,模板依旧是有效的XML文档。模板还可以用作工作原型,Thymeleaf会在运行期替换掉静态值。Velocity与FreeMarker则是连续的文本处理器。 下面的代码示例分别使用Velocity、FreeMarker与Thymeleaf打印

springboot-web综合开发(转)(代码片段)

Web开发SpringBootWeb开发非常的简单,其中包括常用的json输出、filters、property、log等json接口开发在以前使用Spring开发项目,需要提供json接口时需要做哪些配置呢添加jackjson等相关jar包配置SpringController扫描对接的方法添加@ResponseBody... 查看详情

springboot

参考:http://www.ityouknow.com/springboot(一):入门篇springboot(二):web综合开发springboot(三):SpringBoot中Redis的使用springboot(四):thymeleaf使用详解springboot(五):springdatajpa的使用springboot(六):如何优雅的使用mybatisspringboot(七):sp 查看详情

springboot-web综合

自定义FilterpublicclassMyFilterimplementsFilter{@Overridepublicvoidinit(FilterConfigfilterConfig)throwsServletException{System.out.println("filterinit");}@OverridepublicvoiddoFilter(ServletRequestservlet 查看详情

springboot

Web综合开发Web开发SpringBootWeb开发非常的简单,其中包括常用的json输出filters、property、log等 json接口开发在以前的spring开发的时候需要我们提供json接口的时候需要做那些配置呢:1.添加jackjson等相关jar包2.配置springcontroller扫描3... 查看详情

springboot的web部署,springboot开发非web程序

目录:1、SpringBoot的web项目部署为war2、SpringBoot的web项目部署为jar3、SpringBoot开发非Web程序   3.1、方式一:利用main()方法   3.2、方式二:通过springboot启动加载类CommandLineRunner#run()1、SpringBoot的web项目部署为war&... 查看详情

springboot1.5.4之web开发

上一篇:springboot1.5.4入门和原理(二)springBoot之web开发更多更详细的配置参考文件:application.properties和《SpringBoot之application配置详解》(新版本新增属性缺失) 或参考官网http://projects.spring.io/spring-boot/注意:SpringBoot工程默... 查看详情

零基础学习web前端开发:html第一部分基础知识的综合案例

零基础学习WEB前端开发(一):网站及web标准简介零基础学习WEB前端开发(二):HTML标签及开发工具零基础学习WEB前端开发(三):VsCode工具生成的代码框架分析零基础学习WEB前端开发(四):HTML文本编辑标签及分块标签零... 查看详情

springboot(10):web开发-文件上传

一、简介SpringBoot默认使用springMVC包装好的解析器进行上传二、代码实现2.1、from表单<form method="POST" enctype="multipart/form-data" action="/file/upload">    文件:<input type="file" 查看详情

springboot---web应用开发-文件上传

一、SpringBoot默认使用springMVC包装好的解析器进行上传二、添加代码<formmethod="POST"enctype="multipart/form-data"action="/file/upload">文件:<inputtype="file"name="roncooFile"/><inputtype="submit"value="上传"/>& 查看详情

springboot:web开发-servlets,filters,listeners

一、说明Web开发使用Controller基本上可以完成大部分需求,但是我们还可能会用到Servlet、Filter、Listener等等二、在springboot中的三种实现方式2.1、代码CustomServlet.java:package com.example.demo.utils.servlet;import javax.servlet.ServletExceptio 查看详情

springboot--web应用开发-servlets,filters,listeners

...,但是我们还可能会用到Servlet、Filter、Listener等等二.在springboot中的三种实现方式 方法一:通过注册ServletRegistrationBean、FilterRegistrationBean和ServletListenerRegistrationBean获得控制servlet类:package 查看详情

springboot---web开发第一部分(代码片段)

Web开发Web开发简介SpringBoot对静态资源映射规则webjars官网链接映射规则一:通过webjars以jar包的方式引入静态资源,如jquery,bootstrap等映射规则二:"/**"访问当前项目的任何资源(静态资源的文件夹)首页(欢迎页)࿱... 查看详情

springboot系列二:搭建自己的第一个springboot程序(代码片段)

...//projects.spring.io/spring-boot/#quick-start)1、新建一个maven工程springbootfirst2、如果要想开发SpringBoot程序只需要按照官方给出的要求配置一个父pom(spring-boot-starter-parent)和添加web开发的支持(spring-boot-starter-web)即可。1&l 查看详情

springboot-web开发(代码片段)

文章目录一、静态资源映射1、webjars2、访问当前项目编写的静态资源3、欢迎页4、图标二、thymeleaf1、引入依赖2、更改版本3、视图解析4、thymeleaf使用(1)添加命名空间(2)常用语法三、MVC配置1、拓展mvc配置2、全面接管MVC四、引入资... 查看详情

二spring和springboot区别

...WebSecurityConfigurerAdapter类,添加@EnableWebSecurity注解Spring和SpringBoot中应用程序引导的基本区别在于servlet。Spring使用Web.xml或SpringServletContainerInitiators作为它的引导入口点。Spring支持Web.xml引导方式以及最新的Servlet3+方法。Web.xml分步骤... 查看详情

springboot的自动配置原理

目录一、SpringBoot自动配置的理解二、SpringBoot的自动配置示例1、官方文档说明2、以web开发场景为例,引入web的Starter,查看spring-boot-starter-web给我们引入了什么三、spring-boot-autoconfiguration包含了什么一、SpringBoot自动配置的... 查看详情

springboot2之web开发(上)——之静态资源和请求参数处理(代码片段)

SpringBoot2之web开发(上)——之静态资源和请求参数处理一、SpringMVC自动配置概览二、简单功能分析2.1静态资源访问2.2欢迎页支持2.3自定义Favicon2.4静态资源配置原理(源码分析)2.4.1addResourceHandlers方法(静态... 查看详情

springboot的web开发

...Web开发的核心内容主要包括内嵌的Servlet容器和SpringMVC。SpringBoot使用起来非常简洁,大部分配置都有SpringBoot自动装配。SpringBoot的web支持SpringBoot提供了spring-boot-starter-web为web开发予以支持,而这个启动器内嵌了Tomcat以及Spri... 查看详情