簡體   English   中英

從jsp頁面調用java dao類方法是否明智?

[英]Is it advisable to call java dao class method from a jsp page

我希望用戶單擊查看按鈕后可以看到他/她自己的詳細信息。因此,在一個jsp頁面中,我創建了一個這樣的鏈接

<a href="viewuser.jsp">View</a>

我在身份驗證時已將empid設置為session屬性,但現在將用戶重定向到以下鏈接,其中我僅需顯示其詳細信息。

我的疑問是,我們顯然可以調用dao類方法來從jsp頁面獲取用戶數據,但這是一種好的編程習慣,還是我必須先調用servlet,然后才調用jsp。

您的JSP中不得包含任何scriptlet /直接Java代碼。 避免使用它 有關更多信息: 如何避免JSP文件中的Java代碼? (無需再解釋一次使用scriptlet時遇到的所有問題)。

您應該使用一個Servlet,它將處理JSP的GET請求,而Servlet(控制器)將成為您的View與模型(Service,Dao等)之間的鏈接。 這是一個非常基本的示例:

@WebServlet("/viewuser.jsp")
public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        int empid = (Integer)request.getSession().getAttribute("empid");
        //assuming EmployeeService is a service class that has a getEmployee method
        //that will handle the work to a dao to retrieve data from database 
        //or another data source and will return an Employee object
        Employee employee = new EmployeeService().getEmployee(empid);
        request.setAttribute("employee", employee);
        request.getRequestDispatcher("/viewuser.jsp").forward(request, response);
    }
}

然后在您的viewuser.jsp文件中(縮短的代碼):

<p>
    Name: <c:out value="${employee.name}" />
</p>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM