(四) - 传值

一. 使用Request和Session传值

使用这种方式需要先引入相关依赖:

            ...
        </dependency>

        <dependency>
            <!--servlet编译环境-->
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <!--jsp编译环境-->
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

</project>    

servlet代码:

@Controller
@RequestMapping("/data")
public class PassData {

    //使用request和session传值
    @RequestMapping("/test1")
    public String test1(HttpServletRequest request, HttpSession session) {
        System.out.println("test1");
        request.setAttribute("name", "张三");
        session.setAttribute("age", 18);
        return "data1";
    }
}

data1.jsp代码: (使用requestScope / sessionScope 获取值)

<html>
<head>
    <title>data1</title>
</head>
<body>
name: ${requestScope.name}<br>
age: ${sessionScope.age}
</body>
</html>

访问结果:

 

 二. 使用model传值

servlet代码:

@Controller
@RequestMapping("/data")
@SessionAttributes(value = {"country","city"}) //设置model的session
public class PassData {

    //使用model传值
    @RequestMapping("/test2")
    public String test2(Model model) {
        System.out.println("test2");
        model.addAttribute("gender", true);
        model.addAttribute("country", "中国");
        model.addAttribute("city", "杭州");
        return "data2";
    }

data2.jsp代码: (同样使用requestScope / sessionScope 获取值, model会把数据复制到requestScope中)

<html>
<head>
    <title>data2</title>
</head>
<body>
    gender: ${requestScope.gender}<br>
    country: ${sessionScope.country}<br>
    city: ${sessionScope.city}
</body>
</html>

访问结果:

 

 三. 使用status.setComplete()清空所有通过model存入的session

servlet代码:

@Controller
@RequestMapping("/data")
public class PassData {

    @RequestMapping("/test3")
    public String test3(SessionStatus status){
        //清空所有通过model存入的session
        status.setComplete();
        return "data2";
    }

访问结果:

 

 

 

 四. 使用 ModelAndView 传值:

servlet代码:

@Controller
@RequestMapping("/data")
public class PassData {

    @RequestMapping("/test4")
    public ModelAndView test4(){
        ModelAndView modelAndView = new ModelAndView();
        //将会跳转到这个jsp
        modelAndView.setViewName("forward:/data3.jsp");
        modelAndView.addObject("name", "Saber");
        return modelAndView;
    }
}

data3.jsp代码:

<html>
<head>
    <title>data3</title>
</head>
<body>
data3<br>
name: ${requestScope.name}
</body>
</html>

访问结果:

 

posted @ 2020-12-10 18:25  山下明明子  阅读(99)  评论(0编辑  收藏  举报