springMVC入门-02

  本节会在上节基础上讨论springMVC如何传值的问题。

  在添加dispatcherServlet之后,拦截器会将url中的参数拦截下来,使之可以在controller中使用。以下代码就是在前台输入username和password入参之后,在controller之中获取的值。

package zttc.itat.controller;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class Hellocontroller{

     //controller获取入参:拦截器会将入参username和password拦截作为入参传入hello方法之中
    //controller返回view的参数传递:
    //方式一:在入参中使用Map<String, Object> context
     //方式二:在入参中使用Model model
     //框架会自动将context或者model传递到前台页面,使用${xxxx}即可获取对应参数    @RequestMapping("/hello")
    public String hello(String username, String password, Map<String, Object> context)
    {
        //model.addAttribute("username", username);
        //model.addAttribute("password", password);
        context.put("username", username);
        context.put("password", password);
        System.out.println(username);
        System.out.println(password);
        return "hello";
    }

}
View Code

    使用以上两种方式即可将页面url中的参数传入controller,并且将参数返回给前台页面。在前台页面代码如下所示;

<%@ page language="java" contentType="text/html; charset=BIG5"
    pageEncoding="BIG5"%>
<!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=BIG5">
<title>Insert title here</title>
</head>
<body>
<h1>hello!${username},${password}</h1>
</body>
</html>
View Code

    对应页面操作和显示如下所示:

posted @ 2015-03-01 12:26  birdman-peter  阅读(95)  评论(0编辑  收藏  举报