关于怎样在spring mvc中配置使用注解请看我上一篇文章:Spring mvc系列三之 开启注解,
首先用@Controller("userController")标志一个类为控制器,@Controller负责一个bean注册到spring上下文中,bean的ID默认是类名首字母小写,也可以自己定义,下面我显示的把名字定义为userController.
package gd.hz.springmvc.controller;
import org.springframework.stereotype.Controller;
@Controller("userController")
public class UserController {
}
@RequestMapping,用来定义访问的URL,可以定义在类上也可以定义在方法上.把它定义在类方法上,类下面的所有方法访问路径都要它之下.看下面的例子:
package gd.hz.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller("userController")
@RequestMapping("user")
public class UserController {
//当有两个以上的配置时value不可以省略,url路径可以省去"/"
@RequestMapping("addUser")
public ModelAndView addUser()
{
String str = "Springmvc 您好啊!!--->addUser" ;
return new ModelAndView("hello");
}
}
我们在UserController 上使用了@RequestMapping("user"),在方法上使用了@RequestMapping("addUser")这样的话,我们访问这个方法的URL为:http://localhost/项目名称/user/addUser,并返回一个名为hello的视图
下面是注解@RequestMapping的一些常用用法,其中当有配置有二个属性时,value不可省略.另外"result" , str ,是返回数据,我的下一章会介绍.
package gd.hz.springmvc.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller("userController")
@RequestMapping("user")
public class UserController {
//method=RequestMethod.POST
@RequestMapping(value="addUser/tow" , method=RequestMethod.GET)
public ModelAndView addUser2()
{
String str = "Springmvc 您好啊!!--->addUser2" ;
return new ModelAndView("hello" , "result" , str);
}
//URL为user/addUser/thread
@RequestMapping("addUser/thread")
public ModelAndView addUser3()
{
String str = "Springmvc 您好啊!!--->addUser3" ;
return new ModelAndView("hello" , "result" , str);
}
//访问文件二级路径 URL为user/addUser/thread 返回定义目录下的test目录的Hello.jsp文件
@RequestMapping("addUser/six")
public String addUser6(HttpServletRequest request)
{
String str = "Springmvc 您好啊!!--->addUser6" ;
request.setAttribute("result", str);
return "test/hello" ;
}
}
@RequestParam:
required :参数是否必须,boolean类型,可选项,默认为true
value: 传递的参数名称,String类型,可选项,如果有值,对应到设置方法的参数
defaultValue:String类型,参数没有传递时为参数默认指定的值
默认情况下,当从表单或者以GET传来的参数跟Controller中的方法中的参数名不一样时就要使用此注解:
@RequestMapping("/addUser/eight")
public void addUser8(int id, @RequestParam("name") String username) {
//这样做进行URL请求访问这个方法的时候,就会先从request中获取参数id的值赋给参数变量id,
//从request中获取参数name的值赋给参数变量username
}
@PathVariable:可以利用请求路径传值,当指定名称跟变量名不一样时需要指定名字,如下.
@RequestMapping("addUser/{seven}")
public String addUser7(@PathVariable("seven") String name , HttpServletRequest request)
{
request.setAttribute("result", name);
return "test/hello" ;
}
{seven}当url传来什么他就是什么,但是当接收它的变量名不一样时需要用@PathVariable指定.