관리 메뉴

심재운 블로그

IntelliJ 로 spring mvc + gradle 설정하기 본문

프로그래밍/JAVA

IntelliJ 로 spring mvc + gradle 설정하기

재우니 2017.02.08 14:35


springdemo.zip



폴더구조




build.gradle

group 'com.gradle.springdemo'
version '1.0-SNAPSHOT'

apply plugin: 'groovy'
apply plugin: 'java'
apply plugin: 'war'

sourceCompatibility = 1.8
targetCompatibility = 1.8

[compileJava, compileTestJava]*.options*.encoding = 'UTF-8' // 인코딩 UTF-8로 통일합니다.

repositories {
    mavenCentral()
}


def version = [
        spring: '4.1.6.RELEASE',
        servletAPI: '3.1.0',
        commonsCollections: '3.2.1',
        junit: '4.12',
        slf4j: '1.7.12'
]

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.3.11'
    providedCompile "javax.servlet:javax.servlet-api:${version.servletAPI}"
    compile "org.springframework:spring-webmvc:${version.spring}"
    compile "org.springframework:spring-context-support:${version.spring}"
    compile "org.springframework.data:spring-data-jpa:1.5.0.RELEASE"
    compile "org.slf4j:slf4j-api:${version.slf4j}"
    compile "org.apache.velocity:velocity:1.7"
    compile group: 'commons-collections', name: 'commons-collections', version: "${version.commonsCollections}"
    testCompile group: 'junit', name: 'junit', version: "${version.junit}"
}




AppConfig.java (먼저.. HomeController 가 호출되도록 컨트롤러를 지정한 부분이 있음)


package com.gradle.mvc.config;


import com.gradle.mvc.HomeController;
import org.apache.velocity.exception.VelocityException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.velocity.VelocityConfig;
import org.springframework.web.servlet.view.velocity.VelocityConfigurer;
import org.springframework.web.servlet.view.velocity.VelocityViewResolver;

import java.io.IOException;
import java.util.Properties;

@Configuration
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter {

    @Bean
    public HomeController homeController(){
        return new HomeController();
    }

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

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        // TODO Auto-generated method stub
        registry.addResourceHandler("/resources/**").addResourceLocations(
                "/resources/");
    }


    @Bean
    public ViewResolver getViewResolver() {

        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }


    @Bean
    public ViewResolver viewResolver() {
        VelocityViewResolver viewResolver = new VelocityViewResolver();
        viewResolver.setContentType("text/html; charset=UTF-8");
        viewResolver.setSuffix(".vm");
        viewResolver.setOrder(1);
        return viewResolver;
    }





    @Bean
    public VelocityConfig velocityConfig() throws VelocityException, IOException {
        VelocityConfigurer velocityConfig = new VelocityConfigurer();
        velocityConfig.setResourceLoaderPath("/WEB-INF/views/");
        Properties properties = new Properties();
        properties.put("input.encoding", "UTF-8");
        properties.put("output.encoding", "UTF-8");
        velocityConfig.setVelocityProperties(properties);
        return velocityConfig;
    }
}


AppInitializer.java (utf-8 로 인코딩함)


package com.gradle.mvc.config;

import javax.servlet.Filter;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * Created by luckshim on 2017-02-08.
 */
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

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

    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding("UTF-8");
        encodingFilter.setForceEncoding(true);
        return new Filter[] { encodingFilter };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}


HomeController.java (homes.vm 의 view 를 velocity 로 활용)


package com.gradle.mvc;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HomeController {

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);

        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        String formattedDate = dateFormat.format(date);
        model.addAttribute("serverTime", formattedDate);
        return "homes";
    }
}


home.jsp


<%--
  Created by IntelliJ IDEA.
  User: luckshim
  Date: 2017-02-07
  Time: 오후 6:53
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
여기는 home jsp 입니다. ${serverTime}
</body>
</html>


homes.vm


<html>
<head>
    <title>Title</title>
</head>
<body>
여기는 home vm 입니다. $serverTime
</body>
</html>


0 Comments
댓글쓰기 폼