springMVC系列之注解版――03

2014-11-24 02:40:46 · 作者: · 浏览: 1

springMVC系列之注解版——03


摘要:实现使用注解版的springMVC来访问页面、测试GET、与POST类型方法的使用方法。

一:实现顺序


1、 为保留前面项目的内容、这里新建一个springMVC的配置文件:springAnnotation-servlet.xml、当然,要改变web.xml中的配置的加载文件的路径。

2、 在springAnnotation-servlet.xml中使用配置的方式开启annotation的使用、

3、 配置要被扫描的包、即哪些包下面的类是使用annotation来实现的。

4、 在指定的被annotation扫描的包下面建立一个具体的Controller、注意annotation的使用、暂时有类注解、方法的注解、具体意义代码中有说明。

二:具体步骤以及细节


1、实现springAnnotation-servlet.xml的配置、一个是开启、一个是扫描、代码中有注解

2、具体的UserController:具体的代码中也有说明。

package com.chy.web.controller.annotation;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

//类注解、表示这个类使用注解的形式、会被springMVC扫描到
@Controller
public class UserController {
	
	//方法的注解、有两个参数:value表示要使用这个方法的请求、method表示处理的请求的类型、不匹配的话会出错
	@RequestMapping(value=/user/toUser,method=RequestMethod.GET)
	public ModelAndView toUser(){
		return new ModelAndView(/annotation);
	}

	@RequestMapping(value=/user/addUser,method=RequestMethod.POST)
	public ModelAndView addUser(){
		String result=this is addUser-------;
		return new ModelAndView(/annotation,result,result);
	}
	
	@RequestMapping(value=/user/delUser,method=RequestMethod.GET)
	public ModelAndView delUser(){
		String result=this is delUser-------;
		return new ModelAndView(/annotation,result,result);
	}	
}

3、对GET、POST方法的测试

a) 在地址栏中输入http://localhost:8080/springMVC4/user/toUser进入到annotation.jsp页面(此时url请求是get方式、同时UserController中对应”/user/toUser”方法也是按照get方式请求的、此时能正常访问)、因为没有任何参数传递到annotation.jsp、所以annotation.jsp中没有页面div中的reuslt的显示结果。

b) 点击annotation.jsp的form提交按钮、以post方式提交、通过action=”/springMVC/user/addUser”请求UserController的addUser方法、但是两者不一致、则访问失败、当将UserController的addUser方法的请求方式改为post时、则访问正常、

c) 自己尝试啊、不再贴图了、本来就水、图多了更水。。。

补充:

1、UserController中方法定义的请求路径是 /user/addUser、而form的action中请求是/springMVC/user/addUser。

2、项目的整个结构图:

\

更多内容: springMVC系列之目录——00