活动地址:CSDN21天学习挑战赛
上篇链接:我的第一个Spring MVC应用的过程与解释_无忧#的博客-CSDN博客
通过上篇例子来修改
1.搭载项目环境
所需jar包:
使用注解对jre环境有要求,推荐使用JavaSE-15,否则会报版本错误。
Eclipse更换jre方法:
右击项目—— 选择Build Path——选择Configure Build Path——选中Libraries——选中JRE System Library——点击Edit....——如下图——Finish。
2.修改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"
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="com.ssm.controller" />
<!-- 定义视图解析器 -->
<bean id="viewResoler"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 设置前缀 -->
<property name="prefix" value="/" />
<!-- 设置后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
3.修改Controller类
package com.ssm.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/controll")
public class ControllerTest {
@RequestMapping(value = "/annotationController")
public String handleRequest(HttpServletRequest arg0, HttpServletResponse arg1,Model model) throws Exception {
model.addAttribute("msg", "我的第一个基于注解的Spring MVC应用");
return "welcome";
//访问:http://localhost:8848/chapter11_2/controll/annotationController
}
}
4.运行结果
访问:http://localhost:8848/chapter11_2/controll/annotationController
由于标注在类上的@RequestMapping注解的value值为"/controll",因此,类中所有请求方法的路径都需要加上"/controll"。由于类中的handleRequest()方法的返回类型为String,而String类型的返回值又无法携带数据,因此需要通过参数Model对象的addAttribute()方法来添加数据信息。因为配置文件的视图解析器中,定义了试图文件的前缀和后缀名,所以handleRequest()方法只需要返回视图名welcome即可。
通过注解来编写代码比原始方法更简单,代码更简洁。但是所要求的环境更严格,如果自己写的代码运行有问题,可以参考源码:
链接:https://pan.baidu.com/s/1UfsH6IBzdHvsTiYPqv7EyQ?pwd=5yx8
提取码:5yx8