XML configuration does not normally exist in Spring Boot projects. This is because XML is not recommended in Spring Boot. Note that it is not not supported. A lot of the automated configuration is done through Java configuration, which we can do ourselves, that is, we can use pure Java to build an SSM environment, that is, there is no XML configuration in the project, including web.xml.

Environmental requirements:

  • To set up the SSM environment using pure Java, the Tomcat version must be later than 7.

Rapid experience

1 Creating a Project

Create a normal Maven project (note that you don’t need to create a Web project here), add SpringMVC dependencies, and build the environment using servlets. So we also need to introduce Servlet dependencies (never use older versions of servlets), and the resulting POM.xml file looks like this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.6. RELEASE</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>
Copy the code

2 Add the 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 {}Copy the code

About this configuration, I say the following:

  • The @Configuration annotation indicates that this is a Configuration class, and in our case, this Configuration acts like applicationContext.xml
  • UseDefaultFilters use the default filters, and then remove the Controller annotation. That is, all beans except Controller are scanned in the Spring container.

3 Add the SpringMVC configuration

Next, create the SpringMVC configuration file:

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

Note that if you don’t need to add any additional configuration in SpringMVC, this is fine. View parser, JSON parsing, file upload…… Wait, if none of them need to be configured, this is fine.

4 configuration web. XML

At this point, we don’t have a web. The XML file, then we can use Java code to replace web. XML files, here will use WebApplicationInitializer, concrete are defined as follows:

public class WebInit implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws ServletException {
        // Load the SpringMVC configuration file first
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(SpringMVCConfig.class);
        / / add the DispatcherServlet
        ServletRegistration.Dynamic springmvc = servletContext.addServlet("springmvc".new DispatcherServlet(ctx));
        // Add path mapping to DispatcherServlet
        springmvc.addMapping("/");
        // Add boot time to DispatcherServlet
        springmvc.setLoadOnStartup(1); }}Copy the code

WebInit role similar to the web. The XML, this class needs to implement WebApplicationInitializer interfaces, and interface to realize the method, when the project starts, onStartup method will be executed automatically, we can do it in this way some project initialization, For example, load the SpringMVC container, add filters, add listeners, add servlets, etc.

Note:

Since we only add the SpringMVC configuration in WebInit, the project will only load the SpringMVC container at startup, not the Spring container. If we have to load the Spring container, we need to modify the SpringMVC configuration. The @Configuration annotation is also scanned in the package scan of the SpringMVC Configuration to load the Spring container. Another solution to this problem is to simply drop the Spring Configuration in the project. Directly put all the configuration into the configuration of SpringMVC, which is no problem in SSM integration. In actual development, the second scheme is often adopted. The second scheme is as follows:

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

In this scenario, all annotations are scanned in SpringMVC and Spring configuration files can be deleted.

5 test

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

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

Start the project and access the interface as follows:

6 Other Configurations

6.1 Static Resource Filtering

Static resource filtering is configured in the SpringMVC XML as follows:

<mvc:resources mapping="/ * *" location="/"/>
Copy the code

In the Java configuration of SSM environment, if you want to configure static resource filtering, need to make for SpringMVC WebMvcConfigurationSupport configuration inheritance, then rewrite the WebMvcConfigurationSupport method, as follows:

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

So I’m going to override the addResourceHandlers method and I’m going to do static resource filtering, so I’m going to put the static resources in the Resources directory, so CLASspath :/, and of course I can put the resources in the WebApp directory, You only need to change the location of the resource in the configuration. If you are using Java to configure your SSM environment, you generally do not need to use the WebApp directory, unless you are using JSP as a page template, you can ignore the WebApp directory.

6.2 View resolver

In the XML file, configure the view parser as follows:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>
Copy the code

You can do the same with Java classes.

First add webApp directory for our project, add a JSP directory to webApp directory, add JSP file to JSP directory:

Then we introduce JSP dependencies:

<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.1</version>
</dependency>
Copy the code

Then, in the configuration class, continue overriding the method:

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

Next, add the Controller to the Controller to access the JSP page:

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

6.3 Path Mapping

Sometimes, our controller is just a jump, like the controller in the previous section, where there is no business logic. In this case, the page can be accessed through a path map without defining a method. If path mapping is configured in XML, it looks like this:

<mvc:view-controller path="/hello" view-name="hello" status-code="200"/>
Copy the code

This configuration, which means that if the user accesses /hello, the view named Hello is directly returned to the user with a response code of 200. This configuration replaces the method in Controller.

The same requirement, if in Java code, is written as follows:

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

At this point, the user accesses the /hello3 interface and sees a view file named Hello.

6.4 JSON configuration

SpringMVC can either receive or return JSON parameters, depending on HttpMessageConverter.

HttpMessageConverter can convert a JSON string to an object, or an object to a JSON string, depending on the underlying JSON library.

All JSON libraries that automatically return or receive JSON in SpringMVC must provide their own associated HttpMessageConverter.

Jackson’s and Gson’s HttpMessageConverter are provided by default in SpringMVC: MappingJackson2HttpMessageConverter and GsonHttpMessageConverter.

Because of this, in SpringMVC, if we want to use JSON, for Jackson and Gson we just need to add dependencies and then we can use them. Specific configuration is done in AllEncompassingFormHttpMessageConverter class.

If the developer uses Fastjson, SpringMVC does not provide fastjson’s HttpMessageConverter by default. We need to provide this ourselves. Also explicitly configure HttpMessageConverter as follows:

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
Copy the code

In Java configuration SSM, we can also add the following 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); }}Copy the code

You can then return JSON directly in the interface, where the JSON data will be generated through FastJSON.

conclusion

This article shows you how to use Java to configure the Spring+SpringMVC environment. In fact, it is very easy to add MyBatis as long as these two configurations are OK. Github.com/lenve/javab… .

If you have any questions about this article, please leave a comment.