Setattribute là gì

Attribute trong Servlet

4 năm ago
IT Phú Trần
2 minutes

Một Attributelà một đối tượng được sử dụng để chia sẻ thông tin trong một ứng dụng web. Thuộc tính cho phép Servlets chia sẻ thông tin với nhau. Attributecó thể được thiết lập và GET từ một trong những phạm vi sau đây:

  1. request
  2. session
  3. application

Làm thế nào để gán một Attribute?

public void setAttribute[String name, Object obj] Phương pháp được sử dụng để thiết lập một thuộc tính.

Ví dụ về 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 } }

Cách GET giá trị mộtAttribute

Object getAttribute[String name] Phương thức được sử dụng để GET một thuộc tính.

Ví dụ :

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 } }

#Attribute trong java #getattribute trong java #setAttribute trong servlet #ví dụ về Attribute trong java

Video liên quan

Chủ Đề