SpringMVC(三):SpringMVC的两种实现方式
一、方法一:实现Controller接口这个在我的第一个SpringMVC程序中已经学习过了,在此不作赘述,现在主要来学习第二种方法,使用注解开发;
二、方法二:使用注解开发
1.导包
2.在web.xml中配置DispatcherServlet
3.建立一个Spring配置文件springmvc-servlet.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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.jms.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>4.建立一个HelloController类
package com.jms.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "欢迎来到SpringMVC");
return "hello";
}
}可以看到,在这个类中,我们使用到了两种注解。
第一个是@Controller,使用这个注解就说明这个类是一个Handler;第二个是@RequestMapping,看名字就知道这是请求的映射,也就是我们需要请求的路径,这里是请求.../hello。
可以看见一个返回String的方法,返回的这个hello就说明跳转的路径是视图解析器中的“前缀”+hello+“后缀”,在这里也就是/WEB-INF/jsp/hello.jsp。
这里我们用一个model来存储数据。
5.启动tomcat测试
https://img2022.cnblogs.com/blog/2459242/202210/2459242-20221017135921650-553394477.png
(本文仅作个人学习记录用,如有纰漏敬请指正)
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页:
[1]