jsp与servlet如何互相传值

如题所述

1、利用ServletContext这个web全局上下文来共享数据
servlet中getServletContext()可以获得一个ServletContext对象,利用这个对象的getAttribute()/setAttribute()方法可以在整个WEB应该里共享数据,可以实现servlet和jsp之间的数据互传
比如:

在servlet中
1

getServletContext.setAttribute("title", "hello world");

在servlet上下文中以“hello”为键,保存了“hello world”这一个字符串,如果要在jsp中调用,则用如下jsp脚本
1

<%=application.getAttribute("hello")%>

2、利用session在同一个会话共享数据
利用HttpSession共享同一个会话的数据。这也要用到session的getAttribute()/setAttribute()方法,和ServletContext()的使用差不多的。
3、利用request共享一次请求的数据
一次请求当中,可以利用request的getAttribute()/setAttribute()方法在servlet和jsp页面间共享数据。
温馨提示:答案为网友推荐,仅供参考