gpt4 book ai didi

java - 无法在选择查询中使用 session 数据

转载 作者:行者123 更新时间:2023-11-29 17:51:53 24 4
gpt4 key购买 nike

我试图显示已登录用户的数据。我已经使用 session 来识别用户。当我在选择查询中使用 session 数据来获取该用户的详细信息时,它显示为空。控制台中的消息有错误

参数索引超出范围(1 > 参数个数,为 0)。

谁能告诉我哪里做错了,以便我可以解决这个问题并使其正常工作。谢谢。

显示.java

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@WebServlet("/display")
public class display extends HttpServlet {
private static final long serialVersionUID = 1L;
private String uname;


public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
processRequset (request,response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

processRequset (request,response);
}

public void processRequset(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
if(session!=null){
String name=(String)session.getAttribute("uname");
out.print("Hello, "+name+" ");
try {
response.setContentType("text/html;charset=UTF-8");

Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/register","root","toor");


PreparedStatement pstmt=con.prepareStatement(
"select * from headwy where uname='"+ name +"'" );
out.print("Hello, "+uname+" ");
pstmt.setString(1,uname);
ResultSet rs = pstmt.executeQuery();
out.println("<html><body><table BORDER=\"10\" WIDTH=\"50%\" bordercolor = \"green\" CELLPADDING=\"8\" CELLSPACING=\"3\" ALIGN=\"CENTER\" ><tr><td>phone</td><td>unamr</td><td>pass</td></tr>");
while(rs.next())
{
out.println("<tr> <td>"+rs.getString(1)+"</td> <td>"+rs.getString(2)+"</td><td>"+rs.getString(3)+"</td></tr>");


}

out.println("</table></body></html>");
}
catch (Exception e2) {System.out.println(e2);
}

}
else{
out.print("Please login first");
request.getRequestDispatcher("login.html").include(request, response);
}
}
}

最佳答案

如果使用准备好的语句,则需要为语句参数添加占位符:

PreparedStatement pstmt = con.prepareStatement(  
"select * from headwy where uname=?");
pstmt.setString(1, name);

关于java - 无法在选择查询中使用 session 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49252832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com