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

zengzsys  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(287)

我使用会话将一个值传递到servlet中,然后将该值赋给变量调用“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();

    }
zqdjd7g9

zqdjd7g91#

是您的查询导致了异常。而不是

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

您应该引用email参数。

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

但是您的代码容易受到sql注入的攻击。最好使用 PreparedStatement 为了这个。
顺便说一句,最好是打印堆栈跟踪 catch 你可以很容易地发现到底出了什么问题。

相关问题