如何在servlet中使用带有会话值的where子句

时间:2018-04-10 06:43:22

标签: mysql jsp servlets database-connection where-clause

我已经使用session将值传递给servlet。然后将值赋给变量call'ms'。现在我想使用带有'where'子句的变量选择数据。但它不起作用。

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter(); 

         HttpSession ses=request.getSession(false);
         String ms = ses.getAttribute("ma").toString();

    try {

        dbconn = new DatabaseConnection();
        conn = dbconn.setConnection();
        stmt = conn.createStatement();
        query = "select * from  person where Email ="+ms;
        res = dbconn.getResult(query, conn);
        while(res.next()){

            lst.add(res.getString("Username"));
            lst.add(res.getString("Title"));
            lst.add(res.getString("Fname"));
            lst.add(res.getString("Lname"));

        }
        res.close();
     }catch(Exception e){

        RequestDispatcher rd =request.getRequestDispatcher("myAccount.jsp");
        rd.forward(request, response);

    }finally{

        request.setAttribute("EmpData", lst);
        RequestDispatcher rd =request.getRequestDispatcher("myAccount.jsp");
        rd.forward(request, response);

        lst.clear();
        out.close();

    }

1 个答案:

答案 0 :(得分:0)

导致异常的查询。 而不是

 query = "select * from  person where Email ="+ms;

您应引用电子邮件参数。

query = "select * from  person where Email ='"+ms+"'";

但是您的代码很容易受到SQL注入攻击。最好使用PreparedStatement

顺便说一下,最好在catch子句上打印堆栈跟踪,你可以很容易地发现出现了什么问题。