【问题标题】:Is it advisable to call java dao class method from a jsp page从jsp页面调用java dao类方法是否可取
【发布时间】:2014-07-17 15:39:27
【问题描述】:

我希望用户在单击查看按钮后看到他/她自己的详细信息。所以在 jsp 页面中我创建了这样的链接

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

我之前在验证时已将 empid 设置为会话属性,但现在我将用户重定向到以下链接,我必须只显示他/她的详细信息。

我怀疑我们显然可以调用 dao 类方法来从 jsp 页面获取用户的数据,但这是一种好的编程习惯还是我必须先调用 servlet 然后再调用 jsp。

【问题讨论】:

    标签: java database jsp servlets


    【解决方案1】:

    您不得在您的 JSP 中包含任何 scriptlet/direct Java 代码。请避免使用它。有关此的更多信息:How to avoid Java code in JSP files?(无需再解释一次使用 scriptlet 时遇到的所有问题)。

    您应该使用一个 Servlet 来处理 JSP 的 GET 请求,而 Servlet(控制器)将是您的视图和模型(服务、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>
    

    【讨论】:

    • 如何使用标签创建指向 servlet 的链接?
    • servlet 将处理一个 url。链接只需要指向这样的 url。
    • 你的意思是使用view,点击查看后servlet会被调用。对吗?然后它会处理剩下的事情。
    • @Mayank 请注意,在我的示例中,基本 URL 是 viewuser.jsp。是的,您甚至可以将您的 servlet 映射到 HTML 或 JSP 文件。
    • 谢谢,我只是尝试映射 servlet,它调用了 get 方法,但我想调用 post 方法。 :(
    猜你喜欢
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    相关资源
    最近更新 更多