Spring Boot Starter

Source: Internet
Author: User

Spring Boot Starter:

To create a spring Boot project using idea:

Choose

Tick web

To build the project structure:

Example:
 Package Com.example.testboot; Import org.springframework.web.bind.annotation.GetMapping; Import Org.springframework.web.bind.annotation.RestController; @RestController  Public class Hellocontroller {    @GetMapping ("/hello")    public  String Say () {         return "Hello";    }}

Then run the main program:

 PackageCom.example.testboot;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod; @SpringBootApplication Public classtestbootapplication { Public Static voidMain (string[] args) {Springapplication.run (testbootapplication.class, args); }}

Configuration file:

#端口号server. Port=8081    #项目前缀server. Context-path=/test

You can also use the YML format configuration file:

Server:   8081  cotent-path:/sd

You can differentiate between a production environment and a development environment in a multi-environment configuration.

Use of controller:

Annotations:

@RestController annotations are equivalent to @responsebody + @Controller together.

1) If you use the @restcontroller annotation controller only, the method in the controller cannot return to the JSP page, and the configured view resolver Internalresourceviewresolver does not work. The returned content is the content in return.

For example: should be to the success.jsp page, then its display success.

2) If you need to return to the specified page, you need to use the @Controller with the view resolver internalresourceviewresolver.
3) If you need to return Json,xml or custom mediatype content to the page, you need to add @responsebody annotations to the corresponding method.

@GetMapping ({"/hello", "/hi"})
@PostMapping ({"/hello", "/hi"})
@RequestMapping ({"/hello", "/hi"})

Multiple ingress @requestmapping can be specified using a collection or assigned to a controller

@PathVaribale get the data in the URL

// @RequestMapping (value= "/hello/{id}", method= requestmethod.get)    @GetMapping ("/hello/{id}")    public String SayHello (@PathVariable ("id") of the Integer id) {         return "ID:" +ID;    }

Effect:

Note that here

@RequestMapping (value= "/hello/{id}", method= Requestmethod.get)

The effect is equivalent to

@GetMapping ("/hello/{id}")

Similarly, if we need to have more than one parameter in the URL to get, then the code below will do it.

@RequestMapping (value= "/hello/{id}/{name}", method= requestmethod.get)    public String SayHello (@PathVariable ("id") Integer ID, @PathVariable ("name") String name) {        return ' ID: ' +id+ ' Name: "+name;    }

@RequestParam get the value of the request parameter

    @RequestMapping (value= "/hello", method= requestmethod.get)    public String SayHello (@ Requestparam ("id") Integer ID) {        return ' ID: ' +ID;    }

// @RequestMapping (value= "/hello/{id}", method= requestmethod.get)    @GetMapping ("/hello")    ///Required=false indicates that the ID parameter can not be entered in the URL, and the default parameter public is used at this time      false, DefaultValue = "1") Integer ID) {        return ' ID: ' +ID;    }

If there are multiple parameters:

    @GetMapping ("/hello")    public String SayHello (@RequestParam ("id") of the Integer ID, @RequestParam (" Name ") String name {        return " ID: "+id+" Name: "+name;    }

@GetMapping

Equivalent to @requestmapping (method = Requestmethod.get)

and @postmapping and @putmapping and so on.

Database operations:

To configure the Yml file:

Server:  port:8090  session-timeout:30  tomcat.max-threads:0  tomcat.uri-encoding:utf-8spring:  DataSource:    url:jdbc:mysql://localhost:3306/mybill    username:root    password:root    DriverClassName:com.mysql.jdbc.Driver  JPA:    database:mysql    show-sql:true    Hibernate:      Ddl-auto:update      naming-strategy:org.hibernate.cfg.improvednamingstrategy    properties:      Hibernate:        Dialect:org.hibernate.dialect.MySQL5Dialect

To configure an entity class:

 PackageCom.example.testboot;Importjavax.persistence.Entity;ImportJavax.persistence.GeneratedValue;Importjavax.persistence.Id; @Entity Public classUser {@Id @GeneratedValuePrivateInteger ID; PrivateString name;  PublicUser () {} PublicUser (String name) { This. Name =name; }     PublicInteger getId () {returnID; }     PublicString GetName () {returnname; }     Public voidsetId (Integer id) { This. ID =ID; }     Public voidsetName (String name) { This. Name =name; }}

Run the project to generate the data table at the specified location in the database.

Simple database operation:

Get Data:

New interface:

 Package Com.example.testboot; Import org.springframework.data.jpa.repository.JpaRepository;  Public Interface extends Jparepository<user,integer> {}

Controller:

 PackageCom.example.testboot;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.web.bind.annotation.GetMapping;ImportOrg.springframework.web.bind.annotation.RequestParam;ImportOrg.springframework.web.bind.annotation.RestController;Importjava.util.List; @RestController Public classUsercontroller {@AutowiredPrivateuserrepository userrepository; /*** Return to user list *@return     */@GetMapping ("/getuser")     PublicList<user>GetUser () {returnUserrepository.findall (); }}

Add the method:

    /**      * Add      @param  ID     @param  name     @return     */    @PostMapping ("/getuser")    public User addUser (@ Requestparam ("id") Integer ID, @RequestParam ("name") String name) {        user user=new  user ();        User.setid (ID);        User.setname (name);         return userrepository.save (user);    }

    /**      * Query a user      @param  ID     @return     */    @ GetMapping("/get/{id}")    public User finduser (@PathVariable ("id ") Integer ID) {        return  userrepository.findone (ID);    }

    /**      * Update a user      @param  ID     @param  name     @return     */    @PutMapping ("/put/{id}")    public User putuser (@ Pathvariable ("id") Integer ID, @RequestParam ("name") String name) {        user user=new  user ();        User.setid (ID);        User.setname (name);         return userrepository.save (user);    }

    /**      * Delete user      @param  ID     *    /@DeleteMapping ("/del/{id}" )    publicvoid deluser (@PathVariable ("id") Integer ID) {        Userrepository.delete (ID);    }

Transaction management:

@Transactional    @DeleteMapping ("/del/{id}")    publicvoid Deluser (@PathVariable ("id") Integer ID) {        userrepository.delete (ID);    }

Through annotations @Transactional

Causes the operation to not complete when one is not completed, except that the query method should add a transaction.

Spring Boot Starter

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.