1.创建项目

SpringMVC项目构建(Spring框架下) - 图1

2.添加依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>junit</groupId>
  4. <artifactId>junit</artifactId>
  5. <version>4.11</version>
  6. <scope>test</scope>
  7. </dependency>
  8. <dependency>
  9. <groupId>org.springframework</groupId>
  10. <artifactId>spring-context</artifactId>
  11. <version>5.2.7.RELEASE</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.springframework</groupId>
  15. <artifactId>spring-webmvc</artifactId>
  16. <version>5.2.7.RELEASE</version>
  17. </dependency>
  18. </dependencies>

3.在webapp下的WEB-INF下配置web.xml

  1. <!DOCTYPE web-app PUBLIC
  2. "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  3. "http://java.sun.com/dtd/web-app_2_3.dtd" >
  4. <web-app>
  5. <display-name>Archetype Created Web Application</display-name>
  6. <servlet>
  7. <servlet-name>springmvc</servlet-name>
  8. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  9. <init-param>
  10. <param-name>contextConfigLocation</param-name>
  11. <param-value>classpath:dispatcher-servlet.xml</param-value>
  12. </init-param>
  13. </servlet>
  14. <servlet-mapping>
  15. <servlet-name>springmvc</servlet-name>
  16. <url-pattern>/</url-pattern>
  17. </servlet-mapping>
  18. </web-app>

4.在resources下配置dispatcher-servlet.xml 配置自动注解和视图解析器

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xmlns:aop="http://www.springframework.org/schema/aop"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
  9. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
  10. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
  11. <context:component-scan base-package="com.note.spring"/>
  12. <mvc:annotation-driven/>
  13. <!-- 定义视图解析器 -->
  14. <bean id="velocityConfig"
  15. class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  16. <property name="prefix" value="/" />
  17. <property name="suffix" value="*.jsp" />
  18. </bean>
  19. </beans>

5.在com.note.spring目录下建立测试java文件

  1. @RestController
  2. public class HelloController {
  3. @GetMapping("/test")
  4. public String test(){
  5. return "Hello!!!";
  6. }
  7. }