springboot (2): web comprehensive development

web development

Spring boot web development is very simple, including commonly used json output, filters, property, log, etc.

json interface development

What configuration needs to be done when we need to provide json interface in the previous spring development?

  1. Add jackjson and other related jar packages
  2. Configure spring controller scan
  3. Add @ResponseBody to the docking method

In this way, 406 errors are often caused by configuration errors, etc. How does spring boot do, just add   @RestController  classes, and the methods in the default classes will be returned in json format

@RestController
public class HelloWorldController {
    @RequestMapping("/getUser")
    public User getUser() {
    	User user=new User();
    	user.setUserName("Jim");
    	user.setPassWord("123");
        return user;
    }
}

If we need to use page development as long as we use it  , the following will be combined with templates to illustrate @Controller

Custom Filter

We often use filters in our projects to record call logs, exclude characters with XSS threats, perform permission verification, and so on. Spring Boot automatically adds OrderedCharacterEncodingFilter and HiddenHttpMethodFilter, and we can customize Filter.

Two steps:

  1. Implement the Filter interface and implement the Filter method
  2. Add @Configuration annotations to add custom Filters to the filter chain
@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() {
			System.out.println("MyFilter is destroying...");
		}

		@Override
		public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain) throws IOException, ServletException {
			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=springBoot
com.neo.description=轻量级spring框架

custom configuration class

@Component
public class NeoProperties {

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

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

	//省略getter settet方法
}

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 local machine, and logging.level  the log level of different resources can be configured later according to the package path.

database operations

Here I will focus on the use of mysql and spring data jpa. Needless to say, mysql is familiar to everyone. Jpa uses Hibernate to generate various automated sql. If it is just basic CRUD, you don't need to write it by hand. Spring has already helped you encapsulate it. Achieved.

Here's a brief introduction to how to use it in spring boot

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

  1. create: Every time hibernate is loaded, the last generated table will be deleted, and then a new table will be regenerated according to your model class, even if there is no change twice, this is an important reason for the loss of database table data reason.
  2. create-drop: Each time hibernate is loaded, a table is generated based on the model class, but the table is automatically deleted as soon as the sessionFactory is closed.
  3. update: the most commonly used attribute. When hibernate is loaded for the first time, the table structure will be automatically established according to the model class (provided that the database is established first), and the table structure will be automatically updated according to the model class when hibernate is loaded later, even if the table structure has changed. Rows in the table still exist without deleting previous rows. It should be noted that when deployed to the server, the table structure will not be established immediately, it will not be established until the application is run for the first time.
  4. validate : Every time hibernate is loaded, the database table structure is verified to be created, and it will only be compared with the tables in the database, no new tables will be created, but new values ​​will be inserted.

dialect It is mainly to specify whether the storage engine that generates the table name is InneoDB
show-sql whether to print out the automatically generated SQL, which is convenient for viewing during 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;

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

}

Dao only needs to inherit the JpaRepository class, almost no need to write methods, and a particularly convenient function is to automatically generate SQL according to the method name. For example, findByUserName it will automatically generate userName a  query method with parameters, such as findAll automatically querying the table. All data, such as automatic pagination, etc...

Fields in Entity that are not mapped to columns must be annotated with @Transient , and they will also be mapped to columns without annotations

public interface UserDao extends JpaRepository<User, Long> {
    User findByUserName(String userName);
    User findByUserNameOrEmail(String username, String email);
}

4. Test

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class UserRepositoryTests {

	@Autowired
	private UserDao userDao;

	@Test
	public void test() throws Exception {
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);        
		String formattedDate = dateFormat.format(date);
		userDao.save(new User("a", "[email protected]", "aa", "aa123456",formattedDate));
		userDao.save(new User("b", "[email protected]", "bb", "bb123456",formattedDate));
		userDao.save(new User("c", "[email protected]", "cc", "cc123456",formattedDate));
		Assert.assertEquals(9, userDao.findAll().size());
		Assert.assertEquals("bb", userDao.findByUserNameOrEmail("bb", "[email protected]").getNickName());
		userDao.delete(userDao.findByUserName("a"));
	}

}

Of course, spring data jpa also has many functions, such as encapsulated paging, you can define your own SQL, master-slave separation, etc...

thymeleaf template

Spring boot recommends using thymeleaf template instead of jsp

Introducing 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, the biggest feature of Thymeleaf is that it can directly open and display template pages in the browser without starting the entire web application.

Well, if you're used to using templates like velocity, FreeMaker, beetle, what's so good about it? Thymeleaf is different because it uses natural template technology, which means that Thymeleaf's template syntax doesn't 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 will replace static values ​​at runtime. Velocity and FreeMarker are sequential 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 since Thymeleaf uses an XML DOM parser, it is not suitable for processing large-scale XML files. **

URL

URLs play a very important role in web application templates. It should be noted that Thymeleaf handles URLs through the syntax @{…}. 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>

page as prototype

A topic that cannot be avoided in the web development process is the cooperation between front-end development and back-end development. In the traditional Java web development process, front-end development and back-end development also require the installation of a complete development environment, and then various Modify templates and static resource files in the Java IDE, start/restart/reload the application server, and refresh the page to view the final effect.

But in fact, the responsibility of front-end development 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 be displayed in the browser. Thymeleaf fundamentally subverts this process. Template rendering through attributes will not introduce any new tags that are not recognized by browsers, such as in JSP, and will not write expressions inside tags. The entire page is directly opened with a browser as an HTML file, and you can almost see the final effect, which greatly liberates the productivity of front-end engineers, and finally provides HTML/CSS/JavaScript files.

Gradle build tools

The spring project recommends using Gradle to build the project. Compared with maven, Gradle is more concise, and gradle is more suitable for the construction of large and complex projects. Gradle absorbs the characteristics of maven and ant, but maven is still the mainstream in the Java world.

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'  //添加 Java 插件, 表明这是一个 Java 项目
apply plugin: 'spring-boot' //添加 Spring-boot支持
apply plugin: 'war'  //添加 War 插件, 可以导出 War 包
apply plugin: 'idea' //添加 Intellij IDEA 插件, 添加 IDEA IDE 支持, Eclipse为 "eclipse"

war {
    baseName = 'favorites'
    version =  '0.1.0'
}

sourceCompatibility = 1.7  //最低兼容版本 JDK1.7
targetCompatibility = 1.7  //目标兼容版本 JDK1.7

repositories {     //  Maven 仓库
    mavenLocal()        //使用本地仓库
    mavenCentral()      //使用中央仓库
    maven { url "http://repo.spring.io/libs-snapshot" } //使用远程仓库
}
 
dependencies {   // 各种 依赖的jar包
    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 very magical thing that allows you to use various front-end frameworks and components in the form of jar packages.

What are WebJars

WebJars is to package client (browser) resources (javascript, css, etc.) into jar files to manage resources uniformly. The jar packages of WebJars are deployed on the Maven central repository.

why use

When we develop Java web projects, we will use build tools such as Maven, Gradle, etc. to achieve version dependency management of jar packages and automatic management of projects. However, for front-end resource packages such as JavaScript and CSS, we can only copy them to the webapp. In this way, dependency management of these resources is not possible. Then WebJars provides us with the jar package situation of these front-end resources, and we can perform dependency management.

how to use

1.  The main official website of WebJars  finds the corresponding 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!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325889965&siteId=291194637