2016-09-29 82 views
-1

我想學習Java EE,這裏是一個很簡單的例子:的getAttribute返回null值(Servlet和在JavaEE的JSP之間)

在我的servlet:

public class Servlet extends HttpServlet { 
private static final long serialVersionUID = 1L; 

public Servlet() { 
    super(); 
    // TODO Auto-generated constructor stub 
} 


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    String message1 = "Alo alo"; 
    int mess2 = 3; 
    request.setAttribute("test", mess2); 
    request.setAttribute("aloMessage", message1); 

} 

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    // TODO Auto-generated method stub 
} 

}

而且在我的JSP文件:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
    <head> 

    <meta charset="ISO-8859-1"> 
    <title>Insert title here</title> 
    </head> 
    <body> 

    <% 
    String getMessage = (String)request.getAttribute("aloMessage"); 
    out.println(getMessage+" abc"); 
    %> 
    <br> 
    <% 
    Integer k = (Integer)request.getAttribute("test"); 
    out.println(k+" abc"); 
    %> 
    </body> 
    </html> 

這裏是一個結果: 空農行 null abc

我不知道getAttribute返回值爲什麼爲null?

+0

請把你的完整例子。謝謝 – esmoreno

+0

我編輯了我的文章並添加了我的完整代碼。謝謝 –

+0

看這個例子:https://www.mkyong.com/servlet/a-simple-servlet-example-write-deploy-run/ – esmoreno

回答

0

可能是您的jsp頁面正在丟失請求會話。

有替代方法可以做到這一點。

你可以在servlet的設置像

request.getSession().setAttribute("test", mess2); 
request.getSession().setAttribute("aloMessage", message1); 

和JSP得到它像

String getMessage = (String)session.getAttribute("aloMessage"); 

通過out.println(+的getMessage 「ABC」);

相關問題