Thứ Sáu, 5 tháng 9, 2014



Các bước để khởi tạo Servlet với các tham số khởi tạo:

1. Config file web.xml

Các tham số khởi tạo của servlet sẽ được tuỳ chỉnh trong file web.xml với sự hỗ trợ của cặp thẻ <param-name> và <param-value> và được thực hiện như sau


<servlet>
        <servlet-name>NewServlet</servlet-name> 
        <servlet-class>NewServlet</servlet-class>

        <init-param>
             <param-name>Name</param-name>
             <param-value>Phong</param-value>
        </init-param>
< /servlet>

2. Lấy các tham số khởi tạo ra trong Servlet

Các tham số khởi tạo được lấy ra nhờ sự giúp đỡ của phương thức getInitParameter() của lớp ServletConfig

public class NewServlet extends HttpServlet {
    private String Name; 

   @Override
    public void init(ServletConfig config) throws ServletException{
       Name= config.getInitParameter("Name");
    }    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet NewServlet</title>");          
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Tên" + Name+ "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }
}


0 nhận xét:

Đăng nhận xét

    Blogger news

    Blogroll