1. 程式人生 > >Spring MVC controller和jsp頁面傳值

Spring MVC controller和jsp頁面傳值

頁面封裝好Map結構後,頁面使用${} 就可以獲取到數值

Controller

@Controller
@RequestMapping("/index.do")
public class IndexController {
    @RequestMapping(params = "add")
    public ModelAndView add(@RequestParam("name") String name,
            @RequestParam("age") String age) {
        // Map<String, Object> params = new HashMap<String, Object>();
        // params.put("sex", "man");
        ModelMap params = new ModelMap();
        params.addAttribute("name", name);
        params.addAttribute("age", age);
        ModelAndView modelAndView = new ModelAndView("success", params);
        return modelAndView;
    }
}

頁面jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here1</title>
</head>
<body>${name}
</body>
</html>

結果:

注意:如果返回的是list  頁面可以用C標籤foreach迴圈獲取