springmvc是配置在web工程中的,首先使用maven创建标准web工程,创建好的工程目录如下
在pom.xml中添加一个依赖就可以
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.17.RELEASE</version> </dependency> |
maven会自动下载spring-webmvc所有依赖的包
freemarker模板引擎
添加依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>3.2.17.RELEASE</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency> ncy> |
在控制层创建一个测试类
package com.llh.springmvc.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class TestController { @RequestMapping("/test") public String test(){ System.out.println("springMVC is running"); return "success"; } } |
在src/main/resources目录下创建一个文件“springmvc-init.xml”,内容如下
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--扫描所有的控制层 --> <context:component-scan base-package="com.llh.springmvc.controllers" /> <!--配置freemarker视图解析器 --> <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/page/" /> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="suffix" value=".ftl" /> <property name="contentType" value="text/html; charset=UTF-8" /> </bean> </beans> |
在WEB-INF目录建一个page目录,里面放一个success.ftl文件
<html> <body> <h2>success page</h2> </body> </html> |
启动工程,浏览器访问 http:localhost:8080/springmvc/test 就能看到返回 success page 值了,同时控制台打印出“springMVC is running”。