What is for SpringMVC?

SpringMVC is a member of the Spring family, which is a framework for combining components that are currently popular in development! It is used for MVC based presentation layer development, similar to the Struts2 framework

Why use SpringMVC?

Struts2 is an MVC – based framework that we have learned about earlier…. So we already know Struts2, why learn SpringMVC??

Here’s a look at Struts2’s shortcomings:

  • There are loopholes [details can be searched]
  • Slow to run [slower than SpringMVC]
  • The struts. XML file is required.
  • Comparison heavyweight

For these reasons, and SpringMVC is gradually replacing Struts2 in the industry… So we learned that SpringMVC on the one hand allows us to keep up with the current framework in the industry, on the other hand SpringMVC is really good to use!

Suffice it to say, SpringMVC can do what Struts2 can do….

Review Struts2 development

In Struts2, our development features look like this:

  • The Action class inherits from the ActionSupport class.
  • The Action business method always returns a string to jump to the corresponding View from within Struts2 via our hand-written struts.xml configuration file
  • The Action class is multi-case, and receiving arguments from the Web requires instance variables to remember that we usually write set and GET methods

Struts2 workflow

  • Struts2 received a Request
  • Redirect the request to our filter batcher for filtering
  • Read the Struts2 configuration file
  • Create Action after default interceptor
  • The business method is returned to the Response object after execution

SpringMVC quick start

Importing the Development Package

The first six are the Spring core feature package [IOC], the seventh is about the Web, and the eighth is the SpringMVC package

  • Org. Springframework. The context – 3.0.5. RELEASE. The jar
  • Org. Springframework. Expression – 3.0.5. RELEASE. The jar
  • Org. Springframework. Core – 3.0.5. RELEASE. The jar
  • Org. Springframework. Beans – 3.0.5. RELEASE. The jar
  • Org. Springframework. Asm – 3.0.5. RELEASE. The jar
  • commons-logging.jar
  • Org. Springframework. Web – 3.0.5. RELEASE. The jar
  • Org. Springframework. Web. Servlet – 3.0.5. The jar

Write the Action

Action implements the Controller interface


public class HelloAction implements Controller {
    @Override
    public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
        return null; }}Copy the code

We just implement the handleRequest method, which already says request and Response objects for us to use. These are the request and Response objects that we are very familiar with. However, this method returns an object called ModelAndView, which is different from Struts2. Struts2 returns a string, SpringMVC returns a ModelAndView

ModelAndView encapsulates our view path and data (we just need to set the properties of the object where we want to jump to and what data we want to store in the Request field).


public class HelloAction implements Controller {
    @Override
    public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {


        ModelAndView modelAndView = new ModelAndView();

        // Jump to the hello.jsp page.
        modelAndView.setViewName("/hello.jsp");
        returnmodelAndView; }}Copy the code

Register core Controller

In Struts2, if we want to use Struts2 functionality, we have to configure filters in the web.xml file. When we use SpringMVC, we configure the core controller in web.xml


<! Register springMVC framework core controller -->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <! Go to the class directory to find our configuration file -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:hello.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <! -- Mapping path is.action-->
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
Copy the code

Create the SpringMVC controller

We create the SpringMVC controller in the hello.xml configuration file

    <! The value of the name property of the registered controller represents the path of the request.
    <bean class="HelloAction" name="/hello.action"></bean>
Copy the code

access

When we are in the browser to http://localhost:8080/hello.action, Spring will read our access paths, and then compare our configuration in a configuration file/hello. Action, if any. This is handled by the corresponding Action class. The business method of the Action class outputs its request to the Hello.jsp page.


SpringMVC workflow

  • User sends request
  • The request is processed by the core controller
  • The core controller goes to the mapper, and the mapper looks at what is the request path
  • The core Controller then finds the adapter to see which classes implement the Controller interface or corresponding bean objects
  • The data will be converted, formatted and so on
  • Find our controller Action and return a ModelAndView object when we’re done
  • Finally, the ModelAndView is parsed through the view parser
  • Jump to the corresponding JSP/ HTML page

We didn’t talk about mappers, adapters, and view parsers in the workflow above. But the SpringMVC environment was built.

The following by me to introduce them one by one is what use!

mapper

Our configuration in web.xml specifies that any request with the suffix.action will pass through the core Servlet of SpringMVC.

When we receive a request, we find that hello. Action will pass through our core Servlet, and the core Servlet will look for a specific action class to handle the hello. Action request.

In other words, the mapper handles the “what request to submit to Action” processing. 【 default omitted 】…..

The name property specifies hello. Action to be handled in the HelloAction controller!


    <! The value of the name property of the registered controller represents the path of the request.
    <bean class="HelloAction" name="/hello.action"></bean>
Copy the code

The mapper defaults to this:


  <! -- Register mapper (handler package)
	  <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
 	  </bean>
Copy the code

Of course, when we create the controller above [HelloAction], we can not use the name property to specify the path, we can use our mapper to configure it. Like the following code:

    <bean class="HelloAction" id="helloAction"></bean>

    <! Register mapper (Handler package)(framework) -->
    <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/hello.action">helloAction</prop>
            </props>
        </property>
    </bean>

Copy the code

When we need multiple request paths to be handled by the helloAction controller, we simply add the prop tag!


    <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/hello.action">helloAction</prop>
                <prop key="/bye.action">helloAction</prop>
            </props>
        </property>
    </bean>
Copy the code


The adapter

When our mapper finds the corresponding Action to handle the request, the core Controller asks the adapter to find out if the class implements the Controller interface. 3. Omitted by default

In other words: the adapter is looking for a class that implements the Controller interface


    <!-- 适配器【可省略】 -->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
Copy the code

View parser

After we wrap the results into the ModelAndView, SpringMVC uses the view parser to parse the ModelAndView. 3. Omitted by default

There is also a case that cannot be omitted. In our quickstart example, we encapsulate the results in ModelAndView, using absolute real paths! If we are using a logical path, we must configure it, otherwise SpringMVC will not find the corresponding path.

What is a logical path?? In Struts2, we return a string like “success” to jump to a page like success.jsp. We can call success a logical path.

In the Action, return Hello, which is a logical path. We need to use the view parser to complete the logical roadbed


    public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {


        ModelAndView modelAndView = new ModelAndView();

        // Jump to the hello.jsp page.
        modelAndView.setViewName("hello");
        return modelAndView;
    }
Copy the code

If you don’t use the view parser, the page will not be found:

Therefore, we need to configure the view resolver



    <! If the Action contains the logical name of the view, then the view parser must be configured. If the Action contains the real name of the view, then the view parser is optional.
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <! -- Path prefix -->
        <property name="prefix" value="/"/>
        <! -- Path suffix -->
        <property name="suffix" value=".jsp"/>
        <! -- Prefix + View logical name + suffix = true path -->
    </bean>
Copy the code

The controller

ParameterizableViewController

When we used Struts2 earlier, we also wrote business methods if we just wanted to jump to a WEB-INF/JSP page. The business method simply returns a simple string.

The following code:



public String home(a){

	return "home";
}

Copy the code
    <package name="nsfw-home" namespace="/nsfw" extends="struts-default">

        <action name="nsfw_*" class="zhongfucheng.nsfw.HomeAction" method="{1}">
            <result name="{1}">/WEB-INF/jsp/nsfw/{1}.jsp</result>
        </action>
    </package>
Copy the code

In SpringMVC, we can omit the Action and business method if we just jump to a view. Configure the Action as long as inherit the ParameterizableViewController this class!


    <! -- JSP to JSP/HTML forward controller -->
    <bean name="/ok.action" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
    	<! -- Forward to real view name -->
    	<property name="viewName" value="/WEB-INF/ok.jsp"/>
    </bean>
Copy the code

  • For now, it seems better to write in method. I think it would be more convenient to have unified management

AbstractCommandController

So far, we haven’t shown how SpringMVC receives arguments passed from the Web side.

In Struts2, we simply write the corresponding member variables on the Action class and give the corresponding set and GET methods. Struts2 will help us encapsulate the parameters into the corresponding member variables, which is very convenient.

So how do we get parameters in SpringMVC ???? We will Action is inherited AbstractCommandController such a class.


public class HelloAction extends AbstractCommandController {
    
    @Override
    protected ModelAndView handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, BindException e) throws Exception {
           
        return null; }}Copy the code

Before explaining this controller, we need to understand that SpringMVC controllers differ from Struts2 in one way: SpringMVC controllers are singletons, while Struts2 controllers are multi-instances!

That is: Struts2 collects variables by defining member variables for receiving, whereas SpringMVC, as a singleton, cannot use member variables for receiving.

So SpringMVC as a singleton, it can only be through the method parameters to receive the corresponding parameters! Only methods can ensure that different users correspond to different data!

entity

The attributes of the entity should match the name submitted by name on the Web page. This is the same as Struts2!


public class User {

    private String id;
    private String username;

    public User(a) {}public User(String id, String username) {
        this.id = id;
        this.username = username;
    }

    public String getId(a) {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUsername(a) {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString(a) {
        return "User{" +
                "id='" + id + '\' ' +
                ", username='" + username + '\' ' +
                '} '; }}Copy the code

Submit the JSP for the parameters


<form action="${pageContext.request.contextPath}/hello.action" method="post">
    <table align="center">
        <tr>
            <td>User name:</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>Serial number</td>
            <td><input type="text" name="id"></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="Submit">
            </td>
        </tr>
    </table>

</form>

Copy the code

Configure Action to handle requests


    <bean class="HelloAction" id="helloAction"></bean>


    <! Register mapper (Handler package)(framework) -->
    <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/hello.action">helloAction</prop>
            </props>
        </property>
    </bean>
Copy the code

Action Receive parameter


public class HelloAction extends AbstractCommandController {

    /* Sets the no-argument constructor, which calls the setCommandClass method, passing in the object to encapsulate */
    public HelloAction(a) {
        this.setCommandClass(User.class);
    }

    / * * * *@param httpServletRequest
     * @param httpServletResponse
     * @paramO The object here represents the encapsulated User object. ! *@param e
     * @return
     * @throws Exception
     */
    @Override
    protected ModelAndView handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, BindException e) throws Exception {

        User user = (User) o;

        System.out.println(user);

        ModelAndView modelAndView = new ModelAndView();
        // Jump to ok.jsp
        modelAndView.setViewName("/WEB-INF/ok.jsp");
        // Encapsulate the data in ModelAndView
        modelAndView.addObject("USER", user);
        returnmodelAndView; }}Copy the code

Effect:

A small summary

The difference between Struts2 and SpringMVC stores:

  • The SpringMVC workflow:
    • The user sends an HTTP request, and the SpringMVC core controller receives the request
    • Find the mapper to see if the request is referred to the appropriate Action class for processing
    • Find the adapter to see if the Action class exists
    • The Action class processes the result and encapsulates it in ModelAndView
    • Through the view parser to parse the data, jump to the corresponding JSP page
  • Two kinds of controller are introduced:
    • ParameterizableViewController
      • The ability to jump to web-INF resources without using write processing
    • AbstractCommandController
      • The encapsulation of parameter data can be realized

If the article has the wrong place welcome to correct, everybody exchanges with each other. Students who are used to reading technical articles on wechat and want to get more Java resources can follow the wechat public account :Java3y