wj0816

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

初次接触spring MVC项目,通过一段时间的学习,本文介绍一种以纯注解的方法去配置spring MVC环境,让那些配置的.xml文件统统见鬼吧。

什么是Spring MVC

  Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,从而在使用Spring进行WEB开发时,可以选择使用Spring的SpringMVC框架或集成其他MVC开发框架,如Struts1,Struts2等。

版本

本人使用64位的eclipse,版本是eclipse-jee-neon-R-win32-x86_64,下载地址:http://pan.baidu.com/s/1cfETtk;若有32位系统的同学请自行去官网下载。

其他的软件参数:

Tomcat: 8.0.44(下载地址:http://pan.baidu.com/s/1skF1PrJ)

JDK:1.8.0_60(下载地址:http://pan.baidu.com/s/1eSmYoRg)

Maven:3.5.0(下载地址:http://pan.baidu.com/s/1mhItVHQ)

Spring-framework: 4.0.4.RELEASE

可自行百度安装教程。

1)新建项目:

        file-new-other后,在Maven中选择Maven Project,如下图所示,

点Next,如下图所示

在这里Use default Workspace  location可能不同,不用管,直接点Next,如下图:

选择maven-archetype-webapp 1.0,点Next进入输入项目名的步骤。如下图

其中Actifact Id是项目名。点Finish完成项目创建。

       项目建好之后,目录结构如下:

                                                       

注:此时可能会提示index.jsp文件报错,此时右击项目名选择-Build Path-Configure Build Path,在Libraries下选择Add Library-Server Runtime后,选择安装的tomcat版本。

 

2)导入jar包

我们基于Spring mvc框架进行开发,需要依赖一下的spring jar包:

  • spring-aop-4.2.5.RELEASE.jar
  • spring-beans-4.2.5.RELEASE.jar
  • spring-context-4.2.5.RELEASE.jar
  • spring-core-4.2.5.RELEASE.jar
  • spring-expression-4.2.5.RELEASE.jar
  • spring-web-4.2.5.RELEASE.jar
  • spring-webmvc-4.2.5.RELEASE.jar
  • commons-logging-1.1.1.jar(用来打印log)

此时打开pom.xml文件导入上述的jar包

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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.wj.test</groupId>
    <artifactId>springmvc</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>springmvc Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <org.springframework.version>4.0.4.RELEASE</org.springframework.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!--Spring mvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>


    </dependencies>
    <build>
        <finalName>springmvc</finalName>
    </build>
</project>

 

这个时候,就该进行Spring配置了。按传统方式来的话,首先要去web.xml写一堆配置,然后建立个管理beab的Beans.xml,管理spring mvc 的xml,再写一坨一坨Bean。就是先进一点的(也就是很多人说的0配置),也就是自己的业务Bean不用写进xml了,还是很麻烦。

而我这里讲的方式,则是完全不修改任何web.xml代码,不写一行XML代码的方式。

3)配置文件及编写代码

首先,在项目立建立一个

SpringMvcConfig.java文件:
package com.wj.test.cfg;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

  /**
  * 取代Beans.xml,纯注解配置各种BEAN
  * @author wj
  *
  */

@Configuration
@EnableWebMvc
@ComponentScan(
        value = "com.wj.test", includeFilters = {
                @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class)
        })
        
public class SpringMvcConfig extends WebMvcConfigurerAdapter
{
    @Bean
    public ViewResolver viewResolver() 
    {
        //InternalResourceViewResolver;配置视图解析器
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setOrder(1);
        resolver.setPrefix("/WEB-INF/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}

@Configuration注解就是告诉Spring这个是一个配置文件类,这里配置的Bean要交给Spring去管理。这个就是用来取代Beans.xml这种文件的。

@ComponentScan("com.csonezp")这个注解就是配置包扫描用的,不必多说了

@EnableWebMvc ,启用Spring MVC支持

 

这里面配置了一个Bean就是JSP的视图解析器。这可以对应到XML文件里面去的。找一个传统Spring项目,用xml文件对比着我这个类去看,会对这种配置方式有更深的了解。

 

下面要建立一个WebInitializer类继承WebApplicationInitializer,在这里添加一个servlet。这一步是用来取代在web.xml中添加servlet的步骤

 

package com.wj.test.cfg;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

  /**
  * 取代在web.xml中添加servlet的步骤
  * @author wj
  *
  */

public class WebAppInitializer implements WebApplicationInitializer
{
    
    public void onStartup(final ServletContext sc) throws ServletException {

        AnnotationConfigWebApplicationContext  rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(SpringMvcConfig.class);
        rootContext.setServletContext(sc);

        DispatcherServlet dispatcherServlet = new DispatcherServlet(rootContext);

        ServletRegistration.Dynamic dynamic = sc.addServlet("dispatcherServlet", dispatcherServlet);
        dynamic.setLoadOnStartup(1);
        dynamic.addMapping("/");
    }
}

写到这里就已经完成了,现在写一个测试的代码试试。

 UserDao类:

package com.wj.test.mod;

public class UserDao
{
    private String name;
    private String hello;
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getHello()
    {
        return hello;
    }
    public void setHello(String hello)
    {
        this.hello = hello;
    }
}

Controller类:

package com.wj.test.web;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wj.test.mod.UserDao;

/**
 * Created by wj
 */
@RestController
public class TestController
{
    @RequestMapping("/test")
    public UserDao getToken(HttpServletRequest request)
    {
        UserDao user = new UserDao();
        user.setName(request.getParameter("name"));
        user.setHello("How are you?");
        return user;

    }
}

在这还需要导入三个关于json的.jar包,整个项目所需要的.jar包如下:

 

 

运行项目,在浏览器中输入http://localhost:8080/springmvc/test?name=God,最后的运行结果如下:

整个项目的结构图如下:

 

本文到此结束。

posted on 2017-06-22 21:34  wj0816  阅读(617)  评论(0编辑  收藏  举报