2

I have one scenario where I want to do some validation before my welcome.jsp page get loaded. Actually the validation is like I have a user id (using request.getRemoteUser) which I want to check in my Db whether it is already there or not. If yes, then I want to redirect it into another page say login.jsp. if not, it will redirect to my welcome.jsp. I have declare one servlet (CheckUser.java) where I am calling doPost from the doGet and also included the same servlet in my welcome.jsp so that before loading it doGet will invoke.

**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>

}

Welcome.jsp

<body>

    <jsp:include page="/CheckUser" flush="true" />          
sexp1stol
  • 445
  • 4
  • 17
Shibankar
  • 806
  • 3
  • 16
  • 40

2 Answers2

2

This issue get Resolved using beans & scriptlet. in the Jsp page i have import my java class(StoreUsrDetails) and declare a jsp use bean (storeusr).

In jsp page

<%@page import="com.thomsonreuters.alpaca.StoreUsrDetails" %>
<jsp:useBean id="storeusr" class="com.thomsonreuters.alpaca.StoreUsrDetails" scope="request" />

using the bean i call a method inside my java method (validateUser) which returns wheather the user details is present in the database or not. after that i have written a scriplet code at the start of my jsp body. And based on the retun value of validateUser method i redirect them to another page.

Jsp Body

<body>
    <% 

           if(storeusr.validateUser(request.getRemoteUser()))  
          response.sendRedirect("ListProjects.jsp");   


    %> 
Shibankar
  • 806
  • 3
  • 16
  • 40
0

1) You need to extend HTTPServlet to make your class CheckUser a Servlet

ie: Public class CheckUser extends HTTPServlet

2) What is DBConnection ? Does that inherit HTTPServlet ?

3) Then you need to configure CheckUser servlent in your web.xml.

ie:

<servlet>
  <servlet-name>checkUser</servlet-name>
  <servlet-class>package.CheckUser</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>checkUser</servlet-name>
  <url-pattern>/CheckUser</url-pattern>
</servlet-mapping>

Note: Please mention what you have done and what difficulties you are facing

Ravi Trivedi
  • 2,340
  • 2
  • 14
  • 20
  • Thank you for the follow up. Yes, you are right, DBConnection is a class which extends HttpServlet. And also i have configure the xml properly. Actually the things is like i am calling the dopost method inside form doget. and in the doPost i have written one response.sendRedirect(contextPath + "/ListProjects.jsp"); which is not working, and even i am not getting any error msg. – Shibankar May 03 '13 at 08:53
  • @Angel, I want you to do 3 things. **(1)** Please make sure the `doPost()` is getting called. **(2)** Make sure `susr` variable is true and it goes into IF condition. **(3)** Do `system.out.print( contextPath + "/ListProjects.jsp")`. I want to see what value it is. – Ravi Trivedi May 03 '13 at 09:59
  • (1) Yes, doPost is getting called from doGet. (2) And also susr variable returning true Value. (3) system.out.print( contextPath + "/ListProjects.jsp") => "/ALPACA/ListProjects.jsp" where ALPACA is my application name and the "ListProject.jsp" is in my web folder. – Shibankar May 03 '13 at 11:25
  • @Angel, Great. Now tell me several things. **(1)** What is the full URL of your servet ? **(2)** what is your webapp context root ?(is that ALPACA?) **(3)** At what location ListProjects.jsp placed in your root webapp dir structure ? – Ravi Trivedi May 03 '13 at 11:34
  • (1)Server Url=> http://localhost:8080/ALPACA/Welcome.jsp (2)Yes, The Context root is ALPACA (3) Location of the ListProjects.jsp is "D:\ALPACA\web". – Shibankar May 03 '13 at 12:43
  • @Angel, Ok, your redirect should be `contextPath+"/web"+"/ListProjects.jsp"` – Ravi Trivedi May 03 '13 at 12:57
  • Actually still it is not working. My redirect String will be /ALPACA/ListProjects.jsp, bcoz when i typing manually in my browser (localhost:8080/ALPACA/ListProjects.jsp) its working fine. the same statement (response.sendRedirect(Contextpath + "/ListProjects.jsp"))working fine in other cases. But don't knw why it is not working here. What could be the other possible root cause for this issue. – Shibankar May 05 '13 at 20:36
  • what is your web app root ? This one ? >> `D:\ALPACA\web` or this one ? >> `D:\ALPACA` – Ravi Trivedi May 05 '13 at 21:19
  • My web app root is D:\ALPACA. – Shibankar May 06 '13 at 09:55
  • If that is your web root then ListProjects.jsp can't be under D:\ALPACA\web. You are mistaking something here. – Ravi Trivedi May 06 '13 at 10:15