要將Groovy與Spring MVC結合使用,首先確保您已經配置了Spring框架和Spring MVC。然后,您可以按照以下步驟進行操作:
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>3.0.8</version>
</dependency>
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
@Controller
class MyGroovyController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
String hello() {
return "Hello, Groovy!"
}
}
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.example.controllers"})
public class MvcConfig implements WebMvcConfigurer {
}
@Configuration
public class GroovyConfig {
@Bean
public GroovyMarkupConfigurer groovyMarkupConfigurer() {
GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer();
configurer.setResourceLoaderPath("/WEB-INF/groovy/");
return configurer;
}
}
<mvc:view-controller path="/hello" view-name="hello" />
<!DOCTYPE html>
<html>
<head>
<title>Hello Groovy</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>
通過以上步驟,您就可以使用Groovy與Spring MVC結合來開發Web應用程序。您可以創建更多的Groovy Controller類,并在Spring MVC中配置它們,以實現更復雜的功能。