springboot(2): web Integrated Development

Keywords: Spring Thymeleaf Hibernate Java

The previous article introduced the Spring boot preliminary tutorial: spring boot(1): introduction, to facilitate you to quickly get started and understand the practical Spring boot features; the last part of this article continues to introduce other features of spring boot (some may not be the functions of spring boot system, but some open source technologies recommended by spring will also be introduced in this article). Here is only a general introduction, especially detailed use will be explained in other articles.

web development

spring boot web development is very simple, including common json output, filters, property, log, etc.

json interface development

What configurations were needed when we needed to provide json interfaces in previous spring development?
1. Add jackjson and other related jar packages
2. Configure spring controller scan
3. The docking method adds @ResponseBody

In this way, we will often cause 406 errors due to configuration errors and so on. How can spring boot do this? Just add @RestController to the class, and the default method in the class will be returned in json format.

@RestController

public class HelloWorldController {

    @RequestMapping("/getUser")

    public User getUser() {

    User user=new User();

    user.setUserName("Xiao Ming");

    user.setPassWord("xxxx");

        return user;

    }

}

If we need to use page development as long as @Controller is used, the following will be illustrated in conjunction with templates

Custom Filter

We often use filters in projects to record call logs, exclude XSS-threatened characters, perform permission validation, and so on. Spring Boot automatically adds Ordered Character Encoding Filter and Hidden HttpMethod Filter, and we can customize Filter.
Two steps:
1. Implementing Filter Interface and Filter Method
2. Add the @Configuration Z annotation and add custom Filter to the filter chain

Okay, go straight to the code.

@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

}

    }

}

Custom Property

In the process of web development, I often need to customize some configuration files. How to use them?

Configured in application.properties

com.neo.title = a pure smile

com.neo.description = Sharing life and technology

Custom Configuration Class

@Component

public class NeoProperties {

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

private String title;

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

private String description;

//Omitting getter settet method

}

log configuration

Configure the address and output level of the output

logging.path=/user/local/log

logging.level.com.favorites=DEBUG

logging.level.org.springframework.web=INFO

logging.level.org.hibernate=ERROR

The path is the log address of the machine, and the log level of different resources can be configured according to the package path after logging.level

Database operation

Here I will focus on the use of mysql and spring data jpa, among which mysql does not need to say that you are familiar with it. JPA is to use Hibernate to generate a variety of automated sql. If it is only a simple addition, deletion and modification, it basically does not need to be handwritten. Spring has already helped you encapsulate and implement.
Here's a brief introduction to how to use spring boot

1. Adding phase jar package

    <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. Adding Configuration Files

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

In fact, the function of this hibernate.hbm2ddl.auto parameter is mainly used for: automatically creating | updating | validating the database table structure, with four values:
1. create: Every time hibernate is loaded, the last generated table is deleted, and then the new table is regenerated according to your model class. Even if there are no changes twice, it should be executed in this way, which is an important reason for database table data loss.
2. create-drop: Each time hibernate is loaded, tables are generated according to the model class, but once session Factory is closed, tables are automatically deleted.
3. update: The most commonly used attribute is that when hibernate is first loaded, the structure of the table is automatically established according to the model class (provided that the database is established first), and then when hibernate is loaded, the table structure is automatically updated according to the model class. Even if the table structure changes, the rows in the table still exist without deleting the previous rows. It should be noted that when deployed to the server, the table structure will not be established immediately, but will not be established until the application runs for the first time.
4. validate: Every time hibernate is loaded, validation creates the database table structure, compares it with the tables in the database, does not create new tables, but inserts new values.

Diaect mainly specifies InneoDB as the storage engine for generating table names.
Whether show-sql prints out automatically produced SQL for easy debugging

3. Adding Entity Classes and 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;

//Omitting getter settet method and construction method

}

As long as dao inherits the JpaRepository class, it can hardly write methods. Another special urinary function is very good. It can automatically produce SQL according to the method name. For example, findByUserName will automatically produce a query method with userName as its parameter. For example, findAlll will automatically query all the data in the table, such as automatic paging and so on.

Fields not mapped to columns in Entity are annotated with @Transient, and columns are mapped without annotation.

public interface UserRepository extends JpaRepository<User, Long> {

    User findByUserName(String userName);

    User findByUserNameOrEmail(String username, String email);

4. Testing

@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"));

}

}

When spring data jpa has many other functions, such as encapsulated paging, self-defined SQL, master-slave separation and so on, we will not go into details here.

thymeleaf template

Spring boot recommendation to replace jsp,thymeleaf template in the end what is the origin, let spring elder brother to recommend, let's talk about next

Introduction to Thymeleaf

Thymeleaf is a template engine for rendering XML/XHTML/HTML5 content. Similar to JSP, Velocity, FreeMaker, etc., it can also be easily integrated with Web frameworks such as Spring MVC as a template engine for Web applications. Compared with other template engines, Thymeleaf's greatest feature is that it can open and display template pages correctly in browsers without launching the entire Web application.
Okay, you said what kind of velocity,FreMaker, beetle templates we're used to, so what's the good thing about that?
Make a comparison.
Thymeleaf is unique because it uses natural template technology. This means that Thymeleaf's template syntax does not destroy the structure of the document. Templates are still valid XML documents. Templates can also be used as working prototypes, and Thymeleaf replaces static values during runtime. Velocity and FreeMarker are continuous text processors.
The following code example prints a message using Velocity, FreeMarker, and Thymeleaf, respectively:

Velocity: <p>$message</p>

FreeMarker: <p>${message}</p>

Thymeleaf: <p th:text="${message}">Hello World!</p>
Note that because Thymeleaf uses an XML DOM parser, it is not suitable for processing large-scale XML files.

URL

URLs play an important role in Web application templates. It should be noted that Thymeleaf handles URLs through the grammar @{...}. Thymeleaf supports absolute path URLs:

<a th:href="@{http://www.thymeleaf.org}">Thymeleaf</a>

Conditional evaluation

<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

for loop

<tr th:each="prod : ${prods}">

      <td th:text="${prod.name}">Onions</td>

      <td th:text="${prod.price}">2.41</td>

      <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>

</tr>

Just list these.

Pages are prototypes

In the process of Web development, the writing of front-end engineers and back-end engineers is an indispensable topic. In the traditional Java Web development process, front-end engineers, like back-end engineers, need to install a complete development environment, and then modify templates and static resource files in various Java IDE s, start/restart/reload application servers, refresh pages to see the final effect. Fruit.
But in fact, the responsibilities of front-end engineers should focus more on the page itself rather than the back-end. It is difficult to do this with traditional Java template engines such as JSP and Velocity, because they must be rendered in the application server before they can see the results in the browser. Thymeleaf fundamentally overturns this process. Template rendering through attributes will not introduce any new ones. Labels that browsers cannot recognize, such as those in JSP, do not write expressions inside Tag. The whole page is opened directly as HTML files by browser, and the final effect can be seen almost. This greatly liberates the productivity of front-end engineers, whose final delivery is pure HTML/CSS/JavaScript files.

Gradle Construction Tool

spring project suggests using Gradle to build projects. Gradle is simpler than maven, and it is more time to build large and complex projects. Gradle has absorbed the characteristics of Maven and ant, but at present Maven is still the mainstream of Java, you can understand it first.
A project using gradle configuration

buildscript {

    repositories {

        maven { url "http://repo.spring.io/libs-snapshot" }

        mavenLocal()

    }

    dependencies {

        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.6.RELEASE")

    }

}

apply plugin: 'java'  //Add a Java plug-in to indicate that this is a Java project

apply plugin: 'spring-boot' //Add Spring-boot support

apply plugin: 'war'  //Add the War plug-in to export the War package

apply plugin: 'eclipse' //Add Eclipse plug-ins, Eclipse IDE support, and Intellij Idea as "idea"

war {

    baseName = 'favorites'

    version =  '0.1.0'

}

sourceCompatibility = 1.7  //Minimum Compatible Version JDK 1.7

targetCompatibility = 1.7  //Target compatible version JDK 1.7

repositories {     //  Maven Warehouse

    mavenLocal()        //Use local warehouse

    mavenCentral()      //Use central warehouse

    maven { url "http://repo.spring.io/libs-snapshot"}// / Using Remote Warehouse

}



dependencies {   // jar packages with various dependencies

    compile("org.springframework.boot:spring-boot-starter-web:1.3.6.RELEASE")

    compile("org.springframework.boot:spring-boot-starter-thymeleaf:1.3.6.RELEASE")

    compile("org.springframework.boot:spring-boot-starter-data-jpa:1.3.6.RELEASE")

    compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.6'

    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.4'

    compile("org.springframework.boot:spring-boot-devtools:1.3.6.RELEASE")

    compile("org.springframework.boot:spring-boot-starter-test:1.3.6.RELEASE")

    compile 'org.webjars.bower:bootstrap:3.3.6'

compile 'org.webjars.bower:jquery:2.2.4'

    compile("org.webjars:vue:1.0.24")

compile 'org.webjars.bower:vue-resource:0.7.0'

}

bootRun {

    addResources = true

}

WebJars

WebJars is a magic thing that allows you to use various frameworks and components of the front end in the form of jar packages.

What is WebJars

What is WebJars? Web Jars is to type client (browser) resources (JavaScript, Css, etc.) into jar package files to manage resources in a unified way. The jar package of WebJars is deployed on the Maven central warehouse.

Why Use

When we develop Java web projects, we use building tools such as Maven, Gradle to implement jar package version dependency management and project automation management. But for JavaScript, Css and other front-end resource packages, we can only copy to webapp, so we can not rely on these resources management. Web Jars then provides us with the jar package situation for these front-end resources, and we can manage dependencies.

How to use it

1. WebJars Master Web Search for Components, such as Vuejs

<dependency>

    <groupId>org.webjars.bower</groupId>

    <artifactId>vue</artifactId>

    <version>1.0.21</version>

</dependency>

2. Page introduction

<link th:href="@{/webjars/bootstrap/3.3.6/dist/css/bootstrap.css}" rel="stylesheet"></link>

It can be used normally!
Author: Pure Smile
Links to the original text

Posted by arfa on Wed, 26 Jun 2019 12:01:47 -0700