SpringMVC学习--1 以一个实例开始

实例组成:
1、pom.xml:maven文件标明依赖和build插件。
2、logback.xml:配置logback日志,主要由根节点configuration、子节点、、组成。
3、index.jsp:用于展示的jsp文件。
4、@Configuration、@EnableMvc注解的配置类:使能MVC,并装配ViewResolver的Bean,用于将逻辑视图创建生成物理视图。
5、实现WebApplicationContextInitializer接口的类:用以替代web.xml。需要创建一个ApplicationContext,将其与ServletContext建立联系(相互包含),并将ApplicationContext作为SpringMVC的Servlet构造器参数创建Servlet,该Servlet被动态注册到ServletContext中。
6、@Controller注解的控制类:该类或类中方法用@RequestMapping注解用以表明URL与方法之间的映射。
7、本实例的服务器采用Tomcat8.5,其他亦可。

1. pom.xml

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.springmvc</groupId>
  <artifactId>com-springmvc</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>

    <!-- generic properties -->
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

    <!--web  -->
    <jsp.version>2.2</jsp.version>
    <jstl.version>1.2</jstl.version>
    <servlet.version>3.1.0</servlet.version>

    <!-- spring -->
    <spring-framework.version>4.3.5.RELEASE</spring-framework.version>

    <!-- logging -->
    <logback.version>1.0.13</logback.version>
    <slf4j.version>1.7.5</slf4j.version>

  </properties>

  <dependencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>

    <!-- Spring MVC -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring-framework.version}</version>
    </dependency>

    <!-- 其他web依赖 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>${jstl.version}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>${jsp.version}</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>${servlet.version}</version>
        <scope>provided</scope>
    </dependency>

    <!-- spring and transaction -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring-framework.version}</version>
    </dependency>

    <!-- SLF4J and logback -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.16</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>${logback.version}</version>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-core</artifactId>
        <version>${logback.version}</version>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-access</artifactId>
        <version>${logback.version}</version>
    </dependency>

  </dependencies>

  <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
  </build>
</project>

2. logback.xml(src.main.resource目录下)

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true"  scanPeriod="1 seconds">
    <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
        <resetJUL>true</resetJUL>
    </contextListener>

    <jmxConfigurator/>

    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>logback: %d{HH:mm:ss.SSS} %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <logger name="org.springframework.web" level="DEBUG"/>

    <root level="INFO">
        <appender-ref ref="console"/>
    </root>
</configuration>

3. index.jsp(遵循spring boot习惯,在src.main.resource的views下)

<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <pre>
        Welcome to Spring MVC world.
    </pre>
</body>
</html>

4. Configuration类

package com.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;

@Configuration
@ComponentScan("com")
@EnableWebMvc
public class MvcConfig {
    @Bean
    InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = 
                new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/classes/views/");
        viewResolver.setSuffix(".jsp");
        //JstlView is used to support java standard tag library and create jsp view
        viewResolver.setViewClass(JstlView.class); 
        return viewResolver;
    }
}

5. WebApplicationContextInitializer接口的实现类

package com.webapplicationinitializer;

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

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

import com.config.MvcConfig;

/** Use class that implements WebApplicationInitializer interface to  substitute web.xml
 * @author apple
 *
 */
public class WebInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext applicationContext = 
                new AnnotationConfigWebApplicationContext();
        applicationContext.register(MvcConfig.class); // process annotated class MvcConfig
        applicationContext.setServletContext(servletContext);  // make applicationContext and servletContext related
        applicationContext.refresh();

        //register new spring MVC servlet, and setup it, which is equal to the setting of <servlet> and <servlet-mapping> in web.xml.
        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(applicationContext));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);

    }

}

6. 控制器

package com.controller;

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

@Controller
public class HelloController {

    @RequestMapping("/index")
    public String hello() {
        //通过前面MvcConfig中ViewResolver  Bean的配置,返回值为index,说明请求页面放置在
        // /WEB-INF/classes/views/index.jsp
        return "index"; 
    }
}

7. 显示结果

地址栏:http://localhost:8080/com-springmvc/index
显示:Welcome to Spring MVC world.

猜你喜欢

转载自blog.csdn.net/xiewz1112/article/details/80517704