基于注解的Spring MVC实例开发过程


活动地址: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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无忧#

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值