SpringBoot
1. First SpringBoot program
- application.properties core configuration file
- Main entry of Application program
- You can modify the banner manually
2. Preliminary study on principle
Auto configuration:
2.1,pom.xml
- Spring boot dependencies: the core dependencies are in the parent project
- When writing or introducing Springboot dependencies, you do not need to specify the version because there is a version warehouse.
2.2 starter
-
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
-
The initiator is prefixed with spring boot starter
-
To put it bluntly, it is the startup scenario of Springboot
-
Spring boot will turn all functional scenarios into initiators, such as spring boot starter web, which is often used in building the web.
-
What functions do we need to use? Just find the corresponding initiator to start
2.3 main program
@SpringBootApplication public class SpringbootstudyApplication { public static void main(String[] args) { //1. Return to IOC container ConfigurableApplicationContext run = SpringApplication.run(SpringbootstudyApplication.class, args); } }
-
annotation
-
@SpringBootConfiguration:Springboot Configuration of @Configuration: spring Configuration class @Component: This is a spring Components of @EnableAutoConfiguration: Auto configuration @AutoConfigurationPackage: Auto configuration package
-
Well, I gave up. It's too difficult, crazy p6
-
to make a long story short
Conclusion: all automatic configurations of spring boot are scanned and loaded at startup All automatic configuration classes of factories are here, but they do not necessarily take effect. First judge whether the conditions are true. As long as the corresponding start starter is imported, our automatic assembly will take effect, and then configure successfully.
- SpringBoot starts from meta-inf / spring. Inf in the classpath Get the value specified by EnableAutoConfiguration from factories
- Import these values into the container as automatic configuration classes, and the automatic configuration class will take effect to help us with automatic configuration;
- The whole J2EE solution and automatic configuration are in the jar package of springboot autoconfigure;
- It will import many automatic configuration classes (xxxAutoConfiguration) into the container, that is, import all components required for this scenario into the container and configure these components;
- With the automatic configuration class, it eliminates the work of manually writing configuration injection function components;
2.4,SpringApplication.run
The analysis of this method is mainly divided into two parts: one is the instantiation of spring application, and the other is the execution of run method;
1. Infer whether the type of application is a normal project or a Web project
2. Find and load all available initializers and set them in the initializers property
3. Find all the application listeners and set them in the listners property
4. Infer and set the definition class of the main method, and find the main class to run
3. SpringBoot configuration
3.1 yaml can directly assign values to entity classes
Syntax structure: key: space value
server: port: 8080 path: /hello
@Component //The following is the core of the entity class assigned by yaml //yaml is shown below @ConfigurationProperties(prefix = "person") @Data @AllArgsConstructor @NoArgsConstructor public class Person { private String name; private Integer age; private Boolean happy; private Date birth; private Map<String,Object> maps; private List<Object> lists; private Dog dog; }
[the external chain 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-igqcxn06-1627182587727) (C: \ users \ 86133 \ appdata \ roaming \ typora \ user images \ image-20210716101657578. PNG)]
3.2 JSR-303
@Validated//For data verification
[the external chain 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-3s9m9q82-1627182587728) (C: \ users \ 86133 \ appdata \ roaming \ typora user images \ image-20210716110452811. PNG)]
You can add the above annotation and verify that the corresponding element conforms to the format
If not, an error will be reported
[the external chain 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-asiauo2v-1627182587731) (C: \ users \ 86133 \ appdata \ roaming \ typora \ user images \ image-20210716110616514. PNG)]
Constraint location
[the external chain 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-c1lrnlae-1627182587739) (C: \ users \ 86133 \ appdata \ roaming \ typora \ user images \ image-20210716111235149. PNG)]
4. SpringBoot Web development
automatic assembly
Problems to be solved:
- Import static resources
- home page
- jsp, module engine Thymeleaf
- Assembly expansion spring MVC
- Add, delete, modify and query
- Interceptor
- internationalization?
4.1 static resources
1. In spring boot, we can handle static resources in the following ways
- webjars
- public,static,/**,resources localhost: 8080/
2. Priority: Resources > static (default) > public
4.2 customized home page
In the templates directory, all pages can only jump through the controller and need the support of the template engine
Just change the file name of the home page to "index.html" and put it under resources/static, and spring boot will automatically recognize and set it as the home page
If you need to modify the website Icon
springbootv2. Above 2.0, directly name it favicon ICO's website icon can be displayed in the resources or static directory
ps: it doesn't seem very good... Try it again next time (it seems to be speeding up again with another browser?)
4.3 template engine
Import corresponding dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
Conclusion: using thymeleaf, you only need to import the corresponding dependencies. Put the html in templates and use the controller to control it.
html files also need to add constraints
xmlns:th="https://www.thymeleaf.org/"
<div th:text="${msg}"/><div th:utext="${msg}"/><h3 th:each="user:${users}" th:text="${user}"/>
5. Web development practice
First go to the corresponding bootstrap template website to download the corresponding template. The template I use comes from Bootstrap · The most popular HTML, CSS, and JS library in the world. (getbootstrap.com)
5.1 home page configuration
Note: the static resources of all pages need to be taken over by thymeleaf@ {}
[the external chain 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-ybazqzm9-1627182587742) (C: \ users \ 86133 \ appdata \ roaming \ typora user images \ image-20210719150154880. PNG)]
5.2 page internationalization
By adding the configuration file of the corresponding language, see the following (take the login interface as an example)
spring.messages.basename=i18n.login
[the external chain 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-eji5u6og-1627182587743) (C: \ users \ 86133 \ appdata \ roaming \ typora user images \ image-20210719150108074. PNG)]
Also let thymeleaf take over# {}
[the external chain 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-ellovsnp-1627182587744) (C: \ users \ 86133 \ appdata \ roaming \ typora \ typora user images \ image-20210719150309489. PNG)]
If you need to automatically switch buttons in the project, we need to customize a component, LocaleResolver
And remember to configure the components you wrote to the Spring container @ Bean
LocaleResolver
public class MylocaleResolver implements LocaleResolver { @Override public Locale resolveLocale(HttpServletRequest request) { String lang = request.getParameter("lang"); Locale locale = Locale.getDefault(); if(lang!=null){ String[] split = lang.split("_"); locale = new Locale(split[0],split[1]); } return locale; } @Override public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { }}
MyMVCConfig
@Configurationpublic class MyMVCConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("index"); registry.addViewController("/index").setViewName("index"); registry.addViewController("/index.html").setViewName("index"); registry.addViewController("/dashboard").setViewName("dashboard"); } @Bean public LocaleResolver localeResolver(){ return new MylocaleResolver(); }}
5.3. Login interceptor
Create the LoginHandlerInterceptor class under the config folder and implement the HandlerInterceptor interface
public class LoginHandlerInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //Get loginemail through session string email = (string) request getSession(). getAttribute("loginEmail"); if(Email!=null){ return true; } Else {request.setattribute ("MSG", "you haven't logged in yet, please log in first"); request.getrequestdispatcher ("/ index"). Forward (request, response); return false;}// Return true release / / return false intercept}}
In MyMVCConfig, add an interceptor by overriding the addInterceptor function
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginHandlerInterceptor()) .addPathPatterns("/main.html","/employee")//Add places where interceptors need to be applied excludePathPatterns();// Exclude places where interceptors are not needed, such as static resources, etc.}
5.4. Display employee list
<table class="table table-striped table-sm"> <thead> <tr> <th>id</th> <th>lastName</th> <th>email</th> <th>gender</th> <th>department</th> <th>birth</th> <th>operation</th> </tr> </thead> <tbody><!-- This situation does not work redirect--> <tr th:each="em:${all}"> <td th:text="${em.getId()}"></td> <td th:text="${em.getLastName()}"></td> <td th:text="${em.getEmail()}"></td> <td th:text="${em.getGender()==0?'female':'male'}"></td> <td th:text="${em.getDepartment().getName()}"></td> <td th:text="${#dates. Format (em.getbirth(),'yyyy MM DD HH: mm: Ss')} "> < / td > < td > < button class =" BTN BTN SM BTN primary "> Edit < / button > < button class =" BTN BTN SM BTN danger "> delete < / button > < / td > < / TR > < / tbody > < / Table >
First through model AddAttribute to pass all, and then in employee HTML uses th: each to traverse the array of all
5.5 setting 404
Create an error folder under the templates folder and place 404 Html is enough
6,shiro
6.1 import dependency
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.3</version></dependency><dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>1.2.3</version></dependency><dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.3</version></dependency><dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.2.3</version></dependency><dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-quartz</artifactId> <version>1.2.3</version></dependency>
You can also import a package that integrates all at once
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-all</artifactId> <version>1.2.3</version></dependency>
6.2 creating ShiroConfig
Step 1: create a Realm, which requires a custom class
ShiroConfig.java
//Creating a Realm requires a custom class. The first step is @ bean public userrealm userrealm() {return new userrealm();}
UserRealm.java
//Customize userrealmpublic class userrealm extensions authorizingream {@ Autowired userService; / / authorize @ override protected authorizationinfo dogetauthorizationinfo (principalcollection) {system.out.println ("authorization executed") ; // Authorization SimpleAuthorizationInfo info = new SimpleAuthorizationInfo()// Get the object of the current user subject = securityutils getSubject(); User currentUser = (User) subject. getPrincipal();// Get the user object system out. println(currentUser.getPerms()); info. addStringPermission(currentUser.getPerms());// Add corresponding permission return info;}// Authentication @ override protected authenticationinfo dogetauthenticationinfo (authenticationtoken authenticationtoken) throws authenticationexception {system.out.println ("authentication executed"); usernamepasswordtoken token = (usernamepasswordtoken) authenticationtoken; user user = userService.queryuserbyname (token. Getusername()) );// Search for data in the database through userService if (user = = null) {return null; / / an exception is thrown automatically, UnknownAccountException} / / password authentication shiro returns new simpleauthenticationinfo (user, user. Getpwd(), "");}}
Step 2: create the DefaultWebSecurityManager and associate it with the Realm
ShiroConfig.java
//DefaultWebSecurityManager step 2 @ bean public DefaultWebSecurityManager getdefaultwebsecuritymanager (@ qualifier ("userrealm") userrealm userrealm) {DefaultWebSecurityManager securitymanager = new DefaultWebSecurityManager(); / / Associate real securitymanager.setrealm (userrealm); return securitymanager;}
Step 3: ShiroFilterFactoryBean
ShiroConfig
@Bean public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager securityManager){ ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); //Set the security manager bean setSecurityManager(securityManager); // Add shiro built-in filter / * anon: you can access authc without authentication: you must be authenticated to access user: you must have the remember me function to access perms: you must have permission to a resource to access role: you must have permission to a role to access * / map < string, String> map = new LinkedHashMap<>(); // Authorization map put("/add","perms[user:add]");// Set the access conditions of the web page (place filter) map put("/update","perms[user:update]"); bean. setFilterChainDefinitionMap(map); bean. setLoginUrl("/login"); bean. setUnauthorizedUrl("/unauthorized"); return bean; }
7,Swagger
- It is known as the most popular Api framework in the world
- RestFul Api document online automatic generation tool = > real time update of Api document and Api definition
- Run directly, and you can test the Api interface online
- Support multiple languages
Using Swagger in a project requires a Springbox
- swagger2
- ui
7.1 integration of Swagger in Springboot
1. Create a new springboot project - web
2. Import dependent
<!-- https://mvnrepository. com/artifact/io. springfox/springfox-swagger2 --><dependency> <groupId>io. springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version></dependency><!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --><dependency> <groupId>io. Springfox < / groupid > < artifactid > springfox swagger UI < / artifactid > < version > 2.9.2 < / version > if the version is 3.0.0, you may not be able to enter the page < / dependency >
3. Write a helloworld
4. Configure Swagger = = Config
@Configuration@EnableSwagger2//Open Swagger2public class SwaggerConfig {}
5. Visit Swagger page
http://localhost:8080/swagger-ui.html
7.2 configuring Swagger information
SwaggerConfig
@Configuration@EnableSwagger2//Open Swagger2public class SwaggerConfig {/ / bean instance @ bean public dock dock() {return new dock (documentationtype. Swagger_2). Apiinfo (apiinfo());} Public apiinfo apiinfo() {return new apiinfo ("lackoxy's swagger log", "hello", "v1.9"“ https://github.com/lackoxy ", new Contact("lackoxy", " https://github.com/lackoxy ", " 3272789289@qq.com "), "Apache 2.0", " http://www.apache.org/licenses/LICENSE-2.0 ", new ArrayList() ); }}
Screenshot after configuration
[the external chain 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-ds2nn6ij-1627182587746) (C: \ users \ 86133 \ appdata \ roaming \ typora user images \ image-2021072211753631. PNG)]
7.3 configure scanning interface and switch
SwaggerConfig
@Bean public Docket docket(Environment environment){ //Set the environment profiles to display swagger profiles = profiles of("test"); // Through environment Accept profiles to judge whether it is currently in the environment. Boolean flag = environment acceptsProfiles(profiles); return new Docket(DocumentationType.SWAGGER_2) . apiInfo(apiInfo()) . Enable (flag) / / whether the corresponding function is enabled Select() / / requesthandlerselectors configure the way to scan interfaces / / basePackage specifies the package to scan / / any() scan all / / none() do not scan / / withClassAnnotation() scan annotations on classes, such as contoller / / withmethodannotation() Annotations on scanning methods, such as getmapping APIs (requesthandlerselectors. basePackage ("com. Ding. Swaggerdemo. Controller") / / what path to filter paths(PathSelectors.none()) .build(); }
8. Mission
Asynchronous task
AsynService
@Servicepublic class AsynService { //Tell spring that this is an asynchronous method @ Async / / you also need to open this annotation method in the application class public void hello() {try {thread.sleep (3000); system. Out. Println ("Hao");} catch (InterruptedException e){ e.printStackTrace(); } System. out. Println ("data processing");}
AsyncController
@RestControllerpublic class AsyncController { @Autowired AsynService asynService; @RequestMapping("/hello") public String hello(){ asynService.hello();//Stop for three seconds return "alright";}}
Application.java
@SpringBootApplication@EnableAsync//Open asynchronous public class springboot08taskapplication {public static void main (string [] args) {springapplication.run (springboot08taskapplication. Class, args);}}
Timed task
ScheduledService
@Servicepublic class ScheduledService { //Cron expression / / second minute hour day of the week @ Scheduled(cron = "0 20 16 * *?")// It means that public void hello() {system.out.println ("executed");}}
At the same time, it must be added in the application class
@EnableScheduling//Notes for turning on the timing function
Mail sending
Dependency requirements
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> <version>2.5.2</version> </dependency>
Mailbox requirements: enable pop3 in the mailbox
application.properties
spring.mail.username=754428213@qq.comspring.mail.password=**************** #Get the corresponding code from the mailbox spring.mail.host=smtp.qq.com#Turn on encryption verification spring mail. properties. mail. smtp. ssl. enable=true
applicationTest.java
@Test void contextLoads() { //Simple sending of mail simplemailmessage message = new simplemailmessage(); message. setSubject("test java"); message. Settext ("arigado"); message. setTo(" 754428213@qq.com "); message.setFrom(" 754428213@qq.com "); sender.send (message);} @ test void contextloads2() throws messageexception {/ / send MimeMessage message = sender.createMimeMessage(); / / assemble mimemessagehelper helper helper = new mimemessagehelper (message, true); helper. Setsubject (" this is a complex message: springboot ") ;// Add topic helper Settext ("< H1 style ='color: Green '> OK!!! < / H1 >", true)// The following true indicates that HTML can be used for parsing, and text / / attachment helper.html can be added addAttachment("mylike1.jpg",new File("E:\pixiv\mylike1.jpg")); helper. setTo(" 1171201917@qq.com "); helper.setFrom(" 754428213@qq.com "); sender.send(message); }