servlet的 属性
An attribute is an object that is used to share information in a web app. Attribute allows Servlets to share information among themselves. Attributes can be SET and GET from one of the following scopes :
属性是用于在Web应用程序中共享信息的对象。 该属性允许Servlet之间共享信息。 可以从以下范围之一来设置和设置属性:
request
请求
session
会议
application
应用
Servlet:如何设置属性 (Servlet: How to SET an Attribute)
public void setAttribute(String name, Object obj)
method is used to SET an Attribute.
public void setAttribute(String name, Object obj)
方法用于设置属性。
Example demonstrating Setting Attribute
演示设置属性的示例
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class First extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ServletContext sc = getServletContext();
sc.setAttribute("user","Abhijit"); //setting attribute on context scope
}
}
Servlet:如何获取属性 (Servlet: How to GET an Attribute)
Object getAttribute(String name)
method is used to GET an attribute.
Object getAttribute(String name)
方法用于获取属性。
Example demonstrating getting a value of set Attribute
演示获取set Attribute值的示例
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Second extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ServletContext sc = getServletContext();
String str = sc.getAttribute("user"); //getting attribute from context scope
out.println("Welcome"+str); // Prints : Welcome Abhijit
}
}
servlet的 属性