jsp useBean is NULL by getAttribute by servlet

后端 未结 3 1044
我寻月下人不归
我寻月下人不归 2020-12-03 16:14

user is null in servlet. Pls let me if doing mistake.

i m trying to get all html element in bean rateCode.jsp

<%@page import=\"com.hermes.data.Rat         


        
3条回答
  •  春和景丽
    2020-12-03 16:45

    You seem to misunderstand the working and purpose of jsp:useBean.

    First of all, you've declared the bean to be in the session scope and you're filling it with all parameters of the current request.

    
        
    
    

    This bean is thus stored as session attribute with the name user. You need to retrieve it in the servlet as session attribute, not as request attribute.

    RateCode_ user = (RateCode_) request.getSession().getAttribute("user");
    

    (user is a terrible and confusing attribute name by the way, I'd rename it rateCode or something, without this odd _ in the end)

    However, it'll contain nothing. The getCode() and getDescription() will return null. The has namely not filled it with all request parameters yet at that point you're attempting to access it in the servlet. It will only do that when you forward the request containing the parameters back to the JSP page. However this takes place beyond the business logic in the servlet.

    You need to gather them as request parameters yourself. First get rid of whole thing in the JSP and do as follows in the servlet's doPost() method:

    RateCode_ user = new RateCode_();
    user.setCode(request.getParameter("code"));
    user.setDescription(request.getParameter("description"));
    // ...
    request.setAttribute("user", user); // Do NOT store in session unless really necessary.
    

    and then you can access it in the JSP as below:

    
    
    

    (this is only sensitive to XSS attacks, you'd like to install JSTL and use fn:escapeXml)

    No, you do not need in JSP. Keep it out, it has practically no value when you're using the MVC (level 2) approach with real servlets. The is only useful for MV design (MVC level 1). To save boilerplate code of collecting request parameters, consider using a MVC framework or Apache Commons BeanUtils. See also below links for hints.

    See also:

    • Easy way of populating Javabeans based on request parameters
    • Using beans in servlets
    • Our Servlets wiki page

提交回复
热议问题