3.0、Spring-mvc注解实现
依赖的导入和之前1.0、2.0中的一样就不在重复展示了;
web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<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:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>
</web-app>
spring-mvc.xml配置文件
<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" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--自动扫描包,让制定包下的注解生效,由IOC统一管理-->
<context:component-scan base-package="com.hkl.controller" />
<!--让springmvc不处理静态资源,相当于一个过滤器。 静态资源例如:.css .js .html .mp3 .mp4-->
<mvc:default-servlet-handler/>
<!--之前我们想要完成url的处理以及Controller的适配,则需要配置handlermapping和handelAdepter这两个处理器并且需要将相应的Controller注入进来才可以。但是我们现在只需要开启annotation-driven即可完成,并且会自动注入Controller相应的bean-->
<mvc:annotation-driven/>
<!--视图解析器:DispatcherServlet给他的ModelAndView-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀-->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀-->
<property name="suffix" value=".jsp" />
</bean>
</beans>
HelloController.java配置文件
package com.hkl.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
//用Controller注解的类下的所有方法的返回值默认都会被视图解析器解析,然后去寻找相应的页面进行跳转
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(Model model) {
model.addAttribute("msg","欢迎来到SpringMVC");
return "hello";
}
}
最后补充一点如果依赖导入的时候出错就加入以下代码即可
pom.xml文件
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>