1.新建一个moudle,SpringMVC-03-annotation,然后添加web支持!
2.由于父项目已经导入了相关jar包,这里不用导入了。
3.配置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>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--通过初始化指定springmvc配置文件进行关联-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-config.xml</param-value>
</init-param>
<!--启动顺序,数字越小,启动越早-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--所有请求都会被springmvc拦截-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
< url-pattern > / </ url-pattern >中/和/*的区别:
- / :不会匹配到jsp页面,即.jsp不会进入 到DispatcherServlet类。
- /星 : 会匹配jsp页面,进入DispatcherServlet类,导致找不到对应的controller报404错误。例:一个url为:localhost:8080/hello.jsp,想访问一个hello.jsp界面,web.xml配置< url-pattern > /星 </ url-pattern >时,DispatcherServlet会把hello.jsp当成一个控制器,去controller里找,找不到报404,而不是当成一个界面去显示。
4.配置springmvc-config.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--注解扫描-->
<context:component-scan base-package="com.kuang.controller"/>
<!--让springnvc不处理静态资源-->
<mvc:default-servlet-handler/>
<!--支持mvc注解驱动-->
<mvc:annotation-driven/>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
在视图解析器中我们把所有的视图都放在/WEB-INF/目录下,这样可以保证视图安全,因为这个目录下的文件,客户端不能直接访问。
5.创建controller
@Controller
public class HelloController {
@RequestMapping("/h1")
public String test(Model model){
//传递数据
model.addAttribute("msg","hello HelloController");
//跳转页面
//web-inf/jsp/hello.jsp
return "hello";
}
}
配置文件扫描到@Controller知道这是一个控制器。
@RequestMapping("/h1")是为了映射请求路径,可以写在类上也可以写在方法上。
Model是ModelAndView简化版,只进行传递数据,也可以使用session等
return “hello”;会在视图解析器中,拼成一个完整路径,就变成web-inf/jsp/hello.jsp。
6.创建jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${
msg}
</body>
</html>
7.配置tomcat并执行
8.结果