我有一种情况,我想在加载welcome.jsp 页面之前进行一些验证。实际上,验证就像我有一个用户 ID(使用 request.getRemoteUser),我想在我的 Db 中检查它是否已经存在。如果是,那么我想将它重定向到另一个页面,比如 login.jsp。如果没有,它将重定向到我的welcome.jsp。我已经声明了一个 servlet (CheckUser.java),我在其中从 doGet 调用 doPost,并且还在我的welcome.jsp 中包含了相同的 servlet,以便在加载它之前 doGet 将调用。
**CheckUser.java**
package DBResource;
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.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CheckUser extends DBConnection {
String page="ListProjects.jsp";
public Connection conn= null;
// This Happens Once and is Reused
@Override
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}
public boolean SearchUser(String Usrid) throws SQLException{
try{
// Establishing connection using data source
conn=ds.getConnection();
PreparedStatement stmt=conn.prepareStatement("select * from OSS_USER where USER_EMAIL='"+Usrid+"'");
ResultSet rs = stmt.executeQuery();
boolean hasResult = rs.next();
return hasResult;
}
catch (Exception e){
e.printStackTrace();
return false;
}
finally {
if (conn != null) conn.close();
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("on CheckUser doGet...........");
doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("on CheckUser doPost..........");
//String Usrid= request.getRemoteUser();
String Usrid= "abc@tr.com";
contextPath = request.getContextPath();
page = "/ListProjects.jsp";
try {
boolean susr = SearchUser(Usrid);
if (susr==true)
{
response.sendRedirect(contextPath + "/ListProjects.jsp");
}
} catch (SQLException ex) {
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (conn != null) try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
欢迎.jsp
<body>
<jsp:include page="/CheckUser" flush="true" />