当前位置: 代码迷 >> Java Web开发 >> 关于小弟我的Sevlet不能跳转
  详细解决方案

关于小弟我的Sevlet不能跳转

热度:173   发布时间:2016-04-16 21:44:34.0
关于我的Sevlet不能跳转
我在做一个Servlet登陆验证,刚刚自己找问题,发现很可能是数据库代码部分的问题,下面的代码中,验证过那个sql语句被执行,但是查询没有成功,也就是,那个ResultSet的对象,没有内容在里面,只是preparedstatement'执行了sql语句,那么是sql语句出现问题了?
package com.vv.controler;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.vv.databaseConnection.*;


public class LoginCLServlet extends HttpServlet {

/**
 * The doGet method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to get.
 * 
 * @param request the request send by the client to the server
 * @param response the response send by the server to the client
 * @throws ServletException if an error occurred
 * @throws IOException if an error occurred
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

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

String us = request.getParameter("username");
String password = request.getParameter("password");

DatabaseConnection dbc = null ;
Connection conn = null ;
PreparedStatement ps = null ;
String sql = "select * from user where username=?";
ResultSet rs = null ;

try{
dbc = new DatabaseConnection() ;
conn = dbc.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, us);

rs = ps.executeQuery();


String pw = null ;
int count = 0;

while(rs.next()){

pw = rs.getString(password);
if(password.equals(pw)){
response.sendRedirect("/UserManager/MainFrame");
count = count + 1 ;
}
}
if(count == 0){
response.sendRedirect("/UserManager/LoginServlet");
}



dbc.close();
}

catch(Exception e){
e.printStackTrace();
}


}

/**
 * The doPost method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request the request send by the client to the server
 * @param response the response send by the server to the client
 * @throws ServletException if an error occurred
 * @throws IOException if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);

}

}

------解决思路----------------------
断点下,看看 String us = request.getParameter("username"); 拿到的us 是什么值?
确保us 非空的话,可以ps.setString(1, us.trim()); 防止空格字符对查询的影响

如果还查不到结果,那就将select * from user where username='us' 直接放到数据库取查询,看能否查询到结果
------解决思路----------------------
查询不到,估计就是us值得问题了,打印下看看是什么值,另外你要是只能查一条记录的话,把那个while换成if会更好