我想在JSP中使用會話API製作一個基本的登錄系統。我認爲我的代碼很好,當我在tomcat(Eclipse)中運行系統時,填充表單後,servlet加載並且根本不響應(無輸出)。登錄Servlet沒有響應
這是我的login.jsp:
<html>
<body>
<form action="loginservlet" method="post">
<h1>Please Login</h1>
Login: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type=submit value="Login">
</form>
</body>
</html>
這是我loginservlet:
package connectm;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class loginservlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
String username="";
String userpass="";
String strQuery="";
Statement st=null;
ResultSet rs=null;
HttpSession session = request.getSession(true);
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName,
password);
if (request.getParameter("username") != null
&& request.getParameter("username") != ""
&& request.getParameter("password") != null
&& request.getParameter("password") != "") {
username = request.getParameter("username").toString();
userpass = request.getParameter("password").toString();
/*strQuery = "select * from user where username='" + username
+ "' and password='" + userpass + "'";*/
//System.out.println(strQuery);
strQuery = "select username from user where username= ? and password= ?";
st = conn.createStatement();
PreparedStatement ps=conn.prepareStatement(strQuery);
ps.setString(1, username);
ps.setString(2, userpass);
rs = ps.executeQuery(strQuery);
int count = 0;
while (rs.next()) {
session.setAttribute("username", rs.getString(1));
count++;
}
if (count > 0) {
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("login.jsp");
}
} else {
response.sendRedirect("login.jsp");
}
out.println("Connected to the database");
conn.close();
out.println("Disconnected from database");
} catch (Exception e) {
// TODO: handle exception
}
}
}
我,什麼地方出了錯,並在那裏真的一無所知。如果有人能指出錯誤/錯誤,我會很感激。
@BalusC我做了你指出的兩件事。堆棧跟蹤幫助和問題是'ClassNotFoundException:com.mysql.jdbc.Driver'。但是很奇怪,因爲我已經將mysql驅動的jar文件放在項目的構建路徑中,並且在(eclipse)之前工作正常: – Anurag 2011-05-03 17:21:17
JAR需要放在'/ WEB-INF/lib'文件夾中,該文件夾默認是webapp運行時類路徑的一部分。你不需要做其他事情。當您以正確的方式使用'/ WEB-INF/lib'時,Eclipse會自動設置構建路徑。因此,您首先需要撤消構建路徑中的所有手動更改/設置。 – BalusC 2011-05-03 17:25:25
@BaluC如你所說,把mysql連接器放在lib文件夾中,但仍然是相同的錯誤: – Anurag 2011-05-03 17:32:59