Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Web Comprehensive Development in Spring Boot

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "sample Analysis of Web Comprehensive Development in Spring Boot". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn the "Spring Boot Web comprehensive development example analysis" it!

Web development

Spring Boot Web development is very simple, including commonly used json output, filters, property, log and so on.

Json interface development

In the past, when you used Spring to develop projects, what configurations did you need to do when you needed to provide json interfaces?

Add related jar packages such as jackjson

Configure Spring Controller scanning

Add @ ResponseBody to the docking method

In this way, we will often cause 406 errors due to configuration errors, etc. What does Spring Boot do? you only need to add @ RestController to the class. The methods in the default class will be returned in json format.

@ RestControllerpublic class HelloController {@ RequestMapping ("/ getUser") public User getUser () {User user=new User (); user.setUserName ("Xiaoming"); user.setPassWord ("xxxx"); return user;}}

If you need to use page development, just use the @ Controller annotation, which will be explained in combination with the template below

Custom Filter

We often use filters in our projects to log calls, eliminate characters threatened by XSS, perform permission verification, and so on. Spring Boot automatically adds OrderedCharacterEncodingFilter and HiddenHttpMethodFilter, and we can customize Filter.

Two steps:

Implement Filter interface and Filter method

Add @ Configuration annotation to add custom Filter to the filter chain

All right, just go 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 it

Configure com.neo.title= pure smile in application.properties com.neo.description= to share life and technology

Custom configuration class

@ Component

Public class NeoProperties {

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

Private String title

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

Private String description

/ / omit the getter settet method

}

Log configuration

Configure the address and output level of the output

Logging.path=/user/local/loglogging.level.com.favorites=DEBUGlogging.level.org.springframework.web=INFOlogging.level.org.hibernate=ERROR

Path is the local log address. After the logging.level, you can configure the log level of different resources according to the packet path.

Database operation

Here I will focus on the use of Mysql and spring data jpa, of which Mysql is not to mention that you are familiar with it. Jpa uses Hibernate to generate a variety of automated sql. If it is just a simple addition, deletion, modification and query, there is basically no need for handwriting. Spring has been encapsulated and implemented for everyone.

Here is a brief description of how to use it in Spring Boot

1. Add phase jar package org.springframework.boot spring-boot-starter-data-jpa mysql mysql-connector-java2, add configuration file

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, this hibernate.hbm2ddl.auto parameter is mainly used to automatically create | update | verify the structure of the database table. There are four values:

Create: each time you load hibernate, you delete the last generated table, and then regenerate the new table according to your model class, even if there are no changes twice, which is an important reason for the loss of database table data.

Create-drop: each time the hibernate is loaded, the table is generated according to the model class, but as soon as sessionFactory is closed, the table is automatically deleted.

Update: the most commonly used attribute, the structure of the table will be automatically established according to the model class when the hibernate is loaded for the first time (provided that the database is established first), and then the table structure will be automatically updated according to the model class when loading hibernate. Even if the table structure has changed, the rows in the table still exist and the previous rows will not be deleted. It is important to note that when deployed to the server, the table structure will not be set up immediately, but only after the application is run for the first time.

Validate: each time you load hibernate, verify that the database table structure is created, and only the tables in the database are compared. No new tables are created, but new values are inserted.

Dialect mainly specifies that the storage engine for generating table names is InneoDB.

Whether show-sq prints out the SQL of automatic production, which can be easily checked when debugging.

3. Add 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

/ / omit getter settet method and construction method

}

As long as dao inherits the JpaRepository class, there is almost no need to write methods. Another great feature is that you can automatically produce SQL according to the method name. For example, findByUserName will automatically produce a query method that takes userName as a parameter. For example, findAlll will automatically query all the data in the table, such as automatic paging and so on.

Fields that are not mapped into columns in Entity need to be annotated with @ Transient, and will be mapped into columns without annotations.

Public interface UserRepository extends JpaRepository {User findByUserName (String userName); User findByUserNameOrEmail (String username, String email);} 4, test

@ 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 still has many functions, such as encapsulated pagination, SQL can be defined by itself, master-slave separation and so on, I won't go into details here.

Thymeleaf template

What is the origin of Spring Boot's recommendation to use Thymeleaf instead of Jsp,Thymeleaf template? let Brother Spring recommend it. Let's talk about it.

Thymeleaf introduction

Thymeleaf is a template engine for rendering XML/XHTML/HTML5 content. Like JSP,Velocity,FreeMaker, 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, the biggest feature of Thymeleaf is that it can directly open and correctly display the template page in the browser without the need to start the entire Web application.

Well, you said we are used to using templates like Velocity,FreMaker,beetle, so what's the good thing?

Let's have a match.

Thymeleaf is different because it uses natural templating technology. This means that the Thymeleaf template syntax does not break the structure of the document, and the template is still a valid XML document. Templates can also be used as working prototypes, and Thymeleaf replaces static values at run time. Velocity and FreeMarke r are consecutive text processors. The following code example prints a message using Velocity, FreeMarker, and Thymeleaf, respectively:

Velocity:

$message

FreeMarker:

${message}

Thymeleaf: Hello World!

Note that because Thymeleaf uses the XML DOM parser, it is not suitable for processing large-scale XML files.

URL

URL occupies a very important position in the Web application template, and it should be noted that Thymeleaf handles URL through the syntax @ {.}. Thymeleaf supports absolute path URL:

Evaluation of Thymeleaf condition Loginfor loop Onions 2.41 yes

Just list these.

The page is the prototype

In the process of Web development, an unavoidable topic is the cooperation between front-end engineers and back-end engineers. In the traditional Java Web development process, front-end engineers, like back-end engineers, also need to install a complete development environment, and then modify templates and static resource files in all kinds of Java IDE, start / restart / reload the application server, and refresh the page to view the final effect.

But in fact, the responsibility of the front-end engineer should focus more on the page itself than on the back end, which is difficult to do with traditional Java template engines such as JSP,Velocity, because they must be rendered in the application server before they can see the results in the browser. Thymeleaf fundamentally subverts this process, and template rendering through attributes does not introduce any tags that are not recognized by new browsers, such as JSP Expressions are not written inside Tag. The entire page opens directly as a HTML file in the browser, and you can almost see the final effect, which greatly liberates the productivity of the front-end engineers, whose final deliverables are pure HTML/CSS/JavaScript files.

Gradle build tool

The Spring project recommends using Maven/Gradle to build the project, Gradle is more concise than Maven, and Gradle is more suitable for building large and complex projects. Gradle absorbs the characteristics of Maven and Ant, but at present Maven is still the mainstream of the Java world, you can understand it first.

A project configured with Gradle

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 the Java plug-in, indicating that this is a Java project

Apply plugin: 'spring-boot' / / add Spring-boot support

Apply plugin: 'war' / / add War plug-in to export War package

Apply plugin: 'eclipse' / / add Eclipse plug-in, add Eclipse IDE support, and Intellij Idea is "idea"

War {

BaseName = 'favorites'

Version = '0.1.0'

}

SourceCompatibility = 1.7 / / minimum compatible version JDK1.7

TargetCompatibility = 1.7 / / Target compatible version JDK1.7

Repositories {/ / Maven warehouse

MavenLocal () / / use the local warehouse

MavenCentral () / / use the central warehouse

Maven {url "http://repo.spring.io/libs-snapshot"} / / use remote warehouse

}

Dependencies {/ / various dependent jar packages

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 an amazing thing that allows people to use a variety of front-end frameworks and components in the form of Jar packages.

What is WebJars?

WebJars is to package the client (browser) resources (JavaScript,Css, etc.) into Jar package files for unified dependent management of resources. WebJars's Jar package is deployed on the Maven central repository.

Why do you use

When developing Java web projects, we use build tools such as Maven,Gradle to manage Jar package version dependencies and automate project management, but for front-end resource bundles such as JavaScript,Css, we can only copy them to webapp, which makes it impossible to manage these resources. Then WebJars provides us with the Jar package situation of these front-end resources, and we can manage dependencies.

How to use

1. WebJars's main official website to find the components for, such as Vuejs

Org.webjars vue 2.5.16

2. Page introduction

It can be used normally!

At this point, I believe you have a deeper understanding of the "sample Analysis of Web Comprehensive Development in Spring Boot". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report