JavaWeb的存取数据实例
代码
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <context-param> <param-name>name</param-name> <param-value>root</param-value> </context-param> <servlet> <servlet-name>Servlet1</servlet-name> <servlet-class>Servlet.Servlet1</servlet-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </servlet> <servlet> <servlet-name>Servlet2</servlet-name> <servlet-class>Servlet.Servlet2</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet1</servlet-name> <url-pattern>/S1</url-pattern>//访问路径,可以有多个例如: // <url-pattern>/S11</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Servlet2</servlet-name> <url-pattern>/S2</url-pattern>//同上 </servlet-mapping> </web-app>
Servlet1
package Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; //上方"import"为引入类 public class Servlet1 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response);//调用get访问方法。 } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8");//设置编码格式,否则输出为乱码或"???" PrintWriter out=response.getWriter(); //获取域对象 ServletContext context=this.getServletContext(); //取数据 String value=(String)context.getAttribute("user");//获取"user"的值,并赋值给"value"。 out.print(value);//页面输出"value",与控制台输出不同:"System.out.println(value);" } }
Servlet2
package Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class Servlet2 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8");//编码格式 PrintWriter out=response.getWriter(); ServletContext context=this.getServletContext();//定义类(调用) context.setAttribute("user","管理者");//调用刚定义的类,去存数据(set:存,get:取,setAttribute:存,getAttribute:取) /* 名为"user",值为"管理者"。 Ps:获取编号,知道他是什么内容。 例如获取user,知道它的内容是管理者。 再比如:知道一首诗的名字是***,这首诗的内容为***** */ out.write("现在是“/S2”,请在地址栏改为“/S1!”");//页面输出内容 } }