Categories
Uncategorized

Spring Boot2 series of tutorials (a) pure Java project to build SSM

In Spring Boot project it is not normal XML configuration exists, it is not recommended because the Spring Boot XML, note that not does not support, Spring Boot Configuration recommend developers use Java to build the framework, Spring Boot, a large number of automation configuration is done by Java configuration, this set of implementation, we can also do it yourself, that is, they can also be used to build a pure Java environment SSM, namely in the project, any XML configuration does not exist, including web.xml .

Environmental requirements:

    SSM using pure Java environment to build, requires Tomcat version must be at least 7.

Fast Experience

1 Create Project

Creating a common Maven project (note that this may not be necessary to create a Web project), and add SpringMVC reliance, while here the need to use Servlet built environment, so we also need to introduce rely on the Servlet (must not use the low version of the Servlet ), the final pom.xml file as follows:


    org.springframework
    spring-webmvc
    5.1.6.RELEASE


    javax.servlet
    javax.servlet-api
    4.0.1
    provided

2 Add Spring configuration

After the project is successfully created, first add the Spring configuration file, as follows:

@Configuration
@ComponentScan(basePackages = "org.javaboy", useDefaultFilters = true, excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Controller.class)})
public class SpringConfig {
}

About this configuration, I said the following:

    @Configuration notes that this is a configuration class, in our case, this configuration acts like applicationContext.xml

    @ComponentScan annotation indicates scanning configuration package, inside xml configuration attributes and attributes are one to one, useDefaultFilters use the default filter, and then removing the Controller annotation, i.e. scan Spring container in addition to other Controller All Bean.

3 Add SpringMVC Configuration

Then again springmvc create profiles:

@Configuration
@ComponentScan(basePackages = "org.javaboy",useDefaultFilters = false,includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = Controller.class)})
public class SpringMVCConfig {
}

Note that if you do not need to add other additional configuration SpringMVC, so on it. That view resolvers, JSON parsing, file upload …… and so on, if you do not need to configure it, so on it.

4 Configure web.xml

At this point, we do not web.xml file, then we can use Java code to replace the web.xml file, here will be used WebApplicationInitializer, defined as follows:

public class WebInit implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws ServletException {
        //首先来加载 SpringMVC 的配置文件
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(SpringMVCConfig.class);
        // 添加 DispatcherServlet
        ServletRegistration.Dynamic springmvc = servletContext.addServlet("springmvc", new DispatcherServlet(ctx));
        // 给 DispatcherServlet 添加路径映射
        springmvc.addMapping("/");
        // 给 DispatcherServlet 添加启动时机
        springmvc.setLoadOnStartup(1);
    }
}

WebInit role similar to web.xml, this class needs to implement WebApplicationInitializer interface and interface methods to achieve, when the project started, onStartup method will be automatically executed, we can do some project initialization In this method, such as loading SpringMVC container, add filters, add The Listener added Servlet like.

note:

Since we just added SpringMVC WebInit in configuration, so that when the project will start to load SpringMVC container, and not to load the Spring container, if you must load the Spring container, we need to modify SpringMVC configuration, the configuration of the SpringMVC package also scan to scan @Configuration notes, and then load the Spring container, there is a solution to this problem is to give up Spring configuration directly in the project, all configuration directly into SpringMVC configuration to complete this integration in SSM when there is no problem in the actual development, more use of the second option, the second option, SpringMVC is as follows:

@Configuration
@ComponentScan(basePackages = "org.javaboy")
public class SpringMVCConfig {
}

This scenario, all of the notes are SpringMVC scans, using this program, then the Spring configuration file can be deleted.

5 Test

Finally, add a HelloController, and then start the test project:

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}

Start the project, access interface, results are as follows:

Other configurations 6

6.1 static resource filter

SpringMVC static resource filter in the XML configuration is as follows:

In the configuration of SSM Java environment, if you want to configure a static resource filter, need to inherit WebMvcConfigurationSupport SpringMVC configuration, the method WebMvcConfigurationSupport then rewritten as follows:

@Configuration
@ComponentScan(basePackages = "org.javaboy")
public class SpringMVCConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/js/**").addResourceLocations("classpath:/");
    }
}

AddResourceHandlers rewrite method, in this method to configure a static resource filter, where I will be placed under static resources resources directory, so the resource location is classpath: /, of course, resources can be placed under the webapp directory, then only need to modify the configuration the resource location. If Java environment to configure the SSM, in general, you do not have to use webapp directory, unless you want to use JSP page templates do otherwise negligible webapp directory.

6.2 View resolvers

In the XML file, view resolver configured by:


    
    

If Java classes, and they can also achieve similar functionality.

First add to our project webapp directory, add a webapp directory jsp directory, add jsp files jsp directory:

JSP dependence then introduced:


    javax.servlet.jsp
    javax.servlet.jsp-api
    2.3.1

Then, in the configuration class, the method continues to rewrite:

@Configuration
@ComponentScan(basePackages = "org.javaboy")
public class SpringMVCConfig extends WebMvcConfigurationSupport {
    @Override
    protected void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/jsp/", ".jsp");
    }
}

Next, add a controller in the Controller to access the JSP page:

@Controller
public class HelloController2 {
    @GetMapping("/hello2")
    public String hello() {
        return "hello";
    }
}

6.3 pathmap

Sometimes, our role is just a jump controller, like the controller in the above section, inside there is no business logic, as in this case, you can not define the method can be implemented directly by the path mapped page views . If the path disposed in the XML mapping, as follows:

This line configuration, if a user indicates to access / hello this path, the view called hello directly returned to the user, and the response code of 200, this configuration would be an alternative method for the Controller.

The same demand, if the Java code, written as follows:

@Configuration
@ComponentScan(basePackages = "org.javaboy")
public class SpringMVCConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/hello3").setViewName("hello");
    }
}

In this case, user access / hello3 interfaces, you can see the view file called hello.

6.4 JSON configuration

SpringMVC JSON may receive parameters, the parameters can return JSON, all this depends on HttpMessageConverter.

HttpMessageConverter a JSON string can be converted to an object, the object can also be converted to a string JSON, in fact it depends on the specific underlying or JSON libraries.

All JSON library to automatically return SpringMVC or receiving JSON, and must provide their own related HttpMessageConverter.

SpringMVC, the default provided Jackson and gson of HttpMessageConverter, namely: MappingJackson2HttpMessageConverter and GsonHttpMessageConverter.

Because of this, we SpringMVC, if you want to use JSON, for jackson and gson we just need to add a dependency, dependent on completion of the addition can be used directly. The specific configuration is done in AllEncompassingFormHttpMessageConverter class.

If the developer uses fastjson, then by default, SpringMVC does not provide fastjson of HttpMessageConverter, that we need to provide their own, if it is in the XML configuration, in addition to adding fastjson dependence, but also explicitly configured HttpMessageConverter, as follows:


    
        
        
    

In SSM Java configuration, as well as we can add this configuration:

@Configuration
@ComponentScan(basePackages = "org.javaboy")
public class SpringMVCConfig extends WebMvcConfigurationSupport {
    @Override
    protected void configureMessageConverters(List> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setCharset(Charset.forName("UTF-8"));
        converter.setFastJsonConfig(fastJsonConfig);
        converters.add(converter);
    }
}

Then, it can be directly returned in JSON interface, when JSON data generated by fastjson.

to sum up

Well, this article through a simple example demonstrates the use of Java to configure Spring + SpringMVC environment, in fact, as long as both configuration OK, then add MyBatis is a very easy thing to readers, the paper-related cases have been uploaded Song Ge on the GitHub: https: //github.com/lenve/javaboy-code-samples.

About this, there are discussion questions please leave a message.

Leave a Reply