-1
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "SimpleServlet", urlPatterns = { "/SimpleServlet" })
public class SimpleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username = request.getParameter("username").toString();
String password = request.getParameter("password").toString();
String repassword = request.getParameter("repassword").toString();
String ph = request.getParameter("phone").toString();
double phone = Double.parseDouble(ph);
String address = request.getParameter("address").toString();
int status = register(username, password, repassword, phone, address);
if (status > 0) {
RequestDispatcher rd = request.getRequestDispatcher("Register_success.jsp");
rd.include(request, response);
} else {
RequestDispatcher rd = request.getRequestDispatcher("Register_fail.jsp");
rd.include(request, response);
}
out.close();
}
static int status = 0;
@SuppressWarnings("null")
public static int register(String username, String password, String repassword, double phone, String address) {
PreparedStatement ps;
Connection con;
con = GetCon.getCon();
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT username FROM newuser where username='" + username + "'");
while(rs.next())
if (rs.getString("username").equalsIgnoreCase(username)) {
System.out.println(username);
HttpServletResponse response = null;
response.sendRedirect("UserAlreadyExist.jsp");
} else {
ps = con.prepareStatement("Insert into newuser values(?,?,?,?,?)");
ps.setString(1, username);
ps.setString(2, password);
ps.setString(3, repassword);
ps.setDouble(4, phone);
ps.setString(5, address);
status = ps.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return status;
}
}
您好, 我在執行上述代碼時遇到問題。當我們輸入現有的用戶名時,它會拋出一個NullPointerException異常。請有人幫我找到錯誤。該代碼可以使用新用戶名,但與現有用戶無關。謝謝 !無法檢查已有用戶名
閱讀堆棧跟蹤,並使用調試器。 YOu應該能夠找到引發異常的確切線路,然後解決問題 – jhamon
您能否指出您面臨問題的線路? –
建議:'HttpServletResponse的響應= NULL; response.sendRedirect是( 「UserAlreadyExist.jsp」);'響應爲空 – jhamon