ServletContext两个Servlet传值学习笔记
标签:
JavaScript
ServletContext对象
1)在web应用中,由服务器创建的唯一的一个对象是ServletContext
2)ServletContext对象在每一个Servlet中取得都是相同到
3)ServletContext对象在存取方法:
存ServletContext.setAttribute(String,Object):(返回值)void
取ServletContext.getAttribute(String):(返回值)Object
dome1
import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class contDome1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //取得客户端的请求参数 String nsername = request.getParameter("username"); //取得唯一的一个serverletContext对象 ServletContext context = this.getServletContext(); //将信息存入ServletContext对象 context.setAttribute("nsername", nsername); }}
dome2
import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class contDome2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //取得唯一的一个serverletContext对象 ServletContext context = this.getServletContext(); //根据name取得ServletContext对象中的值 String username = (String) context.getAttribute("nsername"); //在浏览器输出 response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("用户名:" + username + "<br/>"); }}
浏览器访问方式:
提交
http://localhost:8080/day04/contDome1?nsername=liwen
结果:
http://localhost:8080/day04/contDome2
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦