我使用表單獲取用戶名和密碼並將其與數據庫表值進行比較。如果它們匹配,則應打印用戶名和密碼。它完成..如何從servlet重定向到jsp頁面
但是,我需要將它們重定向到另一個頁面,如果它的有效(比如welcome.jsp
)在web內容文件夾。我該怎麼做。我是servlet
和jsp
幫助我。
SaveServlet.java
package myPack;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SaveServlet
*/
public class SaveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public SaveServlet() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String u = request.getParameter("username");
String p=request.getParameter("password");
System.out.println("USER-->"+u);
ResultSet rs;
String q="select * from userinfo where username='"+u+"' and password='"+p+"'";
Connection con=null;
String c="jdbc:mysql://localhost:3306/test";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(c, "root", "MyNewPass");
System.out.println("connection done");
PreparedStatement ps=con.prepareStatement(q);
System.out.println(q);
rs=ps.executeQuery();
System.out.println("done2");
while (rs.next()) {
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
}
}
catch (Exception e) {
// TODO: handle exception
System.out.println("Failed");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
請不要發佈無效語法示例。 sendRedirect()方法不是一個靜態方法。與setHeader()相同。 – DSoa
@DSoa只需在doPost方法中定義響應變量即可更改HttpServletResponse。沒什麼大不了 – HFR1994