Java Web series: Spring Boot Basics

Source: Internet
Author: User

The Spring Boot project (ref. 1) provides a standard template like the default templates for ASP. NET MVC, which integrates a series of components directly and uses the default configuration. Using spring Boot does not reduce learning costs or even increase learning costs, but it significantly reduces usage costs and improves development efficiency. If there is no spring foundation it is not recommended to get started directly.

1. Basic projects

This is all about Maven-based project builds, using the Spring Boot CLI command-line tool and the Gradle build method, please refer to the official website.

(1) Create the project:

To create a MAVEN project of type QuickStart, delete the default maven directory by deleting the. java files that are generated.

(2) Modify/pom.xml

 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= " Http://www.w3.org/2001/XMLSchema-instance "3 xsi:schemalocation=" http://maven.apache.org/POM/4.0.0/http Maven.apache.org/xsd/maven-4.0.0.xsd "> 4 <modelVersion>4.0.0</modelVersion> 5 <groupid>com.ex Ample</groupid> 6 <artifactId>myproject</artifactId> 7 <version>0.0.1-snapshot</version > 8 <properties> 9 <java.version>1.8</java.version>10 </properties>11 <p Arent>12 <groupid>org.springframework.boot</groupid>13 <artifactid>spring-boot-starte r-parent</artifactid>14 <version>1.3.1.release</version>15 </parent>16 <depende             Ncies>17 <dependency>18 <groupid>org.springframework.boot</groupid>19 <artifactid>spring-boot-starter-web&Lt;/artifactid>20 </dependency>21 </dependencies>22 </project> 

(3) Add/src/main/sample/controller/homecontroller.java file:

1 package Simple.controller; 2  3 import org.springframework.web.bind.annotation.*; 4  5 @RestController 6 public class HomeController {7  8     @RequestMapping ("/") 9 public     String Index () {Ten         return "Hello world!";     }12}

(4) Add/src/main/sample/application.java file:

1 package simple; 2  3 import org.springframework.boot.*; 4 import org.springframework.boot.autoconfigure.*; 5 import simple.controller.*; 6  7 @EnableAutoConfiguration 8 public class Application {9 public     static void Main (string[] args) throws Excep tion {         springapplication.run (new object[] {application.class, homecontroller.class}, args);     }13 14}

Enter http://localhost:8080/in the browser to see the "Hello World" running results directly.

2. Add Data Access support

(1) Modify Pom to add SPRING-BOOT-STARTER-DATA-JPA and H2 dependencies:

 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= " Http://www.w3.org/2001/XMLSchema-instance "3 xsi:schemalocation=" http://maven.apache.org/POM/4.0.0/http Maven.apache.org/xsd/maven-4.0.0.xsd "> 4 <modelVersion>4.0.0</modelVersion> 5 <groupid>com.ex Ample</groupid> 6 <artifactId>myproject</artifactId> 7 <version>0.0.1-snapshot</version > 8 <properties> 9 <java.version>1.8</java.version>10 </properties>11 <p Arent>12 <groupid>org.springframework.boot</groupid>13 <artifactid>spring-boot-starte r-parent</artifactid>14 <version>1.3.1.release</version>15 </parent>16 <depende             Ncies>17 <dependency>18 <groupid>org.springframework.boot</groupid>19 <artifactid>spring-boot-starter-web&Lt;/artifactid>20 </dependency>21 <dependency>22 <groupid>org.springframe work.boot</groupid>23 <artifactid>spring-boot-starter-data-jpa</artifactid>24 </d ependency>25 <dependency>26 <groupid>com.h2database</groupid>27 <a rtifactid>h2</artifactid>28 <scope>runtime</scope>29 </dependency>30 &L T;/dependencies>31 </project>

If you need to view the generated SQL statements in the console, you can add/src/main/resources/application.properties

1 spring.h2.console.enabled=true2 Logging.level.org.hibernate.sql=debug

(2) Adding entities

Add user, Role, category, and post entities.

User:

 1 package simple.domain; 2 3 Import java.util.*; 4 5 Import javax.persistence.*; 6 7 @Entity 8 public class User {9 @Id10 @GeneratedValue11 private Long id;12 private String UserName ; the private string password;16. email;18 @javax. Persistence.version20 Private Long Version;21 @ManyToMany (cascade = cascadetype.all) Private list<role> roles = new Arraylist<role> ( ), Public Long getId () {id;27}28, public void setId (Long id) {this.id = i d;31}32 public String getusername () {return username;35}36 notoginseng public void Setusername (stri ng userName) {this.username = username;39}40-Public String GetPassword () {Passwor  d;43}44 public void SetPassword (String password) {This.password = password;47}48     String Getemail () {email;51}52 53public void Setemail (String email) {e-mail = email;55}56, public list<role> getroles () {58 Return roles;59}60, public void Setroles (list<role> roles) {this.roles = roles;63}64         70 Public long GetVersion () {version;67 return,}68, public void setversion (Long Version) Version = version;71}72}
View Code

Role:

1 package simple.domain; 2  3 import java.util.*; 4  5 import javax.persistence.*; 6  7 @Entity 8 public class Role {9     @Id10     @Gen EratedValue11     Private Long id;12     rolename;14     @ManyToMany (cascade = cascadetype.all) 16     Private list<user> users = new arraylist<user> (); public     Long getId () {         return id;20< c12/>}21 public     void SetId (Long id) {         this.id = id;24     }25     -Public String getrolename () {27
   return rolename;28     }29     -public void Setrolename (String roleName) {         this.rolename = rolename;32     }33 public     list<user> getusers () {     }37 users;36 setusers     List<user> users) {         this.users = users;40     }41}
View Code

Category:

1 package simple.domain; 2  3 import java.util.*; 4  5 import javax.persistence.*; 6  7 @Entity 8 public class Category {9     @Id10     @GeneratedValue11     Private Long id;12-     private String name;14     @OneToMany16     Private List<post  > posts = new arraylist<post> (); n-Public     Long getId () {         return id;20     }21 n     void SETID (Long id) {         this.id = id;24     }25-Public     String GetName () {         return name;28     }29 30
   public void SetName (String name) {         = = name;32     }33 public     list<post> getposts () {         return posts;36     }37     -public void setposts (list<post> posts) {this.posts         = posts;40     }41}
View Code

Post:

 1 package simple.domain; 2 3 Import java.util.*; 4 5 Import javax.persistence.*; 6 7 @Entity 8 public class Post {9 @Id10 @GeneratedValue11 private Long id;12 private String name;14 The private string html;16-private string text;18 private Date createat;20 @ManyToOne22 privat         E Category category;23 public Long getId () {id;26}27-public void setId (Long id) {29 This.id = id;30}31 The public String getName () {return name;34}35 * public void Setnam     E (String name) {PNS name = name;38}39-Public String gethtml () {html;42}43 44 public void sethtml (string html) {html = html;46}47-Public String GetText () {return Tex T;50}51-public void SetText (String text) {text = text;54}55-Public Date getcreateat () { createat;58 return}59 public void SETCREateat (Date createat) {createat = createat;62}63 public Category getcategory () {D-return C ategory;66}67-public void setcategory (category category) {this.category = category;70}71}
View Code

(3) Adding a resource library

Add Userrepository, Rolerepository, Categoryrepository, and postrepository interfaces without implementation.

Userrepository:

1 package simple.repository;2 3 Import org.springframework.data.repository.*;4 5 import simple.domain.*;6 7 public Interf Ace Userrepository extends Crudrepository<user, long> {8 9}

Rolerepository

1 package simple.repository;2 3 Import org.springframework.data.repository.*;4 5 import simple.domain.*;6 7 public Interf Ace Rolerepository extends Crudrepository<role, long> {8 9}

Categoryrepository

1 package simple.repository;2 3 Import org.springframework.data.repository.*;4 5 import simple.domain.*;6 7 public Interf Ace Categoryrepository extends Crudrepository<category, long> {8 9}

Postrepository

Package Simple.repository;import org.springframework.data.repository.*;import simple.domain.*;p ublic interface Postrepository extends Crudrepository<user, long> {}

(4) Inject the repository interface into the controller

 1 package Simple.controller; 2 3 import org.springframework.beans.factory.annotation.*; 4 import Org.springframewo rk.web.bind.annotation.*; 5 6 Import simple.repository.*; 7 8 @RestController 9 public class HomeController {Ten private userrepository userrepository;12 private Rolerep Ository rolerepository;13 Private categoryrepository categoryrepository;14 private postrepository postReppository;             @Autowired17 public HomeController (userrepository userrepository, Rolerepository rolerepository,18 Categoryrepository categoryrepository, Postrepository postreppository) {this.userrepository = UserRepository ; this.rolerepository = rolerepository;21 this.categoryrepository = categoryrepository;22 THIS.P Ostreppository = postreppository;23}24 @RequestMapping ("/") "Public Long Index" () {+-return US Errepository.count ();}30} 

Apply annotations on a method when using transactions @transactional

3. Add authentication and authorization support

(1) Add spring-boot-starter-security dependency

 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= " Http://www.w3.org/2001/XMLSchema-instance "3 xsi:schemalocation=" http://maven.apache.org/POM/4.0.0/http Maven.apache.org/xsd/maven-4.0.0.xsd "> 4 <modelVersion>4.0.0</modelVersion> 5 <groupid>com.ex Ample</groupid> 6 <artifactId>myproject</artifactId> 7 <version>0.0.1-snapshot</version > 8 <properties> 9 <java.version>1.8</java.version>10 </properties>11 <p Arent>12 <groupid>org.springframework.boot</groupid>13 <artifactid>spring-boot-starte r-parent</artifactid>14 <version>1.3.1.release</version>15 </parent>16 <depende             Ncies>17 <dependency>18 <groupid>org.springframework.boot</groupid>19 <artifactid>spring-boot-starter-web&Lt;/artifactid>20 </dependency>21 <dependency>22 <groupid>org.springframe work.boot</groupid>23 <artifactid>spring-boot-starter-data-jpa</artifactid>24 </d ependency>25 <dependency>26 <groupid>com.h2database</groupid>27 <a         rtifactid>h2</artifactid>28 <scope>runtime</scope>29 </dependency>30 <dependency>31 <groupid>org.springframework.boot</groupid>32 <artifactId&gt ; spring-boot-starter-security</artifactid>33 </dependency>34 </dependencies>35 </project& Gt

(2) Modify Application.java

 1 package simple; 2 3 Import org.springframework.boot.*; 4 Import org.springframework.boot.autoconfigure.*; 5 Import Org.springframework.context.annotation.Bean; 6 Import org.springframework.security.config.annotation.method.configuration.*; 7 Import org.springframework.security.config.annotation.web.builders.HttpSecurity; 8 Import Org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 9 Import org.springframework.security.web.authentication.savedrequestawareauthenticationsuccesshandler;10 11 Import simple.controller.*;12 @EnableAutoConfiguration14 @EnableGlobalMethodSecurity (securedenabled = True,         Prepostenabled = True) public class application {18-public static void main (string[] args) throws Exception     Springapplication.run (new object[] {application.class, homecontroller.class}, args);}20 @Bean22 Public Websecurityconfigureradapter Websecurityconfigureradapter () {return new MYWEBSECURITYCOnfigurer ();}25 public static class Mywebsecurityconfigurer extends Websecurityconfigureradapter {27              @Override28 protected void Configure (Httpsecurity http) throws Exception {http.csrf (). disable (); 30 Http.authorizerequests (). Antmatchers ("/account**", "/admin**"). authenticated (); Http.formlogin ( ). Usernameparameter ("UserName"). Passwordparameter ("password"). LoginPage ("/login"). Loginprocessingur L ("/login"). Successhandler (New Savedrequestawareauthenticationsuccesshandler ()). and (). Logout (). Logo Uturl ("/logout"). Logoutsuccessurl ("/"); Http.rememberme (). Remembermeparameter ("RememberMe"); 35 36}3 7}38}

Access Http://localhost:8080/account will automatically jump to the login login page. The specific use of Spring security has already been described in the previous article.

Reference:

(1) Https://github.com/spring-projects/spring-boot

(2) http://projects.spring.io/spring-boot/

Java Web series: Spring Boot Basics (RPM)

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.