Categories
Uncategorized

Spring Starter (XII): Spring MVC to use to explain

1. Spring MVC Introduction

Mention MVC, Web application development involved the students are familiar with, it is the presentation layer (may also be understood as a layer that is directly presented to the user) to develop an architectural model, M stands for Model, it refers to data model, V is the full name view, refers to a view of the page, such as JSP, Thymeleaf the like, C is the full name controller, refers to the controller for processing a user request at the client (browser) initiated.

Spring MVC is based on MVC pattern implementation, can help you build as flexible and loosely coupled Web application frameworks like Spring.

In other words, Spring MVC is based on Spring, it is mainly used to develop Web applications.

2. Spring MVC Request Process

In the Web application, is essential for the request, each request initiated by a user (client), to the end user (client) receiving the response, the figure shows a request in each experienced in Spring MVC Process:

Next we do the right figure for each process under explain:

    When asked to leave the browser (① in the figure) will be requested by the user with information content, URL and form information submitted such a request.

    And then proceeds to request the first station, the Spring of the DispatcherServlet, its task is to send the request to the controller Spring MVC.

    Because there are multiple controllers in applications, thus DispatcherServlet queries mapping one or more processors (handler mapping), the processor determines the mappings should send the request to which the controller (FIG request according to the URL carried the ②).

    The controller determines the good, the DispatcherServlet sends the request to the controller-determined, then the process waits for the user information submitted by the controller, but in general, almost no processing controller itself, but will give a commission business logic or processing a plurality of service objects (③ in the drawing).

    After the controller to complete the business logic processing, usually produces some models (Model) information, which needs to be returned to the user and displayed on the browser, in order to show a more friendly information, such as to display Html form, we need to send information to a view (view), such as JSP, Thymeleaf.

    The controller did last thing is to model data package, and mark the view name used for rendering output, it sends the request back to the DispatcherServlet (④ in the figure) along with the model and the view name, but the controller will only returns the logical name of a view, rather than returning specific to a particular view, this logic will be used to find the real name of view to produce results. DispatcherServlet uses resolver view (view resolver) to match the name of the logical view of a particular view (⑤ in the drawing), such as JSP or Thymeleaf.

    Finally, a stop request is to achieve a view (⑥ in the drawing) where the view data will be used to render the model output, this output is delivered to the user / client (⑦ in FIG.) Through the response object.

Spring MVC understand the request process, we then to understand how to build and configure at Spring MVC projects.

3. Spring MVC project to build

We still continue to use the blog before the new spring-action program, interested students can look at this series before 11 blog or download the source: https: //github.com/zwwhnly/spring-action.git.

3.1 Add dependence

To use Spring MVC, we need to add the following dependence in pom.xml:


    org.springframework
    spring-webmvc
    4.3.18.RELEASE




    javax.servlet
    jstl
    1.2


    javax.servlet
    javax.servlet-api
    4.0.1
    provided

Because behind To deploy the project to Tomcat, so we are packaged configuration package for the war in pom.xml:

war


    
        
        
            org.apache.maven.plugins
            maven-war-plugin
            3.2.3
            
                false
            
        
    

3.2 New Presentation page

New views directory under src / main / resources, then the new index.jsp page directory shown in the following:

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>


    Spring MVC


    
        Welcome to Spring MVC world
    


There may be a problem that, when the right-new JSP files, no templates JSP file, like this:

Solution as follows:

Click File – Project Structure, open the Project Structure dialog box, select the left Modules, and then click the plus sign and select Web

Right at this time the new JSP file again, you will see the JSP file template:

At this point the project root directory will generate a web folder, you can remove it.

3.3 Spring MVC configuration

MyMvcConfig new configuration class as follows:

package chapter05.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

/**
 * Spring MVC配置
 */
@Configuration
@EnableWebMvc
@ComponentScan("chapter05")
public class MyMvcConfig {
    /**
     * 视图解析器配置
     *
     * @return
     */
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

        viewResolver.setPrefix("/WEB-INF/classes/views/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);

        return viewResolver;
    }
}

Precautions:

1) This configuration class uses annotations to enable @EnableWebMvc Spring MVC, it will open some default configuration.

2) The configuration class configuration view resolvers, here we are configuring a JSP view resolvers.

View resolver, we set the prefix and suffix, logical view name If the controller is returned in index, looking for the actual rendering of the view that /WEB-INF/classes/views/index.jsp, the prefix is ​​why the set / WEB-INF / classes / views / instead of / src / main / resources / views / it, it is because the project directory is compiled runtime / WEB-INF / classes / views /.

If no jsp files compiled the directory, you need to add the following configuration in pom.xml:


    
        
            src/main/resources
            
                **/*.jsp
                **/*.js
            
        
    

3.4 Web Configuration

New Web-based configuration WebInitializer follows:

package chapter05.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

public class WebInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(MyMvcConfig.class);
        context.setServletContext(servletContext);

        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
    }
}

Here the focus should be concerned that the class implements the interface WebApplicationInitializer and rewrite the onStartup () method, WebApplicationInitializer Spring class is used to provide an interface Servlet 3.0+ version of the configuration, which can replace lost web.xml.

3.5 New Controller

New Controller HelloController follows:

package chapter05.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {
    @RequestMapping("/index")
    public String hello() {
        // 这里返回的逻辑视图名
        return "index";
    }
}

@Controller annotations in the code above statement which is a controller, @ RequestMapping ( “/ index”) is used to configure the URL mapping, and now the question is, how do we see the effect of the code to run it?

This involves a project to package and deploy the project, we continue to look down.

4. Project deployed in Tomcat

4.1 Packaging (war package)

Because our project is managed by Maven, in pom.xml is also equipped with a packaging bag and package plug-ins for the war, so we can find Maven Explorer on the right side of the IDEA, and as shown below, click on the clean:

Then click on the package:

War package finally generated as follows:

This is what we want to deploy to the war in Tomcat package.

4.2 Tomcat installation and deployment

Now that you are deploying to Tomcat, then there are two questions need to be answered:

    What is Tomcat?

    How to install Tomcat?

First answer the first question, Tomcat is a free open source lightweight Web application server, if you come into contact with the .NET Web development, it is similar to IIS.

To answer the second question, the following process to be installed Tomcat.

Open the Tomcat’s official website, find the version you want to download Tomcat, I choose here is the Tomcat 8.5.45 Released Version:

Then select the appropriate version to download because my development machine is Windows 64-bit operating system, so I chose the version shown below:

Once downloaded, unzip it to the directory you like, I unzipped the directory E: \ Tools \ apache-tomcat-8.5.45-windows-x64 \ apache-tomcat-8.5.45, after extraction is completed so long as :

Which is the site to deploy webapps directory.

After installation is complete, the question to consider is how to start Tomcat?

The first method is tomcat8.exe under double-click bin directory:

Then enter the address in the browser http: // localhost: 8080 /, see the following interface, on behalf of the Tomcat installation deployment success.

The disadvantage of using this method is that, if the tomcat8.exe open window closed, Tomcat will close, very inconvenient, it is recommended to use the second method, the Tomcat installed as a background service, let it run in the background , methods of operation as follows:

Then click open the computer – Properties – Advanced System Settings – Advanced – Environment Variables, new system variables:

Variable name: CATALINA_HOME

Variable values: E: \ Tools \ apache-tomcat-8.5.45-windows-x64 \ apache-tomcat-8.5.45 (you will extract the Tomcat directory)

Then edit the system variables Path, and finally add the following in its:

;%CATALINA_HOME%\lib;%CATALINA_HOME%\bin

Then open an administrator cmd window, switch to Tomcat’s bin directory, execute the command: service.bat install.

Then open Windows services list, you will see a Tomcat8 services:

Modify the service to start automatically and start the service can be running in the background Tomcat server.

If you’re curious why the new system variables must be CATALINA_HOME, you can use Notepad to open service.bat bin directory, see the following you will understand:

It can be seen from the figure, running the JAVA_HOME environment variable to rely Tomcat (JAVA SDK path configuration), but I had been previously arranged, as shown below:

4.3 package to deploy to the war in Tomcat

Previously packaged spring-action-1.0-SNAPSHOT.war copied to the Tomcat webapps directory:

Since we set up the Tomcat server running in the background became, after a while the directory will generate one and the same spring-action-1.0-SNAPSHOT war package file folder name, the directory structure is as follows:

Our view code and JSP files are classes file in WEB-INF directory folder:

Enter the browser address http: // localhost: 8080 / spring-action-1.0-SNAPSHOT / index, the page display as follows:

The source and reference

Source address: https: //github.com/zwwhnly/spring-action.git, welcome to download.

Craig Walls “Spring combat (4th Edition)”

Wang Yunfei “Java EE developers insurgents: Spring Boot real”

IntelliJ IDEA [] using the New option idea to solve new jsp jsp files can not find the file templates

Tomcat Installation and Configuration Tutorial

The method of installation and Tomcat running in the background

Finally, I welcome the focus on the micro-channel public number: “Shanghai Stranger” all blog gets updated.

Leave a Reply