Getting a Spring MVC base

The first Spring MVC program

Spring version used here is 5.0.4, use that version, then, need jdk8 + version, that is your jdk version 8 or greater.

Step One:
Create a project, where we create a maven project, to help us manage the associated files maven jar, of course, you can also create a web project, but this is the case, you will need to manually download Spring MVC related jar package.

Step Two:
Import-related Jar package, use maven here to help us manage, here is the content pom.xml file, now just write a very simple Spring MVC, so only use maven imported spring-webmvc related packages you can:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.monkey1024</groupId>
    <artifactId>01-first</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>01-first Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId> 
            < Version > 5.0.4.RELEASE </ Version > 
        </ dependency > 

    </ the Dependencies > 
    < Build > 
        < finalName > 01-First </ finalName > 
        < plugins > 
            <-! Compiler plug-in, specify jdk compiled with the version -> 
            < plugin > 
                < the groupId > org.apache.maven.plugins </ the groupId > 
                < the artifactId > Maven-Compiler-plugin </artifactId>
                <configuration>
                    <!-- jdk的版本号 -->
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

The third step:
Sign of Spring MVC central controller the DispatcherServlet , open the web.xml file, add the following content in it:

<!-- 注册spring MVC中央控制器 -->
<servlet>
    <servlet-name>springMVC</servlet-name>
    <!-- spring MVC中的核心控制器 -->
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

 

 When we DispatcherServlet configured in the web.xml file, configure url-pattern * .do way, in fact, except this way you can also be configured in other ways (as well as which way is not important, it is important Here in this way)

* If the url-pattern is set to / after, as long as the match is not found in the web.xml file URL, they will be handed over to DispatcherServlet access request processing, static resource: css files, js files, images will be DispatcherServlet intercepted and handed over to treatment.
This arrangement does not intercept .jsp file and .jspx file, because the appropriate approach in tomcat web.xml file in the conf directory has been added in, and he will give org.apache.jasper.servlet. JspServlet to deal with. That we can access normal jsp file system.
Now restful style of URL and more popular, this / is also increasingly used in the configuration.

In the spring mvc provided in the mvc: resources tag is used to solve the problem of static resources can not be accessed , only need to add the following content springmvc.xml configuration file can be, this will give the ResourceHttpRequestHandler spring mvc class to handle:

<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/jsp/**" location="/jsp/" />
<mvc:resources mapping="/css/**" location="/css/" />
... ...

 

among them:

  • mapping indicates that the request for the resource. Note, followed by two asterisks **.
  • location represents the directory where the static resources, create a folder in the webapp images in my project, I will put all the pictures under this folder.

 

Step Four:
Maven project has a src / main / resources directory, create a Spring MVC in the directory configuration file springmvc.xml , the xml configuration file can be named, with the need param init-param third step in -value can be consistent.

 

the fifth step:

Creating a class to implement org.springframework.web.servlet.mvc. Controller interface, usually we call this class Controller, before learning of its role somewhat similar to servlet, or which can be considered in Spring MVC, the Controller is to use instead of a servlet, it provides a richer than the servlet functionality.

 

package com.monkey1024.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class HelloSpringMVC implements Controller{

    @Override
    public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.addObject("hello", "hello first spring mvc");
         Mv.setViewName ( "/WEB-INF/jsp/first.jsp"); // (rear view resolver may be abbreviated using configuration codes)
         return Music Videos; 
    } 
}

View resolver configuration

In the controller, we passed jsp to jump in there setViewName method ModelAndView the path and name, if there are multiple controller, then, it is required to write the name and path in each jsp inside, this is the case more complicated, then we can solve this problem by using a view resolver Spring MVC to us.
Open springmvc.xml configuration file, add a view resolver in which:

<!-- 视图解释类 -->
<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
<-! Prefix represents the prefix, the path to your jsp where that is. ->
<-! Suffix represents a suffix name suffix that file. ->
 
 
 <property name="suffix" value=".jsp" /> </bean>

In springmvc.xml file has been configured file path and extension, so amended as follows:

mv.setViewName("first");

 

 

Step Six:
Register Controller fifth step created in springmvc.xml configuration file, add the following content:

<bean id="/hello.do" class="com.monkey1024.controller.HelloSpringMVC" />

In the actual development, we will create a lot Controller to meet the needs of business, which would lead to a problem, you need to configure a large number of results in the bean configuration files become bloated up in springmvc.xml configuration file in order to solve this problem, spring MVC provides a series of notes, by setting the notes, you can make springmvc.xml profile becomes simple.

Use annotations written in spring with a whole step MVC program before almost (do not forget to add a central controller DispatherServlet in the web.xml file), but there are some places need to be amended to add the following content before the spring MVC program.

1, registration scanner
in the configuration file we only need to register a scanner component to which the base-package write your name to the package, following such an approach is that it would scan all packages and classes com.monkey1024 under, the scanner is a component of the spring content, the specific content in the spring.

<!-- 注册组件扫描器 -->
<context:component-scan base-package="com.monkey1024.*"/>

<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>

 

Note: If a static resource in your file that is used springmvc.xml

mvc:resources

Label, then you need to configure the annotation-driven configuration file, add the following content:

<mvc:annotation-driven/>

If you do not add annotations drive, you will be 404 when access controller error.

2, the processor defines
create a class TestController at com.monkey1024.controller package:

package com.monkey1024.controller;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller()

public class TestController {

    @RequestMapping("/test/test1.do")
    public ModelAndView test1(HttpServletRequest request, HttpServletResponse response) throws Exception{

        ModelAndView mv = new ModelAndView();
        mv.addObject("hello", "test1");
        mv.setViewName("test1");
        return mv;
    }


    @RequestMapping({"test/test2.do", "test/hello.do"})
    public ModelAndView test2(HttpServletRequest request, HttpServletResponse response) throws Exception{

        ModelAndView mv = new ModelAndView();
        mv.addObject("hello", "test2");
        mv.setViewName("test2");
        return mv;
    }

}

Here jsp creation is omitted, start tomcat, spring MVC will invoke the appropriate method for url you entered.

The annotation processor

In the above example, we created a TestController class does not implement any of these interfaces, just add two notes on the class name and method:

  • @Controller: indicates the current class as a Controller
  • @RequestMapping: Controller indicates that the current method is a method in which the attribute value To of the specified processing in response to the URL, the name of the annotation process can be arbitrarily named. When there are multiple requests may be matched to this method, a write array of type String test2 method, as examples.
    @RequestMapping annotation may also be defined in the class above, in the above example, the method test1 and test2 method contains the url path / test, this time we have these same url extracted, placed on annotation class @ RequestMapping in this case can be called a namespace.
package com.monkey1024.controller;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller()
@RequestMapping("/test")//类名上的注解,命名空间namespace
public class TestController02 {

    @RequestMapping("/test1.do")
    public ModelAndView test1(HttpServletRequest request, HttpServletResponse response) throws Exception{

        ModelAndView mv = new ModelAndView();
        mv.addObject("hello", "test1");
        mv.setViewName("test1");
        return mv;
    }


    @RequestMapping({"/test2.do", "/hello.do"})
    public ModelAndView test2(HttpServletRequest request, HttpServletResponse response) throws Exception{

        ModelAndView mv = new ModelAndView();
        mv.addObject("hello", "test2");
        mv.setViewName("test2");
        return mv;
    }

}

 

In common attributes RequestMapping

Wildcard @ RequestMapping ( "/ the Test * .do")

Request submission  @RequestMapping (value = "/test.do", Method = RequestMethod.POST )

Parameters carried in the request @RequestMapping ( value = "/test.do", the params = { "name", "Age"} )

Please refer to the original link .

 

 

 Step Seven:
Create a directory in jsp WEB-INF directory, create a first.jsp jsp files in this directory.

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
</head>
<body>
${hello}
</body>
</html>

 

 Step eight:

Start tomcat, and then in the browser address bar: HTTP: // localhost: 8080/01-First / hello.do
If you see a display hello first spring mvc web page, it shows the first Spring MVC programming success La.

 

Guess you like

Origin www.cnblogs.com/lucky1024/p/11118875.html