Spring MVC bootstrap w/ Gradle 2.2,Jetty 9 and Servlet 3.0

一个脚本搞定Spring MVC空壳项目的创建。包含:

  • 基于Gradle 2.2的构建脚本,这样使得所有第三方类库自动下载
  • 可以用gradle jettyRun启动Jetty 9运行web应用
  • 用Annotation配置servlet,无须web.xml
  • 自动化单元测试
  • 自动生成IntelliJ Idea的项目工程(使用build/classes作为编译好的class文件的输出目录)
  • 生成.gitignore方便排除无关文件,进行版本控制

这个脚本使用Unix shell写成的,主要用了here doc的特性。Windows的用户可能无法享受此脚本带来的便利,不过你可以装个Virtualbox或VMware然后跑个Linux Guest OS,即可享受到它带来的便利。

以下是脚本:

# .gitignore
cat << EOF > .gitignore
*.ipr
*.iml
*.iws
*.swp
*.swo
*.tgz
*.zip
build/
.gradle/
bootstrap.sh
EOF

# gradle build script
cat << EOF > build.gradle
plugins {
  id "org.akhikhl.gretty" version "1.1.8"
}

apply plugin: 'java'
apply plugin: 'idea'

repositories { mavenCentral() }
dependencies {
  compile "org.springframework:spring-context:3.2.12.RELEASE"
  compile "org.springframework:spring-web:3.2.12.RELEASE"
  compile "org.springframework:spring-webmvc:3.2.12.RELEASE"
  compile "javax.servlet:servlet-api:3.0-alpha-1"

  testCompile "org.springframework:spring-test:3.2.12.RELEASE"
  testCompile "junit:junit:4.11"
}

gretty {
    httpPort = 8080
    contextPath = '/spitter'
}

task wrapper(type: Wrapper) {
    gradleVersion = "2.2"
}

// Override Idea's default 'out' directory to use Gradle's //
// 'build/classes'
idea.project.ipr {
    withXml { provider ->
         provider.node.component
                 .find { it.@name == 'ProjectRootManager' }
                 .output.@url='file://$PROJECT_DIR$/build/classes'
    }
}

idea.module {
    outputDir = file('build/classes/main')
    testOutputDir = file('build/classes/test')
}
EOF

# setup directory layout
mkdir -p src/{main,test}/{java,resources}/org/home/spittr/{config,web,service}
mkdir -p src/{main,test}/java/org/home/spittr/web/controller
mkdir -p src/main/webapp/WEB-INF/views
mkdir -p src/main/webapp/css

# create Servlet 3.0 compliant ServletInitializer
cat << EOF > src/main/java/org/home/spittr/config/MyWebAppInitializer.java
package org.home.spittr.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected String[] getServletMappings() {
        return new String[] {
            "/"
        };
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] {
            RootConfig.class
        };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] {
            WebConfig.class
        };
    }
}
EOF

# create Java Config for web tier
cat << EOF > src/main/java/org/home/spittr/config/WebConfig.java
package org.home.spittr.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.home.spittr.web.controller.PackageMarker;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackageClasses={PackageMarker.class})
public class WebConfig extends WebMvcConfigurerAdapter {
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver =
                new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(
        DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}
EOF

# create controller marker interface to facilitate component scan
cat << EOF > src/main/java/org/home/spittr/web/controller/PackageMarker.java
package org.home.spittr.web.controller;

public interface PackageMarker {
}
EOF

# create service marker interface to facilitate component scan
cat << EOF > src/main/java/org/home/spittr/service/PackageMarker.java
package org.home.spittr.service;

public interface PackageMarker {
}
EOF

# create Java Config for middle tier
cat << EOF > src/main/java/org/home/spittr/config/RootConfig.java
package org.home.spittr.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ComponentScan;
import org.home.spittr.service.PackageMarker;

@Configuration
@ComponentScan(basePackageClasses={PackageMarker.class})
public class RootConfig {
}
EOF

# create HomeController
cat << EOF > src/main/java/org/home/spittr/web/controller/HomeController.java
package org.home.spittr.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.*;

@Controller
public class HomeController {
    @RequestMapping(value="/", method=GET)
    public String home() {
        return "home";
    }
}
EOF

# create unit test for HomeController
cat << EOF > src/test/java/org/home/spittr/web/controller/HomeControllerTest.java
package org.home.spittr.web.controller;

import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

public class HomeControllerTest {
    @Test
    public void testHomePage() throws Exception {
        HomeController controller = new HomeController();
        MockMvc mock = standaloneSetup(controller).build();
        mock.perform(get("/"))
            .andExpect(view().name("home"));
    }
}
EOF

# create style.css
cat << EOF > src/main/webapp/css/style.css
/* TODO: find a web artist to fix here */
h1 {
    backgroud-color: #F2F2CC;
}
a {
    backgroud-color: #E22FCC;
}
EOF

# create home.jsp
cat << EOF > src/main/webapp/WEB-INF/views/home.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
  <head>
    <title>Spittr</title>
    <link rel="stylesheet"
          type="text/css"
          href="<c:url value="/css/style.css" />" >
  </head>
  <body>
    <h1>Welcome to Spittr</h1>
    <a href="<c:url value="/spittles" />">Spittles</a> |
    <a href="<c:url value="/spitter/register" />">Register</a>
  </body>
</html>
EOF

# vim: set ai nu nobk expandtab ts=4 sw=4 tw=72 syntax=sh :

 

你可能感兴趣的:(spring mvc)