搭建springMvc框架:
第一步:配置所需要的框架以及依赖注入
首先在pom.xml注入核心包:spring-context 也是就是spring框架
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
其次注入所需依赖:
<!-- spring web-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
<!-- spring mvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.14.RELEASE</version>
</dependency>
</dependencies>
第二步:添加一个springmvc.xml文件,并配置文件
因为使用注解,所以需要注解扫描,并配置注解约束:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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="包名.文件名"></context:component-scan>
</beans>
第三步:配置springmvc前端控制器
因为servlet容器与spring容器不在同一个容器中,servlet容器不能访问spring容器;所以就需要DispatcherServlet去做,需要在在web.xml中配置DispatcherServlet
<!-- spring mvc前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- /表示根目录下的所有非静态资源请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
第四步:编写controller
package com.hs.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloWorldController {
// http://localhost:8080/mvc/hello
@RequestMapping("/mvc/hello")
public String hello(){
System.out.println("hello,world!");
// return "forward:/hello.jsp";
return "redirect:/hello.jsp";
}
}
第五步:部署到tomcat上即可运行