SpringMVC使用注解开发

2023-07-29,,

1.编写web.xml(模板代码)


2.导入springmvc的context和mvc两个依赖,通过context标签可以自动扫描识别包"com.lian.controller"下的所有注解,两个mvc标签是默认配置;context和mvc分别替代了之前的处理器映射器HandleMapper和处理器适配器HandlerAdapter;视图解析器拼接要要跳转的jsp页面,这样方便我们在Controller类进行跳转页面时候直接写jsp名就可以,更简洁

<?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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描包,让指定包下的注解生效,有IOC容器统一管理-->
<context:component-scan base-package="com.lian.controller"/>
<mvc:default-servlet-handler/>
<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>

3.编写Controller类

@Controller表示控制器,@RequestMapping表示映射路径

相比于之前我们编写Controller类是需要实现 Controller接口并重写handleRequest方法,在方法中封装数据并返回ModelAndView实例对象;通过注解之后想写多少个方法,在方法上添加注解就可以反映映射路径了

@Controller
public class HelloController {
@RequestMapping("/h1")
public String hello(Model model){
//封装数据
model.addAttribute("msg","Hello,SpringMVCAnnotation!");
return "test"; //会被视图解析器处理
}
}

4.编写Controller类要跳转的jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>

5.最后添加tomcat配置启动

SpringMVC使用注解开发的相关教程结束。

《SpringMVC使用注解开发.doc》

下载本文的Word格式文档,以方便收藏与打印。