Spring MVC项目快速搭建

一 点睛

Spring MVC提供了一个DispatcherServlet来开发Web项目。

在Servlet 2.5及以下的时候,只要在web.xml下配置<Servlet>元素就可以了。

但在Servlet 3.0下,可以实现无web.xml的配置。

在Spring MVC里实现WebApplicationInitializeer接口便实现等同web.xml的配置。

二 项目说明

基于Maven搭建零配置Spring MVC原型项目。

三 实战

1 构建Maven项目,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.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
       <groupId>com.wisely</groupId>
       <artifactId>highlight_springmvc4</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <packaging>war</packaging>
       <properties>
              <!-- Generic properties -->
              <java.version>1.7</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.1.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</groupId>
                     <artifactId>javax.servlet-api</artifactId>
                     <version>${servlet.version}</version>
                     <scope>provided</scope>
              </dependency>
              
              <dependency>
                     <groupId>javax.servlet.jsp</groupId>
                     <artifactId>jsp-api</artifactId>
                     <version>${jsp.version}</version>
                     <scope>provided</scope>
              </dependency>
              <!-- Spring and Transactions -->
              <dependency>
                     <groupId>org.springframework</groupId>
                     <artifactId>spring-tx</artifactId>
                     <version>${spring-framework.version}</version>
              </dependency>
              <!-- 使用SLF4J和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 日志配置

在src/main/resources目录下,新建logback.xml用来配置日志,内容如下:

<?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>logbak: %d{HH:mm:ss.SSS} %logger{36} - %msg%n</pattern>
              </encoder>
       </appender>
       <!-- 将org.springframework.web包下的类的日志级别设置我DEBUG,可以看到更详细的信息 -->
       <logger name="org.springframework.web" level="DEBUG" />
       <root level="info">
              <appender-ref ref="console" />
       </root>
</configuration>

3 演示页面编写

在src/main/resources下建立view目录,并在此目录下新建index.jsp,内容如下:

<%@ 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  Spring MVC配置

package com.wisely.highlight_springmvc4;

import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import com.wisely.highlight_springmvc4.interceptor.DemoInterceptor;
import com.wisely.highlight_springmvc4.messageconverter.MyMessageConverter;

@Configuration
@EnableWebMvc// 开启一些MVC的默认配置
@ComponentScan("com.wisely.highlight_springmvc4")
//Spring的配置类,这里配置了一个JSP的ViewResolver,用来映射路径和实际页面的位置
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/classes/views/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);
        return viewResolver;
    }
}

5 Web配置

package com.wisely.highlight_springmvc4;

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;
//WebApplicationInitializer是Spring提供用来配置Servlet3.0+配置的接口,从而实现
//替代web.xml的位置。实现此接口将会自动被SpringServletContainerInitializer(用来启动Servlet3.0容器)
//获取到。
public class WebInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext)
            throws ServletException {
        //新建WebApplicationContex
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        //注册配置类
        ctx.register(MyMvcConfig.class);
        //将其和当前servletContext关联。
        ctx.setServletContext(servletContext); 
        //注册Spring MVC的DispatcherServlet
        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx)); 
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
    }

}

6 编写简单控制器

package com.wisely.highlight_springmvc4.web;

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

@Controller//声明是一个控制器
public class HelloController {
    
    @RequestMapping("/index")//配置URL和方法之间的映射
    public  String hello(){
        //通过ViewResolver的Bean的配置,返回值为index,说明页面放置的位置
        //为WEB-INF/classes/views/index.jsp
        return "index";
    }

}

7 运行

将程序部署到Tomcat,启动Tomcat,并访问http://localhost:8080/highlight_springmvc4/index

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值