This is another javaweb-related blog that covers:
- Springboot: Micro-framework that provides the ability to build services quickly
- Springmvc:struts's replacement
- MyBatis: Database Operations Library
- Groovy: A high-level language that can be combined with Java, with Java at the bottom
- Maven: For simplifying jar package import and packaging
- LOG4J: Log Management
What we're going to do is a simple interface that gets the corresponding data based on the URL request, the data format can be JSON or XML
The effect is as follows:
As you can see, the Get method is used here to request all the book information from the current server and get the result in a JSON format.
If you need to get the XML format, you only need to set the request header's Accept field Text/xml or Application/xml:
Next, start our project:
The community version of idea is used here for the simple reason that we don't need to configure the server at all, and Springboot has tomcat support, so running the project requires just one main method.
The steps are as follows:
- Create and configure a project
- Write Project code (MyBatis, SPRINGMVC)
- Configure log
- Packaged
① Creating and configuring a project
A. Create a MAVEN project (omitted)
B. Modify Pom.xml
1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <project xmlns= "http://maven.apache.org/POM/4.0.0" 3 xmln S:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemalocation= "http://maven.apache.org/POM/4.0.0 http:/ /maven.apache.org/xsd/maven-4.0.0.xsd "> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupid> ;com.fndroid.javaweb</groupid> 8 <artifactId>springboottest</artifactId> 9 <version>1.0- Snapshot</version> <!--dependent starter-parent--> <parent> <GROUPID>ORG.SPR Ingframework.boot</groupid> <artifactId>spring-boot-starter-parent</artifactId> &L T;version>1.4.2.release</version> </parent> <dependencies> <!--this is a W EB Project--<dependency> <groupId>org.springframework.boot</groupId> 22 <artifactid>spring-boot-starter-web</artifactid> <exclusions> <exclusion> 25 <artifactId>log4j-over-slf4j</artifactId> <groupid>org.slf4j</gr oupid> </exclusion> </exclusions> </dependency> 30 31 <!--go out and logging this package from the parent project because we're using log4j--and-<dependency>-<groupid>org .springframework.boot</groupid> <artifactId>spring-boot-starter</artifactId> 35 <exclusions> <groupid>org.springframework.boot& <exclusion> PNs Lt;/groupid> <artifactId>spring-boot-starter-logging</artifactId> 39 </exclusion> </exclusions> $ </dependency> log4j <!--introducing the support--& Gt <depenDency> <groupId>org.springframework.boot</groupId> <artifactid>spring-b Oot-starter-log4j</artifactid> <version>1.3.8.RELEASE</version> </dependenc y> <dependency> <groupId>com.jayway.jsonpath</groupId> Wuyi <a Rtifactid>json-path</artifactid> <scope>test</scope> </dependency> 54 <!--Groovy Support--<dependency> <groupid>org.codehaus.groovy</groupi D> <artifactId>groovy-all</artifactId> <version>2.4.7</version> 5 9 </dependency> <!--use mybatis--> <groupid& Gt;org.mybatis.spring.boot</groupid> <artifactId>mybatis-spring-boot-starter</artifactId> <versIon>1.1.1</version> </dependency> <!--JDBC Drive-up <groupId>mysql</groupId> <ARTIFACTID>MYSQL-CONNECTOR-JAVA</ARTIFACTID&G T <version>6.0.5</version> <scope>runtime</scope> </depe ndency> <dependency> <artifactid <groupId>log4j</groupId> >log4j</artifactId> <version>1.2.17</version> 78 </dependency> <!--support for generating XML--<groupid>com.fasterxml.jackson.dataformat</<dependency> groupid> BA <artifactId>jackson-dataformat-xml</artifactId> a </dependency> 83 </dependencies> <properties> + <java.version>1.8</java.version> /properties> 88 89 <build> <plugins> $ <!--used to generate jar files------------94 <groupId>org.springframework.boot</groupId> <artifactid>spring-boot- Maven-plugin</artifactid> </plugin> </plugins> 98 </build> 99 100 <repositories>101 <repository>102 <id>spring-releases</id>103 &L t;url>https://repo.spring.io/libs-release</url>104 </repository>105 </repositories>106 <pluginrepositories>107 <pluginrepository>108 <id>spring-releases</id>109 <url>https://repo.spring.io/libs-release</url>110 </pluginrepository>111 </plug inrepositories>112 </project>
Some dependencies have been introduced here, and the corresponding functions have been commented out in the code. Note: Using the parent tag to introduce all the dependencies of the parent class, if necessary, can be removed using exclusion, referencing 31-41 lines of code.
Also note that groovy support is introduced here, which allows our compilers to create and write groovy code.
The final plugin is used to package the jar and must be added before the project can be packaged and published using the MAVEN command.
c. Create a Application.yml file
The properties can be created here, but the yml file is more intuitive, and idea can be highlighted, and some of the official demos are configured using YML:
MyBatis: mapperlocations:classpath:mybatis/*-mapper.xml config:classpath:mybatis/mybatis-conf.xml TypeAliasesPackage:com.fndroid checkconfiglocation:falsespring: DataSource: url:jdbc:mysql:// Localhost:3306/books?servertimezone=utc&usessl=false username:root password:root Driver-class-name:com.mysql.cj.jdbc.driver
Some of the properties of the MyBatis are configured here, and Springboot will use the user-configured information when it checks to the user configuration, although it defaults to configuring the properties.
This configuration file is used in the application definition.
d. Create the MyBatis folder under the Resources directory, in the configuration file used to place the MyBatis and the mapper file
E. In the Src/main/java directory to create the corresponding package, respectively, DAO, Controller, Service, entity, respectively, for storing SPRINGMVC corresponding class
After the configuration is complete, the directory structure:
This is not the case for application and log4j.properties two files, which will be created when used later. Now that the project is basically built, you can start writing code.
② Writing Project Code
Just to be clear, this is groovy, which is simpler than Java code, and groovy is compiled to run in Java.
Depending on the function, you now want to get the corresponding results from the following two URLs:
Get all book information: Http://localhost:8080/books
Get the corresponding book information by ID: HTTP://LOCALHOST:8080/BOOK/2 (get book information with ID 2)
A. Based on the data table, create the corresponding entity class book. Create a groovy script named book in the entity package:
1 package com.fndroid.entity 2 3 Import javax.xml.bind.annotation.XmlRootElement 4 5 @XmlRootElement (name = ' Book ') 6 class Book {7 int ID 8 string title 9 string Description10 string Pub_time11 string Author12 Book () {}15 ( int id, string title, string description, String pub_time, string author) { This.id = id18 this.title = title19 this.description = description20 this.pub_time = Pub_time21 This.author = Author22 }23}
The class is not decorated, groovy is set to public by default, and the field is private by default, and groovy will default to the private field to generate setter and getter methods, so we don't have to write it ourselves.
B. Create the controller and create the Bookcontroller in the package that the controller corresponds to:
1 package Com.fndroid.controller 2 3 import com.fndroid.entity.Book 4 import com.fndroid.services.BookServices 5 Import org.springframework.web.bind.annotation.PathVariable 6 Import Org.springframework.web.bind.annotation.RequestMapping 7 Import Org.springframework.web.bind.annotation.RestController 8 9 Import javax.annotation.Resource10 11 @ RestController12 class Bookcontroller { @Resource15 bookservice service;16 @RequestMapping ('/ Books ') list<book> getbooks () { service.getbooks () }21 @RequestMapping ('/book/{id} ') GetBook (@PathVariable (name = ' ID ') int id) { service.getbook (ID) }26}
This is the knowledge of SPRINGMVC, @RestController shows that this class is a restful controller.
Use @resource to indicate an object that gets bookservices by injection.
@RequestMapping is the path that indicates the request, and the corresponding method is executed according to the path.
@PathVariable used to get a value named ID in the path, used as a query
You can see that the method here has a return value type without a return statement, which is the attribute of groovy, which defaults to the last statement as the return value.
c. Create a services and define the corresponding methods:
The controller above uses a method of two bookservice, which we need to write:
1 package com.fndroid.services 2 3 import com.fndroid.entity.Book 4 import Com.fndroid.dao.IBookDao 5 import Org.spri Ngframework.stereotype.Service 6 7 Import Javax.annotation.Resource 8 @Service 9 class Bookservice {ten @ Resource11 Ibookdao bookdao;12 list<book> getbooks () {bookdao.getbooks () }16 Book GetBook (int id) { bookdao.getbook (ID) }20}
@Service indicate that this class is a service layer of SPRINGMVC and that the Ibookdao object is injected through annotations.
d. To create a DAO interface Ibookdao:
1 package Com.fndroid.dao 2 3 import com.fndroid.entity.Book 4 import org.springframework.stereotype.Repository 5< C1/>6 @Repository 7 Interface Ibookdao {8 list<book> getbooks () 9 book getBook (int id) 10}
@Repository indicates that this class is an entity bean class
Interface only needs to define the corresponding method.
E. Write the mapper file according to the interface and create a book-mapper.xml file in the MyBatis folder:
1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <! DOCTYPE Mapper 3 public "-//MYBATIS.ORG//DTD mapper 3.0//en" 4 "HTTP://MYBATIS.ORG/DTD/MYBATIS-3-MAPPER.DTD" > 5 <mapper namespace= "Com.fndroid.dao.IBookDao" > 6 <select id= "Getbooks" resulttype= " Com.fndroid.entity.Book "> 7 SELECT * FROM book 8 </select> 9 <select id=" GetBook "Resulttype = "Com.fndroid.entity.Book" parametertype= "Integer" >11 select * FROM book WHERE id = #{id}12 </select> </mapper>
Note here that the namespace of the mapper element needs to be defined as the full pathname of our DAO, followed by the definition of two select corresponding to our two methods, id corresponding to the method name, resulttype corresponding return value, parametertype corresponding parameter, Then write the SQL statement in select.
Note: Although Getbooks will return multiple rows here, Resulttype is still a book rather than a list, because MyBatis will help us assemble the list.
F. Define Mybatis-conf.xml
In general, the configuration for MyBatis, such as aliases, is declared in this file:
1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <! DOCTYPE Configuration 3 Public "-//mybatis.org//dtd Config 3.0//en" 4 "http://mybatis.org/dtd/ Mybatis-3-config.dtd "> 5 <configuration> 6 <settings> 7 <setting name=" Logimpl "value=" log4j "/> 8 </settings> 9 <typealiases>11 <typealias type=" Com.fndroid.entity.Book "alias=" book "/>12 </typealiases>13 </configuration>
If the book alias is defined here, the Mapper file above can be used instead of "Com.fndroid.entity.Book" using "book"
G. To create a program's entry application class:
1 Package com.fndroid 2 3 Import org.apache.ibatis.session.SqlSessionFactory 4 import Org.apache.tomcat.jdbc.pool.DataS Ource 5 Import Org.mybatis.spring.SqlSessionFactoryBean 6 import org.mybatis.spring.annotation.MapperScan 7 Import Org.mybatis.spring.boot.autoconfigure.MybatisProperties 8 Import org.springframework.boot.SpringApplication 9 Import ORG.SPRINGFRAMEWORK.BOOT.AUTOCONFIGURE.SPRINGBOOTAPPLICATION10 Import ORG.SPRINGFRAMEWORK.BOOT.CONTEXT.PROPERTIES.CONFIGURATIONPROPERTIES11 Import Org.springframework.context.annotation.Bean12 Import ORG.SPRINGFRAMEWORK.CONTEXT.ANNOTATION.PRIMARY13 Import Org.springframework.core.io.support.PathMatchingResourcePatternResolver14 Import ORG.SPRINGFRAMEWORK.JDBC.DATASOURCE.DATASOURCETRANSACTIONMANAGER15 Import Org.springframework.transaction.PlatformTransactionManager16 @SpringBootApplication18 @MapperScan (' Com.fndroid.dao ') class application {$ static void main (string[] args) {Springapplication.run (Applica Tion.class,args)}24 @Bean26 @ConfigurationProperties (prefix = ' spring.datasource ') DataSource datasource () {2 8 new DataSource ()}30 @Bean32 sqlsessionfactory sqlsessionfactory () throws Exception {33 def Sqlsessionfactorybean = new Sqlsessionfactorybean () Sqlsessionfactorybean.setdatasource (DataSource ()) 35 def resolve = resolver () + def mybatisproperties = this.mybatisproperties () Notoginseng sqlsessionfactorybean.s Etconfiglocation (Resolve.getresource (Mybatisproperties.getconfiglocation ())) 38 Sqlsessionfactorybean.setmapperlocations (Resolve.getresources (mybatisproperties.mapperlocations[0)) 39 Sqlsessionfactorybean.getobject ()}41 @Bean43 @Primary44 @ConfigurationProperties (prefix = ' mybatis ') Mybatisproperties mybatisproperties () {pathmatching new mybatisproperties ()}48 @Bean50 Resourcepatternresolver Resolver () {Wuyi new PathmatchingresourcePatternresolver ()}53 @Bean55 Platformtransactionmanager TransactionManager () {New Datasourcet Ransactionmanager (DataSource ()) 57}58}
16 lines @springbootapplication annotations indicate that this class is a portal for Springboot, and that features such as automatic configuration and component scanning (the class that scans annotation statements such as Controller and service) are initiated.
17 rows of @mapperscan indicate the search for mapper from under the DAO package (here Mapper refers to the corresponding DAO class)
The 21-23 row defines a main method, which is the entry for the program, which calls Springapplication's static method run to start a spring program
Line 25-29 injects an object of type DataSource with the annotation @bean, because DataSource's properties need to indicate the connection information of the database, so @configurationproperties annotations need to be added. This annotation will configure the corresponding attributes in the Application.yml file that we have previously defined to this DataSource object
31-40 rows are injected into the Sqlsessionfactory object by @bean annotations, which are called by the spring container for database operations. We want to set the mapper and conf paths configured in APPLICATION.YML to Sqlsessionfactorybean, and finally return a GetObject object through the Sqlsessionfactory method
42-47 lines use @bean annotations to obtain configuration information for the corresponding mybatis in the Application.yml file
The 54-57 line is to set the DataSource to Platformtranscationmanager, which allows spring to handle the JDBC transaction.
③ Configuring log
In fact, the project has been able to run here, but actually running the console does not have detailed operation information output, because we have removed the default logging in Pom.xml, that is, Logback. If you need to use Logback, it is simple to add a logback configuration file in resource. And here is the log4j, so you need to create a log4j.properties file in the resource, this can not be used yml, because log4j does not support.
1 # Global Configuration 2 log4j.rootlogger=info, stdout, file 3 # MyBatis configuration 4 log4j.logger.com.fndroid.dao.ibookdao=trace 5 # Console Output configuration 6 Log4j.appender.stdout=org.apache.log4j.consoleappender 7 log4j.appender.stdout.layout= Org.apache.log4j.PatternLayout 8 log4j.appender.stdout.layout.conversionpattern=%d%5p [%t]-%m%n 9 # File Output configuration 10 Log4j.appender.file=org.apache.log4j.fileappender11 log4j.appender.file.layout=org.apache.log4j.patternlayout12 log4j.appender.file.layout.conversionpattern=%d%5p [%t]-%m%n13 log4j.appender.file.file=d:/log.log4j14 Log4j.appender.file.immediateflush=true
Line 2nd declares that the log type of the root logger input is info, and the output object is console and file
The 4th line shows that for the corresponding DAO class, we want to display the query statement and the query result, so here is the trace
第6-8 Configuring console output, including display layout and formatting
第10-14 is the file output, including display layout, format and output path, etc.
Here, the project can already run the project at the terminal using the MAVEN command: MVN Spring-boot:run, or directly using idea to run the corresponding main method, and you can see that the console prints the information that the container opened, The corresponding log.log4j file is also generated in the D disk:
Here is the information for the success of the launch:
Access url:http://localhost:8080/books using debugging tools or a browser
The browser will display the corresponding XML result file:
Back to the console, you can see that the SQL statement is also output:
This proves that we have no problem with the log configuration.
Note: If a restart is required, the previous application must be closed, otherwise the port will be prompted for use.
④ Packaging
For Springboot projects, packaging is very simple, just use terminal input: MVN packag command to generate a jar file in the target directory of the project, using the Java-jar in a server environment only The Xxx.jar command launches the Springboot project.
Springboot, Groovy