Power node Mr. Wang he's SpringBoot introductory series of courses, easy to understand, based on SpringBoot 2 4 version explanation.
Start with the details and explain POM in each case Important dependencies in XML, followed by application configuration file, and finally code implementation. Let you know why, gradually let you master the automatic configuration of SpringBoot framework, starter start dependency and other features.
Video resources
https://www.bilibili.com/video/BV1XQ4y1m7ex
SpringBoot
Chapter 1 JavaConfig
- Why use Spring Boot
Because of Spring, Spring MVC needs to use a large number of configuration files (xml files)
You also need to configure various objects and put the used objects into the spring container to use the objects
You need to understand other framework configuration rules.
- Spring + boot configuration file is not required. Common frameworks and third-party libraries have been configured.
You can use it.
- SpringBoot has high development efficiency and is much more convenient to use
1.1 JavaConfig
JavaConfig: using java classes as an alternative to xml configuration files is a pure Java way to configure spring containers. In this Java class, you can create Java objects and put them into the spring container (inject them into the container),
Use two annotations:
1) @ Configuration: placed on top of a class, indicating that this class is used as a Configuration file.
2) @ Bean: declare the object and inject the object into the container.
example: package com.bjpowernode.config; import com.bjpowernode.vo.Student; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Configuration:Indicates that the current class is used as a configuration file. It is used to configure the container * Location: above the class * * SpringConfig This class is equivalent to beans xml */ @Configuration public class SpringConfig { /** * Create a method whose return value is an object. Add @ Bean to the method * The return value object of the method is injected into the container. * * @Bean: Inject the object into the spring container. Equivalent to < bean > * * Location: above the method * * Description: @ Bean, does not specify the name of the object. The default is the method name and id * */ @Bean public Student createStudent(){ Student s1 = new Student(); s1.setName("Zhang San"); s1.setAge(26); s1.setSex("male"); return s1; } /*** * Specify the name of the object in the container (specify the id attribute of < bean >) * @Bean Specifies the name (id) of the object */ @Bean(name = "lisiStudent") public Student makeStudent(){ Student s2 = new Student(); s2.setName("Li Si"); s2.setAge(22); s2.setSex("male"); return s2; } }
1.2 @ImporResource
@ImportResource is used to import other xml configuration files, which is the same as in xml
<import resources="Other profiles"/>
For example:
@Configuration @ImportResource(value ={ "classpath:applicationContext.xml","classpath:beans.xml"}) public class SpringConfig { }
1.3 @PropertyResource
@PropertyResource: read the properties property configuration file. External configuration can be realized by using the property configuration file,
Provide data outside the program code.
Steps:
- In the resources directory, create the properties file and provide data in the format of k=v
- Specify the location of the properties file in PropertyResource
- Use @ Value (value="${key}")
@Configuration @ImportResource(value ={ "classpath:applicationContext.xml","classpath:beans.xml"}) @PropertySource(value = "classpath:config.properties") @ComponentScan(basePackages = "com.bjpowernode.vo") public class SpringConfig { }
Chapter 2 Spring Boot
2.1 introduction
SpringBoot is a member of Spring, which can simplify the use of Spring and Spring MVC. Its core is the IOC container.
characteristic:
- Create stand-alone Spring applications
Create spring app
- Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
Embedded tomcat, jetty, Undertow
- Provide opinionated 'starter' dependencies to simplify your build configuration
starter start dependency is provided to simplify the configuration of applications.
For example, to use the MyBatis framework, you need to configure the object SqlSessionFactory of MyBatis and the proxy object of Dao in the Spring project
In the SpringBoot project, in POM XML, add a mybatis spring boot starter dependency
- Automatically configure Spring and 3rd party libraries whenever possible
Configure spring and third-party libraries as much as possible. It's called automatic configuration (that is to create objects in spring and third-party libraries and put them into containers for developers to use directly)
- Provide production-ready features such as metrics, health checks, and externalized configuration
Health check, statistics and externalized configuration are provided
- Absolutely no code generation and no requirement for XML configuration
There is no need to generate code or use xml for configuration
2.2 create Spring Boot project
2.2.1 the first way is to use the initializer provided by Spring, that is, the wizard to create a SpringBoot application
Address used: https://start.spring.io
Structure of SpringBoot project:
The external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG drfoatek-1645599534519) (D: \ course \ 25 springboot \ notes \ images\image-20210115152427829.png)
2.2.1 address in China
The transfer of external chain pictures failed. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-in52drb7-1645599534520) (D: \ course \ 25 springboot \ notes \ images \ image-2021011515556662. PNG)
2.3 use of notes
@SpringBootApplication Compliance note: by @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan 1.@SpringBootConfiguration @Configuration public @interface SpringBootConfiguration { @AliasFor( annotation = Configuration.class ) boolean proxyBeanMethods() default true; } Note: used@SpringBootConfiguration Annotated classes can be used as configuration files, have access to Bean Declare the object and inject it into the container
2.@EnableAutoConfiguration
Enable automatic configuration, configure java objects and inject them into the spring container. For example, you can create the object of mybatis and put it into the container
3.@ComponentScan
@ComponentScan Scanner, find annotations, create objects according to the functions of annotations, assign values to attributes, etc. Packages scanned by default: @ComponentScan The package and sub package of the class.
2.4 SpringBoot configuration file
Profile name: application
The extensions are: properties (k = V); yml ( k: v)
Use application properties, application. yml
Example 1: application Properties sets the port and context
#Set port number server.port=8082 #Set access application context path, contextpath server.servlet.context-path=/myboot
Example 2: application yml
server: port: 8083 servlet: context-path: /myboot2
2.5 multi environment configuration
There are development environment, test environment and online environment.
Each environment has different configuration information, such as port, upper and lower files, database url, user name, password and so on
Using multi environment configuration files, you can easily switch different configurations.
Usage: create multiple configuration files. Name rule: application - environment name properties(yml)
Create the configuration file of the development environment: application-dev.properties (application-dev.yml)
Create the configuration used by the tester: application test properties
2.6 @ConfigurationProperties
@ConfigurationProperties: map the data of the configuration file to java objects.
Attribute: the beginning of some key s in the prefix configuration file.
@Component @ConfigurationProperties(prefix = "school") public class SchoolInfo { private String name; private String website; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "SchoolInfo{" + "name='" + name + '\'' + ", website='" + website + '\'' + ", address='" + address + '\'' + '}'; } }
application.properties
#Configure port number server.port=8082 #context-path server.servlet.context-path=/myboot #Custom key=value school.name=Dynamic node school.website=www.bjpowernode.com school.address=Daxing District of Beijing site=www.bjpowernode.com
2.7 using jsp
SpringBoot does not recommend using jsp, but uses template technology instead of jsp
To use jsp, you need to configure:
1) Add a dependency to handle jsp. Responsible for compiling jsp files
<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency>
2) If you need to use the functions of servlet, jsp and jstl
<dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency>
3) Create a directory for storing JSPS, commonly called webapp
index.jsp
4) Need to be in POM XML specifies the storage directory of the compiled jsp file.
META-INF/resources
5) Create Controller and access jsp
6) In application Configure view parser in propertis file
2.8 use of containers
You want to get objects from the container through code.
Via springapplication run(Application.class, args); Get container with return value.
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) { return run(new Class[]{primarySource}, args); } ConfigurableApplicationContext : Interface, yes ApplicationContext Sub interface of public interface ConfigurableApplicationContext extends ApplicationContext
2.9 ComnandLineRunner interface, applicationrunner interface
Both interfaces have a run method. Execution time after the container object is created, the run () method is automatically executed.
You can complete some customized operations created in the container object.
@FunctionalInterface public interface CommandLineRunner { void run(String... args) throws Exception; } @FunctionalInterface public interface ApplicationRunner { void run(ApplicationArguments args) throws Exception; }
Chapter 3 Web components
Talk about three contents: interceptor, Servlet and Filter
3.1 interceptor
Interceptor is an object in spring MVC, which can interceptor requests to Controller.
There are system interceptors in the interceptor framework, and you can also customize interceptors. Realize the pre-processing of requests.
Implement custom interceptors:
- Create a class to implement the HandlerInterceptor interface of the spring MVC framework
public interface HandlerInterceptor {
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
2. Declare the interceptor in the configuration file of spring MVC
<mvc:interceptors> <mvc:interceptor> <mvc:path="url" /> <bean class="Interceptor class fully qualified name"/> </mvc:interceptor> </mvc:interceptors>
Register interceptors in SpringBoot:
@Configuration public class MyAppConfig implements WebMvcConfigurer { //Add interceptor objects and inject them into the container @Override public void addInterceptors(InterceptorRegistry registry) { //Create interceptor object HandlerInterceptor interceptor = new LoginInterceptor(); //Specifies the uri address of the intercepted request String path []= {"/user/**"}; //Specify an address that is not blocked String excludePath [] = {"/user/login"}; registry.addInterceptor(interceptor) .addPathPatterns(path) .excludePathPatterns(excludePath); } }
3.2 Servlet
Use Servlet objects in the SpringBoot framework.
Use steps:
- Create a Servlet class. Create class inheritance HttpServlet
- Register the Servlet so that the framework can find the Servlet
example:
1. Create a custom Servlet
//Create Servlet class public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Use HttpServletResponse to output data and response results resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); out.println("===The implementation is Servlet=="); out.flush(); out.close(); } }
- Register Servlet
@Configuration public class WebApplictionConfig { //Define methods and register Servlet objects @Bean public ServletRegistrationBean servletRegistrationBean(){ //public ServletRegistrationBean(T servlet, String... urlMappings) //The first parameter is the Servlet object and the second is the url address //ServletRegistrationBean bean = //new ServletRegistrationBean( new MyServlet(),"/myservlet"); ServletRegistrationBean bean = new ServletRegistrationBean(); bean.setServlet( new MyServlet()); bean.addUrlMappings("/login","/test"); // <url-pattern> return bean; } }
3.3 Filter
Filter is a filter in Servlet specification. It can process requests and adjust the parameters and attributes of requests. Character encoding is often handled in filters
Use filters in frames:
- Create a custom filter class
- Register Filter object
example:
// Custom filter public class MyFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("Yes MyFilter,doFilter "); filterChain.doFilter(servletRequest,servletResponse); } }
Register Filter
@Configuration public class WebApplicationConfig { @Bean public FilterRegistrationBean filterRegistrationBean(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter( new MyFilter()); bean.addUrlPatterns("/user/*"); return bean; } }
3.4 character set filter
Characterencoding filter: solve the problem of garbled code in post requests
In the spring MVC framework, on the web XML registration filter. Configure his properties.
The first way:
Use steps:
- Configure character set filter
@Configuration
public class WebSystemConfig {
//Register Servlet
@Bean
public ServletRegistrationBean servletRegistrationBean(){
MyServlet myServlet = new MyServlet();
ServletRegistrationBean reg = new ServletRegistrationBean(myServlet,"/myservlet");
return reg;
}
//Register Filter
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean reg = new FilterRegistrationBean();
//Using filter classes in the framework
CharacterEncodingFilter filter = new CharacterEncodingFilter();
//Specifies the encoding used
filter.setEncoding("utf-8");
//Specify the value of encoding for both request and response
filter.setForceEncoding(true);
reg.setFilter(filter);
//Specify the url address of the filter
reg.addUrlPatterns("/*");
return reg;
}
}
- Modify application Properties file to make the custom filter work
#Characterencoding filter has been configured in SpringBoot by default. Code default ISO-8859-1 #Set enabled=false to close the configured filter in the system and use the custom characterencoding filter server.servlet.encoding.enabled=false
The second way
Modify application Properties file
server.port=9001 server.servlet.context-path=/myboot #Make the CharacterEncdoingFilter of the system effective server.servlet.encoding.enabled=true #Specifies the encoding used server.servlet.encoding.charset=utf-8 #Force request and response to use the value of charset attribute server.servlet.encoding.force=true
Chapter 4 ORM operation MySQL
Use the MyBatis framework to manipulate data and integrate MyBatis in the SpringBoot framework
Use steps:
- Mybatis start dependency: complete the automatic configuration of mybatis objects, and put the objects in the container
- pom.xml specifies that the xml files in the src/main/java directory are included in the classpath
- Create entity class Student
- Create Dao interface StudentDao and create a method to query students
- Create Mapper files and xml files corresponding to Dao interfaces, and write sql statements
- Create the Service layer object, and create the StudentService interface and its implementation class. Method to dao object. Complete database operation
- Create a Controller object and access the Service.
- Write application Properties file
Configure the connection information of the database.
The first way: @ Mapper
@Mapper: put it on the top of dao interface. Each interface needs to use this annotation.
/** * @Mapper: Tell MyBatis that this is the dao interface and create the proxy object of this interface. * Location: above the class */ @Mapper public interface StudentDao { Student selectById(@Param("stuId") Integer id); }
The second method is @ MapperScan
/** * @MapperScan: Find Dao interface and Mapper file * basePackages: Dao Package name of the interface */ @SpringBootApplication @MapperScan(basePackages = {"com.bjpowernode.dao","com.bjpowernode.mapper"}) public class Application { }
The third way: Mapper file and Dao interface are managed separately
Now put the Mapper file in the resources directory
1) Create a subdirectory (customized) in the resources directory, such as mapper
2) Put the mapper file in the mapper directory
3) In application In the properties file, specify the directory of the mapper file
#Specifies the location of the mapper file mybatis.mapper-locations=classpath:mapper/*.xml #Specify the log for mybatis mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
4) In POM XML specifies to compile the files in the resources directory into the target directory
<!--resources plug-in unit--> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> </resource> </resources>
Fourth transaction
Transactions in the Spring framework:
1) Transaction management object: transaction manager (interface, which has many implementation classes)
For example: use Jdbc or mybatis To access the database, use the following transaction manager: DataSourceTransactionManager
2) declarative transaction: specify the content of transaction control in the xml configuration file or with annotations
Control transactions: isolation level, propagation behavior, timeout
3) Transaction processing method:
1) Spring In frame@Transactional
2) aspectj The framework can be in xml In the configuration file, declare the contents of transaction control
Using transactions in SpringBoot: both of the above methods are OK.
1) Add @ Transactional to the business method. After adding annotation, the method has transaction function.
2) Explicitly add @ EnableTransactionManager to the main startup class
example:
/** * @Transactional: The representation method has transaction support * Default: use the isolation level of the library and the REQUIRED propagation behavior; Timeout - 1 * Throw a runtime exception and roll back the transaction */ @Transactional @Override public int addStudent(Student student) { System.out.println("Business method addStudent"); int rows = studentDao.insert(student); System.out.println("implement sql sentence"); //Throw a runtime exception to roll back the transaction //int m = 10 / 0 ; return rows; }
Chapter V interface architecture style - RESTful
Interface: API (Application Programming Interface) refers to some predefined interfaces (such as functions and HTTP interfaces), or software system Agreement on the connection of different components. Used to provide application program With developers based on a Software Or a set of hardware accessible routine Without having to access the source code or understand the internal Working mechanism Details.
Interface (API): it can refer to accessing the url of servlet and controller and calling the functions of other programs
Architecture style: api Organization (appearance)
Is a traditional: http://localhost:9002/mytrans/addStudent?name=lisi&age=26
The name of the accessed resource is provided on the address addStudent, Used later get Pass parameters by.
5.1 REST
RESTful architecture style
1)REST: (English: Representational State Transfer, Chinese: presentation layer state transfer).
REST: it is an interface architecture style and design concept, not a standard.
Advantages: more concise and hierarchical
Presentation layer state transition:
The presentation layer is the view layer, which displays resources through the view page, jsp Wait to display the results of operating resources.
Status: resource change
Transfer: resources can change. Resources can be created, new Status. After the resource is created, you can query the resource and see the content of the resource,
The content of this resource can be modified. The modified resource is different from the previous one.
2) Elements in REST:
Use REST to represent resources and operations on resources. In the Internet, it represents a resource or an operation.
Resources are represented by URLs. On the Internet, images, videos, texts, web pages and so on are resources.
Resources are represented by nouns.
For resources:
Query resources: look, through url Resource found.
Create resource: Add Resource
Update resource: update resource, edit
Deleting resources: removing
Resources are represented by URLs, and resources are represented by nouns.
stay url In, nouns are used to represent resources and information to access resources, stay url In, use“ / " Separate information about resources
http://localhost:8080/myboot/student/1001
Use the action in http (request mode) to represent the operation on resources (CURD)
GET: query resources -- sql select
Dealing with a single resource: in his singular way
http://localhost:8080/myboot/student/1001
http://localhost:8080/myboot/student/1001/1
Working with multiple resources: use the plural
http://localhost:8080/myboot/students/1001/1002
POST: create resource -- sql insert
http://localhost:8080/myboot/student
stay post Transfer data in request
<form action="http://localhost:8080/myboot/student" method="post"> full name:<input type="text" name="name" /> Age:<input type="text" name="age" /> </form>
PUT: update resources -- SQL update
<form action="http://localhost:8080/myboot/student/1" method="post">
full name:<input type="text" name="name" />
Age:<input type="text" name="age" />
<input type="hidden" name="_method" value="PUT" />
</form>
DELETE: DELETE resources -- sql delete
```xml
<a href=" http://localhost:8080/myboot/student/1 "> delete 1's data</a>
```
The required paging, sorting and other parameters are still placed after the url, such as
http://localhost:8080/myboot/students?page=1&pageSize=20
`
3) One sentence for REST:
use url Represents a resource, using http Action operation resources.
4) Annotation
@PathVariable: get data from url
@GetMapping: the supported get request method is equivalent to @ requestmapping (method = requestmethod. Get)
@PostMapping: supports post request mode, which is equivalent to @ requestmapping (method = requestmethod. Post)
@PutMapping: supports put request mode, which is equivalent to @ requestmapping (method = requestmethod. Put)
@DeleteMapping: supports the delete request method, which is equivalent to @ requestmapping (method = requestmethod. Delete)
@RestController: conforms to the annotation. It is a combination of @ Controller and @ ResponseBody.
Use on top of class@RestController , Indicates that all methods of the current class are added @ResponseBody
5) Postman: test tool
Using Postman: you can test get, post, put, delete and other requests
5.2 in page or ajax, put and delete requests are supported
There is a filter in spring MVC that supports the conversion of post requests to put and delete
Filter: org springframework. web. filter. HiddenHttpMethodFilter
Function: turn the post request into put and delete
Implementation steps:
- application.properties(yml): enable the use of HiddenHttpMethodFilter filter
- In the request page, include_ The method parameter, whose values are put and delete, is the post method used to initiate the request
Chapter VI Redis
Redis: a NoSQL database, which is often used as a cache
Redis data types: string, hash, set, Zset, list
Redis is a middleware: an independent server.
Famous clients in java: Jedis, lettuce, Redisson
In spring, there is a RedisTemplate (string RedisTemplate) in springboot, which handles the interaction with redis
6.1 configure Windows version of redis
Redis-x64-3.2.100.rar decompress to a non Chinese directory
redis-server.exe: server. Do not close it after startup
redis-cli.exe: client to access data in redis
redisclient-win32. x86_ 64.2.0. Jar: redis graphical interface client
Execution method: in the directory where this file is located, execute Java - jar redisclient-win32 x86_ 64.2.0. jar
lettuce client library used by RedisTemplate
<!--redis Start dependence: directly used in the project RedisTemplate(StringRedisTemplate)--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> data-redis Used lettuce Client Library Use in program RedisTemplate Class redis Data is actually called lettuce Methods in client
6.2 comparison between StringRedisTemplate and RedisTemplate
String redistemplate: k and v are treated as strings. The serialization of strings is used, which has good readability
RedisTemplate: serialize K and v and save them to redis. k. v is serialized content and cannot be recognized directly
Used by default jdk Serialization, which can be modified as premise serialization
Serialization: the process of converting an object into a transferable byte sequence is called serialization.
Deserialization: the process of restoring a byte sequence to an object is called deserialization.
Why serialization
The ultimate goal of serialization is that objects can be stored across platforms and transmitted over the network. The way of cross platform storage and network transmission is Io, and the data format supported by IO is byte array. We must make a rule (serialization) when converting the object into a byte array. When we read the data from the IO stream, we will restore the object back (deserialization) with this rule.
When serialization is required
From the above, I think you already know that all data that needs "cross platform storage" and "network transmission" need to be serialized.
In essence, both storage and network transmission need to save an object state into a byte format recognized by cross platform, and then other platforms can restore the object information through byte information analysis.
Serialization mode
Serialization is just a rule for disassembling and assembling objects, so there must be many kinds of rules. For example, the common serialization methods are:
JDK (cross language not supported), JSON, XML, Hessian, Kryo (cross language not supported), Thrift, Protofbuff
Student( name=zs, age=20) ---- { "name":"zs", "age":20 }
java serialization: convert java objects into byte [], binary data
JSON serialization: the JSON serialization function converts objects to or from JSON format. For example, convert a Student object into JSON string {"name": "Li Si", "age":29}), and deserialize (convert JSON string {"name": "Li Si", "age":29} into Student object)
Set the serialization method of key or value
// Use RedisTemplate to set serialization before accessing the value // Set serialization of key using String redisTemplate.setKeySerializer( new StringRedisSerializer()); // Set serialization of value redisTemplate.setValueSerializer( new StringRedisSerializer()); redisTemplate.opsForValue().set(k,v);
Chapter 7 SpringBoot integration Dubbo
7.1 see the documentation of SpringBoot inheriting Dubbo
https://github.com/apache/dubbo-spring-boot-project/blob/master/README_CN.md
7.2 public projects
Independent maven project: defines interfaces and data classes
public class Student implements Serializable { private static final long serialVersionUID = 1901229007746699151L; private Integer id; private String name; private Integer age; } public interface StudentService { Student queryStudent(Integer id); }
7.3 provider
Create a SpringBoot project
1) pom.xml
<dependencies> <!--To join a public project gav--> <dependency> <groupId>com.bjpowernode</groupId> <artifactId>022-interface-api</artifactId> <version>1.0.0</version> </dependency> <!--dubbo rely on--> <dependency> <groupId>org.apache.dubbo</groupId> <artifactId>dubbo-spring-boot-starter</artifactId> <version>2.7.8</version> </dependency> <!--zookeeper rely on--> <dependency> <groupId>org.apache.dubbo</groupId> <artifactId>dubbo-dependencies-zookeeper</artifactId> <version>2.7.8</version> <type>pom</type> <exclusions> <!-- exclude log4j rely on --> <exclusion> <artifactId>slf4j-log4j12</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> </dependencies>
2) Implementation interface
/** * Expose services using annotations in dubbo * @Component You don't have to add it */ @DubboService(interfaceClass = StudentService.class,version = "1.0",timeout = 5000) public class StudentServiceImpl implements StudentService { @Override public Student queryStudent(Integer id) { Student student = new Student(); if( 1001 == id){ student.setId(1001); student.setName("------1001-Zhang San"); student.setAge(20); } else if(1002 == id){ student.setId(1002); student.setName("#######1002 - Li Si "); student.setAge(22); } return student; } }
3)application.properties
#Configure service name dubbo:application name = "name" spring.application.name=studentservice-provider #Configure scanned packages, scanned @ DubboService dubbo.scan.base-packages=com.bjpowernode.service #Configure dubbo protocol #dubbo.protocol.name=dubbo #dubbo.protocol.port=20881 #Registration Center dubbo.registry.address=zookeeper://localhost:2181
4) Above the startup class
@SpringBootApplication @EnableDubbo public class ProviderApplication { public static void main(String[] args) { SpringApplication.run(ProviderApplication.class, args); } }
7.4 consumers
Create a SpringBoot project
1) pom.xml
<dependencies> <!--To join a public project gav--> <dependency> <groupId>com.bjpowernode</groupId> <artifactId>022-interface-api</artifactId> <version>1.0.0</version> </dependency> <!--dubbo rely on--> <dependency> <groupId>org.apache.dubbo</groupId> <artifactId>dubbo-spring-boot-starter</artifactId> <version>2.7.8</version> </dependency> <!--zookeeper rely on--> <dependency> <groupId>org.apache.dubbo</groupId> <artifactId>dubbo-dependencies-zookeeper</artifactId> <version>2.7.8</version> <type>pom</type> <exclusions> <!-- exclude log4j rely on --> <exclusion> <artifactId>slf4j-log4j12</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> </dependencies>
2) You can create a Controller or a Service
@RestController public class DubboController { /** * Reference the remote service and inject the created proxy object into the studentService */ //@DubboReference(interfaceClass = StudentService.class,version = "1.0") /** * interfaceClass is not used. The default is the data type of reference type */ @DubboReference(version = "1.0") private StudentService studentService; @GetMapping("/query") public String queryStudent(Integer id){ Student student = studentService.queryStudent(id); return "Call the remote interface to get the object:"+student; } }
3)application.properties
#Specify service name spring.application.name=consumer-application #Designated registry dubbo.registry.address=zookeeper://localhost:2181
7.5 practice
Technologies used: springboot, Dubbo, redis, mybatis
Student table:
The external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-wjoftbqs-1645599534521) (D: \ course \ 25 springboot \ notes \ images\image-20210119150418295.png)
CREATE TABLE student (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(255) COLLATE utf8_bin DEFAULT NULL,
phone varchar(11) COLLATE utf8_bin DEFAULT NULL,
age int(11) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
1) Registered student
phone It must be unique. If a mobile phone number already exists, the registration fails.
int addStudent(Student student);
Return value: int
1: login was successful
2 : Mobile number already exists
name At least two characters,
age Must be greater than 0
2) Query the student. Query the student according to the id.
arrive earlier than redis Query students if redis If there is no such student, query from the database and put the queried students into redis.
Check again later. This student should redis You can get it.
Student queryStudent(Integer id);
3) Using the Dubbo framework, addstudent and querystudent are implemented by service providers.
Consumers can be a Controller , Call the two methods of the provider. Realize registration and query.
4) The page uses html, ajax and jquery.
stay html Available on page form Register students and provide text box input id,Make a query.
Both registration and query use ajax Technology.
html,jquery.js All put resources/static In the directory
Chapter VIII packaging
8.1 packaging war
1. Create a jsp Application
2. Modify POM xml
1) Specify the packaged file name
<build> <!--Packaged file name--> <finalName>myboot</finalName> </build>
2) Specify jsp compilation directory
<!--resources Plug in, put jsp Compile to the specified directory--> <resources> <resource> <directory>src/main/webapp</directory> <targetPath>META-INF/resources</targetPath> <includes> <include>**/*.*</include> </includes> </resource> <!--mybatis is used, and the mapper file is placed in the src/main/java directory -- > <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <!--hold src/main/resources All the following files are included in classes catalogue--> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> </resource> </resources>
3) Performing packaging is war
<!--Packaging type--> <packaging>war</packaging>
4) The main boot class inherits SpringBootServletInitializer
/** * SpringBootServletInitializer: Only by inheriting this class can we use a separate tomcat server */ @SpringBootApplication public class JspApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(JspApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(JspApplication.class); } }
5) Deploy war
Put war in the release directory of servers such as tomcat. tomcat as an example, myboot Put war in tomcat/webapps directory.
8.2 package as jar
1. Create a project containing jsp
2. Modify POM xml
1) Specify the packaged file name
<build> <!--Packaged file name--> <finalName>myboot</finalName> </build>
2) Specify the springboot Maven plugin version
<plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <!--pack jar, have jsp File must be specified maven-plugin The version of the plug-in is 1.4.2.RELEASE--> <version>1.4.2.RELEASE</version> </plugin> </plugins>
3) Finally, execute maven clean package
stay target Directory, generating jar File, an example is myboot.jar
Perform independent springboot Project in cmd in java -jar myboot.jar
Chapter 9 Thymeleaf template engine
Thymeleaf: it is a template technology developed in java and runs on the server side. Send the processed data to the browser.
The template works as a view layer. Displays the of the data. Thymeleaf Is based on Html Language. Thymleaf Grammar is applied in
html Label. SpringBoot Framework integration Thymealeaf, use Thymeleaf replace jsp.
Thymeleaf's official website: http://www.thymeleaf.org
Thymeleaf official Manual: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
9.1 expression
- Standard variable expression
Syntax: ${key}
Function: get the text data of key. Key is the key in the scope of request. Use request setAttribute(), model. addAttribute()
In the html tag on the page, use th:text="${key}"
<div style="margin-left: 400px"> <h3>Standard variable expression: ${key}</h3> <p th:text="${site}">key non-existent</p> <br/> <p>obtain SysUser Object attribute value</p> <p th:text="${myuser.id}">id</p> <p th:text="${myuser.name}">full name</p> <p th:text="${myuser.sex}">full name: m male</p> <p th:text="${myuser.age}">Age</p> <p th:text="${myuser.getName()}">Get name usage getXXX</p> </div>
- Select variable expression (asterisk variable expression)
Syntax: * {key}
Function: to obtain the data corresponding to this key, * {key} needs to be used together with the th:object attribute.
The purpose is to simply obtain the attribute value of the object.
<p>Use * {} to get the property value of SysUser</p>
<div th:object="${myuser}">
<p th:text="*{id}"></p>
<p th:text="*{name}"></p>
<p th:text="*{sex}"></p>
<p th:text="*{age}"></p>
</div>
<p>Use * {} to complete the attribute value representing the object</p>
<p th:text="*{myuser.name}" ></p>
- link expression
Syntax: @ {url}
Function: indicates the link, which can
<script src="..."> , <link href="..."> <a href=".."> ,<form action="..."> <img src="...">
9.2 thymeleaf properties
The attribute is placed in the html element, which is the attribute of the html element, and the th prefix is added. Property does not change. After adding th, the value of the attribute is processed by the template engine. You can use variable expressions in attributes
For example:
<form action="/loginServlet" method="post"></form> <form th:action="/loginServlet" th:method="${methodAttr}"></form>
9.3 each
each loop can loop List and Array
Syntax:
In an html tag, use th:each
<div th:each="Collection loop member,Loop state variable:${key}"> <p th:text="${Collection loop member}" ></p> </div> Collection loop member,Loop state variable:Both names are custom. The name "loop state variable" can be undefined. The default is"Collection loop member Stat"
each loop Map
In an html tag, use th:each
<div th:each="Collection loop member,Loop state variable:${key}"> <p th:text="${Collection loop member.key}" ></p> <p th:text="${Cyclic member set.value}" ></p> </div> Collection loop member,Loop state variable:Both names are custom. The name "loop state variable" can be undefined. The default is"Collection loop member Stat" key:map In the collection key value: map aggregate key Corresponding value value
9.4 th:if
"th:if": judge the statement. When the condition is true, the html tag body will be displayed; otherwise, no else statement will be displayed
Syntax: <div th:if=" 10 > 0 "> Display text content </div>
There is also an opposite behavior between th:unless and th:if
Syntax: <div th:unless=" 10 < 0 "> When the condition is false Display label body content </div>
Example: if
<div style="margin-left: 400px"> <h3> if use</h3> <p th:if="${sex=='m'}">Gender is male</p> <p th:if="${isLogin}">Logged in to the system</p> <p th:if="${age > 20}">Older than 20</p> <!--""The null character is true--> <p th:if="${name}">name Is' '</p> <!--null yes false--> <p th:if="${isOld}"> isOld yes null</p> </div>
Example: unless
<div style="margin-left: 400px"> <h3>unless: The judgment condition is false,Display label body content</h3> <p th:unless="${sex=='f'}">Gender is male</p> <p th:unless="${isLogin}">Login system</p> <p th:unless="${isOld}"> isOld yes null </p> </div>
9.5 th:switch
th:switch is the same as switch in java
Syntax: <div th:switch="Value to compare"> <p th:case="Value 1"> Result 1 </p> <p th:case="Value 2"> Result 2 </p> <p th:case="*"> Default result </p> Above case Only one statement is executed </div>
9.6 th:inline
- Inline text: get the value of the expression outside the html tag
Syntax:
<p>The display name is: [${key}]]</p>
<div style="margin-left: 400px">
<h3>inline text, Displays the value of a variable using an inline expression</h3>
<div th:inline="text">
<p>I am[[${name}]],Age is[[${age}]]</p>
I am<span th:text="${name}"></span>,Age is<span th:text="${age}"></span>
</div>
<div>
<p>Use inline text</p>
<p>I am[[${name}]],Gender is[[${sex}]]</p>
</div>
</div>
- Inline javascript
example: <script type="text/javascript" th:inline="javascript"> var myname = [[${name}]]; var myage = [[${age}]]; //alert("data in the obtained template" + myname + "," + myage ") function fun(){ alert("Click the event to get the data "+ myname + ","+ [[${sex}]]) } </script>
9.7 literal quantity
example:
<div style="margin-left: 400px"> <h3>Text literal: A string enclosed in single quotes</h3> <p th:text="'I am'+${name}+',My city'+${city}">data display</p> <h3>Numeric literal</h3> <p th:if="${20>5}"> 20 Greater than 5</p> <h3>boolean Literal </h3> <p th:if="${isLogin == true}">The user has logged in to the system</p> <h3>null Literal </h3> <p th:if="${myuser != null}">have myuser data</p> </div>
9.8 string connection
There are two syntax for connection strings
1) Syntax uses single quotation marks to enclose strings and + to connect other strings or expressions
<p th:text="'I am'+${name}+',My city'+${city}">data display</p>
2) Syntax: use double vertical bars, | strings and expressions|
<p th:text="|I am ${name},My city ${city|"> Display data </p>
example:
<div style="margin-left: 400px"> <h3>String connection method 1: a string enclosed in single quotation marks</h3> <p th:text="'I am'+${name}+',My city'+${city}">data display</p> <br/> <br/> <h3>String connection mode 2:|Strings and expressions|</h3> <p th:text="|I am ${name},City ${city},someone else ${myuser.name}|"></p> </div>
9.9 operators
Arithmetic operation: + , - - , * , / , % relative comparative : > , < , >= , <= ( gt , lt , ge , le ) Equality judgment: == , != ( eq , ne ) <div style="margin-left: 400px"> <h3>Use operator</h3> <p th:text="${age > 10}">Older than 10 </p> <p th:text="${ 20 + 30 }">Display operation results</p> <p th:if="${myuser == null}">myuser yes null</p> <p th:if="${myuser eq null}">myuser yes null</p> <p th:if="${myuser ne null}">myuser no null</p> <p th:text="${isLogin == true ? 'User already logged in' : 'User needs to log in'}"></p> <p th:text="${isLogin == true ? ( age > 10 ? 'Users are greater than 10' : 'The user is relatively young') : 'User needs to log in'}"></p> </div> Ternary operator: expression? true Results : false Results Ternary operators can be nested
9.10 built in objects
Document address: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#web-context-namespaces-for-requestsession-attributes-etc.
#request means HttpServletRequest
#session represents the HttpSession object
Session represents the Map object. It is a simple representation of #d session, which is used to obtain the value of the key specified in the session
#session.getAttribute("loginname") == session.loginname
These are built-in objects that can be used directly in the template file.
example: <div style="margin-left: 350px"> <h3>Built in object#request,#Session, use of session</h3> <p>Get data in scope</p> <p th:text="${#request.getAttribute('requestData')}"></p> <p th:text="${#session.getAttribute('sessionData')}"></p> <p th:text="${session.loginname}"></p> <br/> <br/> <h3>Methods of using built-in objects</h3> getRequestURL=<span th:text="${#request.getRequestURL()}"></span><br/> getRequestURI=<span th:text="${#request.getRequestURI()}"></span><br/> getQueryString=<span th:text="${#request.getQueryString()}"></span><br/> getContextPath=<span th:text="${#request.getContextPath()}"></span><br/> getServerName=<span th:text="${#request.getServerName()}"></span><br/> getServerPort=<span th:text="${#request.getServerPort()}"></span><br/> </div>
9.11 built in tools
Built in tool types: some of Thymeleaf's own classes provide some processing methods for string, date and collection
#dates: tool class that handles the date handler
#Numbers: process numbers
#lists: handle the list collection
<div style="margin-left: 350px"> <h3>Date class object #dates</h3> <p th:text="${#dates.format(mydate )}"></p> <p th:text="${#dates.format(mydate,'yyyy-MM-dd')}"></p> <p th:text="${#dates.format(mydate,'yyyy-MM-dd HH:mm:ss')}"></p> <p th:text="${#dates.year(mydate)}"></p> <p th:text="${#dates.month(mydate)}"></p> <p th:text="${#dates.monthName(mydate)}"></p> <p th:text="${#dates.createNow()}"></p> <br/> <h3>Built in tool class#numbers, the number of operands</h3> <p th:text="${#numbers.formatCurrency(mynum)}"></p> <p th:text="${#numbers.formatDecimal(mynum,5,2)}"></p> <br/> <h3>Built in tool class#strings, operation string</h3> <p th:text="${#strings.toUpperCase(mystr)}"></p> <p th:text="${#strings.indexOf(mystr,'power')}"></p> <p th:text="${#strings.substring(mystr,2,5)}"></p> <p th:text="${#strings.substring(mystr,2)}"></p> <p th:text="${#strings. Concat (mystr, '-- Whampoa Military Academy developed by Java --'} "></p> <p th:text="${#strings.length(mystr)}"></p> <p th:text="${#strings.length('hello')}"></p> <p th:unless="${#strings. Isempty (mystr)} "> mystring is not an empty string</p> <br/> <h3>Built in tool class#lists, operation list set</h3> <p th:text="${#lists.size(mylist)}"></p> <p th:if="${#lists. Contains (mylist, 'a')} "> member a</p> <p th:if="!${#lists. Isempty (mylist)} "> the list set has multiple members</p> <br/> <h3>handle null</h3> <p th:text="${zoo?.dog?.name}"></p> </div>
9.12 custom templates
Templates are content reuse, defined once and used multiple times in other template files.
Template usage:
1. Define template
2. Use template
Template definition syntax:
th:fragment="Template custom name" For example: <div th:fragment="head"> <p> Dynamic node-java development </p> <p> www.bjpowernode.com </p> </div>
Reference template syntax:
1) ~{templatename :: selector} templatename: File name selector: Custom template name 2)templatename :: selector templatename: File name selector: Custom template name For templates containing:( th:include), Insert template(th:insert)
Chapter 10 summary
10.1 notes
Spring + SpringMVC + SpringBoot
To create an object: @Controller: Put it on the top of the class, create a controller object and inject it into the container @RestController: Put it on the top of the class, create the controller object and inject it into the container. Function: Compound annotation is@Controller , @ResponseBody, The return value of the controller method in this annotation class It's all data @Service : Put it on the implementation class of the business layer and create service Object, injecting into container @Repository : Put on dao On the implementation class of layer, create dao Object, put it into the container. This annotation is not used because it is used now MyBatis frame Frame, dao Object is MyBatis Generated by proxy. No need to use@Repository, So it's not used. @Component: Put it on the top of the class, create the object of this class, and put it into the container. Assigned: @Value : Assignment of a simple type, for example, above an attribute@Value("Li Si") private String name You can also use@Value,Get profile owner data( properties or yml). @Value("${server.port}") private Integer port @Autowired: Automatic injection of reference type assignment is supported byName, byType. Default is byType . It can be placed on the top of the attribute or on the structure Above the method. The recommendation is to put it on the construction method @Qualifer: Assign a value to the reference type, using byName Way. @Autowird, @Qualifer All Spring Provided by the framework. @Resource : come from jdk As defined in, javax.annotation. Implement automatic injection of reference types and support byName, byType. Default is byName, If byName Failed, reuse byType Inject. Use on properties other: @Configuration : Put it on the top of the class, indicating that it is a configuration class, which is equivalent to xml configuration file @Bean: Put it on the top of the method and inject the return value object of the method into the spring In the container. @ImportResource : Load other xml Configuration file, inject the objects in the file into spring In container @PropertySource : Read other properties Property profile @ComponentScan: Scanner, specify package name, scan annotation @ResponseBody: Put it on the top of the method, indicating that the return value of the method is data, not view @RequestBody : Read out the data in the request body and turn it into java Object usage. @ControllerAdvice: Controller enhancement, placed on the top of the class, indicates that this class provides methods to controller Enhancements. @ExceptionHandler : For exception handling, put it on the top of the method @Transcational : Dealing with affairs, put in service Implementation class public Above the method, it indicates that this method has transactions SpringBoot Annotations used in @SpringBootApplication : On the startup class, including@SpringBootConfiguration @EnableAutoConfiguration, @ComponentScan MyBatis Relevant notes @Mapper : Put it on top of the class and let MyBatis Find the interface and create its proxy object @MapperScan :Put it on the top of the main class, specify the scanned package, and create proxy objects for all interfaces in the package. Object into container @Param : Put on dao In front of the formal parameter of the method of the interface, it is used as a named parameter. Dubbo annotation @DubboService: Those used on the provider side and exposing services are placed on the implementation class of the interface @DubboReference: Used on the consumer side, reference the remote service and use it on the attribute. @EnableDubbo : It is placed on the main class to indicate that the current reference is enabled Dubbo Function.
Reference template syntax:
1) ~{templatename :: selector} templatename: File name selector: Custom template name 2)templatename :: selector templatename: File name selector: Custom template name For using templates: include templates( th:include), Insert template(th:insert)
Chapter 10 summary
10.1 notes
Spring + SpringMVC + SpringBoot
To create an object: @Controller: Put it on the top of the class, create a controller object and inject it into the container @RestController: Put it on the top of the class, create the controller object and inject it into the container. Function: Compound annotation is@Controller , @ResponseBody, The return value of the controller method in this annotation class It's all data @Service : Put it on the implementation class of the business layer and create service Object, injecting into container @Repository : Put on dao On the implementation class of layer, create dao Object, put it into the container. This annotation is not used because it is used now MyBatis frame Frame, dao Object is MyBatis Generated by proxy. No need to use@Repository, So it's not used. @Component: Put it on the top of the class, create the object of this class, and put it into the container. Assigned: @Value : Assignment of a simple type, for example, above an attribute@Value("Li Si") private String name You can also use@Value,Get profile owner data( properties or yml). @Value("${server.port}") private Integer port @Autowired: Automatic injection of reference type assignment is supported byName, byType. Default is byType . It can be placed on the top of the attribute or on the structure Above the method. The recommendation is to put it on the construction method @Qualifer: Assign a value to the reference type, using byName Way. @Autowird, @Qualifer All Spring Provided by the framework. @Resource : come from jdk As defined in, javax.annotation. Implement automatic injection of reference types and support byName, byType. Default is byName, If byName Failed, reuse byType Inject. Use on properties other: @Configuration : Put it on the top of the class, indicating that it is a configuration class, which is equivalent to xml configuration file @Bean: Put it on the top of the method and inject the return value object of the method into the spring In the container. @ImportResource : Load other xml Configuration file, inject the objects in the file into spring In container @PropertySource : Read other properties Property profile @ComponentScan: Scanner, specify package name, scan annotation @ResponseBody: Put it on the top of the method, indicating that the return value of the method is data, not view @RequestBody : Read out the data in the request body and turn it into java Object usage. @ControllerAdvice: Controller enhancement, placed on the top of the class, indicates that this class provides methods to controller Enhancements. @ExceptionHandler : For exception handling, put it on the top of the method @Transcational : Dealing with affairs, put in service Implementation class public Above the method, it indicates that this method has transactions SpringBoot Annotations used in @SpringBootApplication : On the startup class, including@SpringBootConfiguration @EnableAutoConfiguration, @ComponentScan MyBatis Relevant notes @Mapper : Put it on top of the class and let MyBatis Find the interface and create its proxy object @MapperScan :Put it on the top of the main class, specify the scanned package, and create proxy objects for all interfaces in the package. Object into container @Param : Put on dao In front of the formal parameter of the method of the interface, it is used as a named parameter. Dubbo annotation @DubboService: Those used on the provider side and exposing services are placed on the implementation class of the interface @DubboReference: Used on the consumer side, reference the remote service and use it on the attribute. @EnableDubbo : It is placed on the main class to indicate that the current reference is enabled Dubbo Function.