我尝试显示已登录用户的数据。 我已经使用会话来识别用户。当我在select查询中使用会话数据来获取该用户的详细信息时,它显示为null。 并且控制台中的消息中存在错误
参数索引超出范围(1>参数个数,为0)。
任何人都可以告诉我我做错了什么,以便我可以解决这个问题并让它发挥作用。 谢谢。
Display.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);
}
}
}
答案 0 :(得分:0)
如果使用预准备语句,则需要为语句参数添加占位符:
PreparedStatement pstmt = con.prepareStatement(
"select * from headwy where uname=?");
pstmt.setString(1, name);