Spring boot (ii)-WEB development

Source: Internet
Author: User
Tags assert dateformat stub

The previous article introduced the Spring Boot Beginner Tutorial: Spring boot (a): Introductory article, easy to get started, to understand the practice of Spring boot feature; This article goes on to introduce other features of spring boot (some may not be spring The boot system is buyers, but some of the open source technologies recommended by spring are also described in this article.

1.Web Development

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

2.Json Interface Development

What do we need to do when we provide the JSON interface in the previous spring development? There are probably the following configurations:

(1) Add Jackjson and other related jar packages;

(2) Configure spring Controller scan;

(3) Docking method to add @responsebody;

In this way we will often due to configuration errors, resulting in 406 errors and so on, spring boot How to do it, just need to add the class @RestController , the default class method will be returned in JSON format.

1 @RestController2  Public classHelloworldcontroller {3@RequestMapping ("/getuser")4      PublicUser GetUser () {5User user=NewUser ();6User.setusername ("Xiao Ming");7User.setpassword ("xxxx");8         returnuser;9     }Ten}

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

3. Custom Filter

We often use filters in our projects to record call logs, exclude characters with XSS threats, perform permission validation, and so on. Spring boot automatically adds orderedcharacterencodingfilter and Hiddenhttpmethodfilter, and we can customize the filter.

Two steps:

(1) Implement the filter interface and implement the filter method;

(2) Adding @Configurationz annotations, adding the custom filter to the filtering chain;

The code is as follows:

1 @Configuration2  Public classwebconfiguration {3 @Bean4      PublicRemoteipfilter Remoteipfilter () {5         return NewRemoteipfilter ();6     }7     8 @Bean9      PublicFilterregistrationbean testfilterregistration () {Ten  OneFilterregistrationbean registration =NewFilterregistrationbean (); ARegistration.setfilter (Newmyfilter ()); -Registration.addurlpatterns ("/*"); -Registration.addinitparameter ("ParamName", "Paramvalue"); theRegistration.setname ("Myfilter"); -Registration.setorder (1); -         returnregistration; -     } +      -      Public classMyfilterImplementsFilter { + @Override A          Public voiddestroy () { at             //TODO auto-generated Method Stub -         } -  - @Override -          Public voidDoFilter (ServletRequest srequest, Servletresponse sresponse, Filterchain filterchain) -                 throwsIOException, servletexception { in             //TODO auto-generated Method Stub -HttpServletRequest request =(HttpServletRequest) srequest; toSystem.out.println ("This is Myfilter,url:" +Request.getrequesturi ()); + Filterchain.dofilter (Srequest, sresponse); -         } the  * @Override $          Public voidInit (Filterconfig arg0)throwsservletexception {Panax Notoginseng             //TODO auto-generated Method Stub -         } the     } +}

4. Custom property

In the process of web development, I often need to customize some of the configuration files, how to use it?

(1) configuration in application.properties:

Com.neo.title= a pure Smile

Com.neo.description= Sharing life and technology

(2) Custom configuration class:

1 @Component2  Public classneoproperties {3@Value ("${com.neo.title}")4     PrivateString title;5@Value ("${com.neo.description}")6     PrivateString description;7 8     //Omit Getter Settet method9 Ten}

5.log Configuration

Configure the address and output level of the output

1 logging.path=/user/local/log2 logging.level.com.favorites=DEBUG3 logging.level.org.springframework.web=INFO4 logging.level.org.hibernate=error

Path is the log address for this machine, and logging.level the log level of different resources can be configured later based on the package path.

6. Database Operations

Here I focus on the use of MySQL, spring data jpa, where MySQL is not to mention that everyone is familiar with, JPA is the use of hibernate to generate a variety of automated SQL, if only simple additions and deletions to change, basically do not hand-written, Within spring, we've already packaged it for everyone.

Here's a brief look at how to use it in spring boot:

(1) Add related JAR package

1  <dependency>2         <groupId>org.springframework.boot</groupId>3         < Artifactid>spring-boot-starter-data-jpa</artifactid>4     </dependency>5      <dependency>6         <groupId>mysql</groupId>7         <artifactId> Mysql-connector-java</artifactid>8     </dependency>

(2) Adding a configuration file

 1  spring.datasource.url=jdbc:mysql://  localhost:3306/test  2  Spring.datasource.username=root  3  Spring.datasource.password=root  4  Spring.datasource.driver-class -name= Com.mysql.jdbc.Driver  5  6  Spring.jpa.properties.hibernate.hbm2ddl.auto=update  7  spring.jpa.properties.hibernate.dialect= Org.hibernate.dialect.MySQL5InnoDBDialect  8  spring.jpa.show-sql= true  

In fact, the function of this hibernate.hbm2ddl.auto parameter is mainly used for: auto Create | update | Validate database table structure with four values:

    1. Create: Each time you load hibernate, the last generated table will be deleted, and then the new table will be generated based on your model class, even if there are no changes two times to do so, which is an important reason for the loss of database table data.
    2. Create-drop: The table is generated according to the model class each time hibernate is loaded, but the table is automatically deleted when Sessionfactory is closed.
    3. Update: The most commonly used property, the first time hibernate is loaded according to the model class will automatically establish the structure of the table (provided that the database is first established), and later when loading hibernate according to the model class automatically update the table structure, Even if the table structure changes but the rows in the table still exist, the previous rows are not deleted. It is important to note that when deployed to a server, the table structure is not immediately established, it is to wait for the application to run for the first time.
    4. Validate: Each time hibernate is loaded, validation creates a database table structure that is only compared to tables in the database and does not create new tables, but inserts new values.

 dialectThe main is to specify the generation table name of the storage engine for INNEODB;
 show-sqlWhether to print out the automatic production of SQL, convenient debugging time to view;

(3) Adding entity classes and DAO packages

1 @Entity2  Public classUserImplementsSerializable {3 4     Private Static Final LongSerialversionuid = 1L;5 @Id6 @GeneratedValue7     PrivateLong ID;8@Column (nullable =false, unique =true)9     PrivateString UserName;Ten@Column (nullable =false) One     PrivateString PassWord; A@Column (nullable =false, unique =true) -     PrivateString Email; -@Column (nullable =true, unique =true) the     PrivateString nickname; -@Column (nullable =false) -     PrivateString regtime; -  +     //omitting Getter Settet method and construction method -  +}

DAO as long as the inheritance of Jparepository class can, almost without writing methods, there is a special urine function is very good, that can be derived from the method name of the production of SQL, for example findByUserName , will automatically produce a userName query method for parameters, such as findAlll Automatically queries all the data in the table,

such as automatic paging and so on.

Fields that do not map to columns in **entity are @transient annotated and are mapped as columns without annotations * *

1  Public Interface extends Jparepository<user, long> {2    User findbyusername (String userName); 3     User Findbyusernameoremail (string username, string email);

7. Testing

1@RunWith (Springjunit4classrunner.class)2@SpringApplicationConfiguration (Application.class)3  Public classuserrepositorytests {4 5 @Autowired6     Privateuserrepository userrepository;7 8 @Test9      Public voidTest ()throwsException {TenDate Date =NewDate (); OneDateFormat DateFormat =dateformat.getdatetimeinstance (Dateformat.long, Dateformat.long);  AString formatteddate =Dateformat.format (date); -          -Userrepository.save (NewUser ("Aa1", "[email protected]", "AA", "aa123456", Formatteddate)); theUserrepository.save (NewUser ("Bb2", "[email protected]", "BB", "bb123456", Formatteddate)); -Userrepository.save (NewUser ("CC3", "[email protected]", "CC", "cc123456", Formatteddate)); -  -Assert.assertequals (9, Userrepository.findall (). Size ()); +Assert.assertequals ("BB", Userrepository.findbyusernameoremail ("BB", "[email protected]"). Getnickname ()); -Userrepository.delete (Userrepository.findbyusername ("Aa1")); +     } A  at}

When the spring data JPA has a lot of features, such as packaged paging, you can define the SQL, master and slave separation, and so on, here is not detailed ...

END

Spring boot (ii)-WEB development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.