SpringMVC:注解开发

来自Wikioe
跳到导航 跳到搜索


@RequestMapping 使用

通过RequestMapping注解可以定义不同的处理器映射规则。

URL路径映射

@RequestMapping(value="/item")@RequestMapping("/item") value的值是数组,可以将多个url映射到同一个方法,如:

@RestController
@RequestMapping("/home ")
public class IndexController {

    @RequestMapping(value = {
        " ",
        "/page ",
        "page* ",
        "view/*,**/msg "
    })
    String indexMultipleMapping() {
        return "Hello from index multiple mapping. ";
    }
}

如下的这些 URL 都会由 indexMultipleMapping() 来处理:

  • localhost:8080/home
  • localhost:8080/home/
  • localhost:8080/home/page
  • localhost:8080/home/pageabc
  • localhost:8080/home/view/
  • localhost:8080/home/view/view

窄化请求映射

在class上添加@RequestMapping(url)指定通用请求前缀, 限制此类下的所有方法请求url必须以请求前缀开头,通过此方法对url进行分类管理。

@Controller
@RequestMapping("/items")
public class ItemsController {

	@Autowired
	private ItemsService itemsService;

	// 商品查询
	@RequestMapping("/queryItems")
	public ModelAndView queryItems(HttpServletRequest request) throws Exception {

		List<ItemsCustom> itemsList = itemsService.findItemsList(null);
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("itemsList", itemsList);
		modelAndView.setViewName("items/itemsList");

		return modelAndView;
	}
...
}

商品列表请求路径为:“/items/queryItems.action”。

限定请求方法

出于安全性考虑,对http的链接进行方法限制。

//商品信息修改页面显示
@RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET})
public ModelAndView editItems()throws Exception {
	
	ItemsCustom itemsCustom = itemsService.findItemsById(1);
	
	ModelAndView modelAndView = new ModelAndView();
	modelAndView.addObject("itemsCustom", itemsCustom);
	modelAndView.setViewName("items/editItems");
	
	return modelAndView;
}

如果限制请求为post方法(method={RequestMethod.GET}),进行get请求,报错: RequestMapping请求限定.png

@RequestParam 的RequestMapping

//@RequestParam里边指定request传入参数名称和形参进行绑定。 //通过required属性指定参数是否必须要传入 //通过defaultValue可以设置默认值,如果id参数没有传入,将默认值和形参绑定。

//商品信息修改页面显示
@RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET})
public String editItems(Model model,@RequestParam(value="id",required=true) Integer items_id)throws Exception {
	
	ItemsCustom itemsCustom = itemsService.findItemsById(items_id);
	
	//通过形参中的model将model数据传到页面
	//相当于modelAndView.addObject方法
	model.addAttribute("itemsCustom", itemsCustom);
	
	return "items/editItems";
}

Handler方法返回值

ModelAndView

void

字符串

逻辑视图名

Redirect重定向

forward转发

参数绑定

默认支持的参数类型

简单类型

pojo

集合

自定义参数绑定

示例代码

需求

dao

service

controller

页面