标签:spl let 使用 getattr div gets extends set contex
今天观看视频复习得时候学到了ServletContext相关知识,发现它可以实现servlet之间得数据共享,可以在servlet中传递数据,我还记得原来做老师布置的项目的时候因为这个问题,我把数据都存在session域再在需要的servlet取用,那样特别麻烦,还是源于自己之前学的不踏实。
所有的servlet都共用一个servletcontext的对象,利用它存取数据:
下面我贴一下我使用其的例子:
<html> <body> <h2>Hello World!</h2> <form action="servlet_01"> <input type="submit" value="queding"> </form> </body> </html>
import java.io.IOException; import java.io.Writer; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class servlet_01 */ public class servlet_01 extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public servlet_01() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Writer writer = response.getWriter(); writer.append("hello servlet"); ServletContext context = this.getServletContext(); context.setAttribute("username", "一个程序猿!"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package frist_test; import java.io.IOException; import java.io.Writer; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class servlet_02 */ public class servlet_02 extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public servlet_02() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = this.getServletContext(); // response.setHeader("utf-8", "text/html"); response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); String name = (String)context.getAttribute("username"); response.getWriter().append(name); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
标签:spl let 使用 getattr div gets extends set contex
原文地址:https://www.cnblogs.com/yangxionghao/p/13209545.html