java – 在Spring MVC中没有参数的@RequestMapping

前端之家收集整理的这篇文章主要介绍了java – 在Spring MVC中没有参数的@RequestMapping前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我在学习Spring MVC时试图理解我的项目代码.

在Spring中,@ RequestMapping注释需要参数.例如,

  1. @RequestMapping(value="/something",method=RequestMethod.POST)
  2. @RequestMapping(value="/index.html",method=RequestMethod.GET)
  3. @RequestMapping("/index")
  4. @RequestMapping(params="command=GETINFO")

我的项目使用注释,它不使用任何XML进行映射.我有一个以下的控制器结构.

  1. @Controller
  2. public class RuleStepController {
  3. private static final String ATTRIBUTE_BRANCH = "branch";
  4. private static final String ATTRIBUTE_EDIT_FORM = "editForm";
  5. .................
  6. @Autowired
  7. private RuleStepService ruleStepService;
  8. @Autowired
  9. private PopulationDao populationDao;
  10. @RequestMapping
  11. public void ruleStepEntForm(Long populationId,ModelMap model) {
  12. .....
  13. editForm.setStepEnt(stepDto);
  14. }
  15. @RequestMapping
  16. public void ruleStepOrgCount(RuleStepOrgSearchForm searchForm,ModelMap model){
  17. .......
  18. model.addAttribute("searchForm",searchForm);
  19. }
  20. @RequestMapping
  21. public String ruleStepMgrForm() {
  22. logger.debug(String.format("ruleStepMgrForm"));
  23. return "forward:/employee/employeeSearchForm.view?relationshipId=0&roleId=0&formId=stepMgr";
  24. }

我想了解@RequestMapping在没有任何参数的情况下有什么意义?

@AutoWired的用途是什么?

最佳答案
>使用注释@RequestMapping,您可以通过多种方式绑定请求参数:

URI模板模式,使用注释@PathVariable

  1. @RequestMapping(value="/owners/{ownerId}",method=RequestMethod.GET)
  2. public String findOwner(@PathVariable String ownerId,Model model) {
  3. Owner owner = ownerService.findOwner(ownerId);
  4. model.addAttribute("owner",owner);
  5. return "displayOwner";
  6. }

请求参数和标头值

  1. @Controller
  2. @RequestMapping("/owners/{ownerId}")
  3. public class RelativePathUriTemplateController {
  4. @RequestMapping(value = "/pets/{petId}",method = RequestMethod.GET,params = "myParam=myValue")
  5. public void findPet(@PathVariable String ownerId,@PathVariable String petId,Model model) {
  6. // implementation omitted
  7. }
  8. }

使用@RequestParam

  1. @Controller
  2. @RequestMapping("/pets")
  3. @SessionAttributes("pet")
  4. public class EditPetForm {
  5. @RequestMapping(method = RequestMethod.GET)
  6. public String setupForm(@RequestParam("petId") int petId,ModelMap model) {
  7. Pet pet = this.clinic.loadPet(petId);
  8. model.addAttribute("pet",pet);
  9. return "petForm";
  10. }
  11. }

使用@RequestBody注释映射请求正文

  1. @RequestMapping(value = "/something",method = RequestMethod.PUT)
  2. public void handle(@RequestBody String body,Writer writer) throws IOException {
  3. writer.write(body);
  4. }

>自动装配

  1. @Autowired
  2. private RuleStepService ruleStepService;

Spring Container之前创建了bean ruleStepService.如果你需要在你的类中使用这个bean,你只需要如上所述声明,容器会将bean注入你的类.你不需要声明像;

  1. RuleStepService ruleStepService =new RuleStepService().

Container将找到bean名称ruleStepService或bean具有类型RuleStepService(基于配置中的策略)

猜你在找的Spring相关文章