基于注解的SpringMVC

本文介绍了SpringMVC中基于注解的配置方法,包括如何使用@Controller和@RequestMapping等注解来处理HTTP请求,并展示了如何配置SpringMVC以支持注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基于注解的SpringMVC

基于注解的话,需要添加几个配置内容到 springmvc-servlet.xml文件中(这个文件使我们配置的spring配置文件,在web.xml中配置的)

基于注解的方式,可能不仅仅依赖与DefaultAnnotationHandlerMapping,

但我们还需要添加一句:<mvc:annotation-driven/>

他提供了SpringMVC注解的所有支持,以及JSR-303的注解支持。

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class QueryController {

	@RequestMapping("/index.htm")
	public void requestIndexHtml(HttpServletRequest request,
			HttpServletResponse respose){
	}
}
这里的类是支持注解的。

注:如果不用@Controller 注解,需要自己定义这个bean,


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
@RequestMapping("/home")
public class QueryController {

	@RequestMapping({"/default.htm","/index.htm"})
	public void requestIndexHtml(HttpServletRequest request,
			HttpServletResponse respose,
			@RequestParam(required = true) int days,
			@RequestParam(required = true) String key){
		//Add you code
	}
}


(1)请求中的参数 days 和 key输入不能为空(required = true 表示参数不能为空) 

如果没有@RequestParam ,默认情况下 required = false;

如果写了@RequestParam,默认情况下 required = true;

(2)另外注意 在类的上边有 @RequestMapping("/home"),表示,只有在请求是资源"/home"下面才会处理;

例如

请求:

一个hello工程

 localhost:8080/hello/default.html

 localhost:8080/hello/test/home/default.html

将不被处理

 localhost:8080/hello/home/default.html

将会被处理




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值