SpringMVc 随笔3 ,注解入参pathVariable,requestparam,和modelAttributes和返回值,modelAndView,map

1.如果要从浏览器向控制器传入参数,有两个注解可以使用,一个是@PathVariable,一个是@RequestParam。

其中,@PathVariable用于类似REST风格的入参,如/getEmp/12,这样子的。

@RequestParam,用于/getEmp?user=xxx&password=xxx,这样的入参。

示例如下,在注解中,如果只有一个参数,即value=,,默认的value可以省略不写

package cn.taotao.controller;

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.RequestParam;

@Controller
public class EmployeeController {
    @RequestMapping("/getEmp")
    public String getEmp() {
        return "success";
    }

    @RequestMapping("/getEmp01/{id}")
     public String getEmp01(@PathVariable("id") Integer id) {
         System.out.println("id="+id);
        return "success";
     }

    @RequestMapping("/getEmp02") 
    public String getEmp02(@RequestParam("username") String username,@RequestParam("password") String password) {
        System.out.println("username= "+username+",pasword="+password);
        return "success";
    }
}

jsp页面如下

<html>
<body>
<h2>Hello World!</h2>
<a href="getEmp01/1332">get pathVariable</a>
<br><br><br>
<a href="getEmp02?username=xxxxx&password=765678">get RequestParam</a>
<br>
<br>
<a href="getEmp">getEmp</a><br>
</body>
</html>

返回值类型,有两个,最常用的是ModelAndView,另一个是Map,,系统会自动把map类型,或者list类型,封装成modelAndView类型。

@RequestMapping("/testMap")
    public String testMap(Map<String, Object> map){
        System.out.println(map.getClass().getName()); 
        map.put("names", Arrays.asList("Tom", "Jerry", "Mike"));
        return "success";
    }
    
   
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView(){
        String viewName = "success";
        ModelAndView modelAndView = new ModelAndView(viewName);
        
     
        modelAndView.addObject("time", new Date());
        
        return modelAndView;
    }
    

猜你喜欢

转载自www.cnblogs.com/sdgtxuyong/p/11865310.html