Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Extending a Servlet and sharing HttpServletRequest

  1. #1
    Junior Member
    Join Date
    Oct 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Extending a Servlet and sharing HttpServletRequest

    Hi there.

    I been messing around with having a template master servlet which does all the verifications required and then running a basic code to extend from this template servlet.

    Within the template servlet I have the usual doPost and doGet actions, The configured servlet in my web.xml is the new shorter extended code and does work.

    So far I can pass values back to the template which loads up on the extended class, the problem I am currently having is trying to get the HttpServletRequest to be sent back to my extended class.



    I have tried making req a public variable in Template.java and calling this back via the extended class - as soon as I attempt any calls of the request parameter I do not get the outputs I send to the master template.java shown on the screen -

    public HttpServletRequest req;
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
    req=request;
    doGet(req, response);
    }
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    req=request;
    ....
    ...
    I have tried to create a setReq and getReq in the master Template.java - again it behaves the same way returning none of the new values I send to Template.java.


    public class Contact extends Template {
    String output="";
    //Contact tm=new Contact();
    //Template tm=new Template();
    // HttpServletRequest re=(HttpServletRequest)tm.getReq();
    public String RunThis() {
    try {
    //String mact=(String)re.getParameter("a");
    if (mact==null) { mact=""; }
    String act=(String)Template.getAct();
    if (act==null) { act=""; }
    String title="NOT SET";
    String op="NOT SET";
    String page="";
    if (act.equals("2")) {
    title=act+"__page2";
    op="page2";
    page="login";

    }else{
    title="Contact Web support team";
    op="Contact us here";
    page=" page: contact <>"+act+" @ "+mact+" <br>";
    }
    setOP(op);
    setPage(page);
    setTitle(act+"--"+title);
    } catch (Exception e) { output +="Error "+e; }
    return output;
    }
    String done=(String)RunThis();
    }
    Does anyone know how I can achieve this ?


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Extending a Servlet and sharing HttpServletRequest

    So far I can pass values back to the template which loads up on the extended class, the problem I am currently having is trying to get the HttpServletRequest to be sent back to my extended class
    I am not quite sure what you are asking...if you pass an object to a method as a parameter, and change the variables within said object, when that method exits the object has been changed...if the method changes the object itself (eg creates a new reference), you can define that method to return the new object.

  3. #3
    Junior Member
    Join Date
    Oct 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Extending a Servlet and sharing HttpServletRequest

    Been doing some more testing - it appears that HttpServletRequest req is returning a null value.

    What I am trying to achieve is to let the 2nd extended class query the output of http request values from the template which is the master class.

    I will send the code base and hopefully it will make more sense.


    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.net.URL;
     
    public class Template extends HttpServlet  {
     public Template () {}
            public String op="";
            public String title="";
            public String page="";
            //These 3 work and are values passed from the extended class
            public void setTitle(String tit) { title = tit; }
            public void setOP(String oo) { op = oo; }
            public void setPage(String pg) { page = pg; }
     
            //Could not get it to return request.getParameter("a")
            public static String act="";
            public static void setAct(String aa) { act=aa; }
            public String getAct() { return act; }
     
            Nor any attempts to return entire request to extended class
            //public HttpServletRequest req=null;
            //public void setReq(HttpServletRequest r) { req=r;}
            //public static HttpServletRequest getReq() { return req; }
     
     
            public void doPost(HttpServletRequest req,HttpServletResponse response) throws ServletException,IOException {
                    doit (req,response);
     
            }
            public void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
                    doit (req,response);
     
            }
     
            public HttpServletRequest doit (HttpServletRequest req,HttpServletResponse response) throws ServletException,IOException{
            response.setContentType("text/html");
            String output="";
            PrintWriter out = response.getWriter();
            HttpSession session = req.getSession(true);
            String loggedin=(String)session.getValue("LOGGEDIN");
            if (loggedin==null) { loggedin="";}
            String luser=(String)session.getValue("LUSER");
            if (luser==null) { luser=""; }
            String userlevel=(String)session.getValue("ULEV");
            if (userlevel==null) { userlevel="0"; }
            int ulev=Integer.parseInt(userlevel);
            String ipadd=(String)session.getValue("IPADD");
            if (ipadd==null) { ipadd="0.0.0.0";}
            act=(String)req.getParameter("a");
            setAct(act);
            if (act==null) { act="menu"; }
            GetURL gu = new GetURL();
            gu.dothis(req);
            String fullurl=gu.Result();
            String spath=gu.ret_path();
            String scr=gu.ret_url();
            ServletConfig sg=getServletConfig();
            String sname=(String)sg.getServletName();
            String level=(String)req.getParameter("level");
            if (level==null) { level=""; }
            String query=(String)req.getParameter("query");
            String qtype=(String)req.getParameter("qtype");
            if (query==null) { query="";}
            if (qtype==null) { qtype="";}
            //if (loggedin.equals("")) {
              //      response.sendRedirect(spath+"/Login?source="+fullurl+"");
            //}
     
            //This was working so when I sent a page value from extended class it would load up
            // if (!page.equals("")) {
            //        LoadPage lp=new LoadPage();
            //        lp.dothis(req,page);
            //        op=lp.Result();
            //}
     
            //This loads in the page content (header/footer)
            //LoadContent lca=new LoadContent();
            //lca.dothis(req,title,sname,op);
            //output +=lca.Result();
     
            //My attempts to try to set the request
            //setReq(req);
            //getReq(req);
     
            out.println(output);
     
            return req;
      }
    }

    So this code above is my master template file

    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    //import com.ual.Template.*;
     
     
    public class Contact extends Template {
            String output="";
            //Contact tm=new Contact();
            //Template tm=new Template();
            //   HttpServletRequest  re=(HttpServletRequest)tm.getReq();
            public String RunThis() {
                    try {
                    //String mact=(String)re.getParameter("a");
                    if (mact==null) { mact=""; }
                    String act=(String)Template.getAct();
                    if (act==null) { act=""; }
                    String title="NOT SET";
                    String op="NOT SET";
                    String page="";
                    if (act.equals("2")) {
                            title=act+"__page2";
                            op="page2";
                            page="login";
     
                    }else{
                            title="Contact Web support team";
                            op="Contact us here";
                            page=" page: contact <>"+act+" @ "+mact+" <br>";
                    }
                    setOP(op);
                    setPage(page);
                    setTitle(act+"--"+title);
                    } catch (Exception e) { output +="Error "+e; }
                    return output;
          }
        String done=(String)RunThis();
    }


    Within web.xml I am referring to the extended Contact Class


    <servlet>
    <servlet-name>Contact</servlet-name>
    <servlet-class>Contact</servlet-class>
    </servlet>

    <servlet-mapping>
    <servlet-name>Contact</servlet-name>
    <url-pattern>/Contact</url-pattern>
    </servlet-mapping>

    This works as far as the extended class Contact sending Template values - which it receives and does things accordingly.

    This version of Template doit was my attempt to try to get back the httprequest from the Template from within Contact
    HttpServletRequest rq=doit(reqs,resp);
    String act=(String)rq.getParameter("a");
    This has not worked either


    So in summary if I define
    //public static HttpServletRequest req;

    Above doPost/doGet - this then gets recognised in the extended Contact servlet but the value is always null.

    The issue I seem to be having is I can send values to the master Template.java which gets processed and viewed via Contact.java (which is the mapped servlet)

    But I can not seem to get the values from Template.java to be shown within Contact.java

    So within Contact.java I would be looking to get hold of request.getParameter and request.getSession etc
    Last edited by copeg; October 11th, 2011 at 11:25 AM.

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Extending a Servlet and sharing HttpServletRequest

    For future reference, please wrap your code within the [highlight=java][/highlight] tags. I have edited your post for you.

    I have read your post a few times - but I still don't understand. I was hoping your code would help, but it is jammed packed with tons of variables, methods, and objects which don't directly relate to the problem at hand and makes it very hard to wade through. I recommend cleaning it up on the form of an SSCCE that demonstrates the issue at hand.

  5. #5
    Junior Member
    Join Date
    Oct 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Extending a Servlet and sharing HttpServletRequest

     
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.net.URL;
     
    public class Template extends HttpServlet  {
            public String title="";
            public String page="";
            public void setTitle(String tit) { title = tit; }
            public void setPage(String pg) { page = pg; }
     
            // I have tried  a variety of methods of trying to pass request parameter 
            // To extended Contact Servlet
            //HttpServletRequest req;
            //public void setReq(HttpServletRequest r) { req=r;}
            ///public HttpServletRequest getReq() { return req; }
     
     
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
            doGet(request, response);
      }
      public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            HttpSession session = request.getSession(true);
            String act=(String)request.getParameter("a");
     
            //setReq(request);
     
            if (act==null) { act=""; }
            out.println("<html><head><title>"+title+"</title></head>");
            out.println("<body>"+page+"</body></html>");
     
     
    }
    }


    2nd Extended servlet - The one defined in web.xml

     
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class Contact extends Template {
            String output="";
            public String RunThis() {
                    try {
                      //HttpServletRequest req=(HttpServletRequest)Template.getReq();
                      String page=""; 
                      String title="";
                      //I am trying to bring in request values to here
                      //String act=req.getParamter("a");
                      String act="";
                      if (act.equals("2")) {
                       title="action = 2";
                       page="My 2nd page";
                      }else{
                       title="Main page";
                       page="My main page";
                      }
     
                    setPage(page);
                    setTitle(title);
                    } catch (Exception e) { output +="Error "+e; }
                    return output;
          }
     
        String done=(String)RunThis();
    }

    Now I have compiled this and it does appear to be working - I have disabled the req.getParameter("a") but in theory I am trying to pass all/any value from req.getParameter which is generated in Template back into Contact.java

    So if I did /servlets/Contact?a=2 no the web page I should see

    My 2nd page

    Hope its easier to understand

  6. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Extending a Servlet and sharing HttpServletRequest

    So if I understand correctly (again, still a bit fuzzy), the following might be a possibility: declare the Template as abstract, and define an abstract method that is implemented in the child class - this can then be accessed from within the parent class doGet method

    public abstract class Template extends HttpServlet{
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //do stuff
            String myString = runAbstract();
            //do something with myString
        }
     
        protected abstract String runAbstract();
     
    }
    public class Contact extends Template{
           @Override
            protected String runAbstract(){
                return "my string";
            }
    }

  7. #7
    Junior Member
    Join Date
    Oct 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Extending a Servlet and sharing HttpServletRequest

    Ye I been trying this - and in theory it would be in reverse - it still failed to work.

    If I explain what I am trying to achieve hopefully it will make more sense.

    If you take the code I have already provided, compile and run it - you will find the Template (although not defined in web.xml) is actually doing all the work in the background for Contact.java.

    Contact.java is simply producing what title/page content to show within Template.

    The theory and it does appear to be working - is for Template to be exactly this a Template for any Servlet I wish to create - It does all the required tasks I need within all my servlets - it returns the username,the ip address and if not logged in will redirect them to log in page.

    I expect the Template to only have the top part of my Servlet code - meaning checking username,authentication ip etc. This is what is required from all or any new servlet that is to go live.

    The Contact alongside with newservlet1 newservlet2 etc is supposed to extend Template and then look for specific doPost/doGet actions and action them accordingly.

    So in theory in Contact.java

    I have already got it to generate the Contact form page - it sends back title and page name and then Template.java loads up the page and shows headers/footers title etc.

    The next bit which is not working is for me to verify the form parameters which is where I am stuck at since I can not seem to pass values back from Template.

Similar Threads

  1. Assigning a Value to a Class extending a Superclass
    By ubermoe in forum Object Oriented Programming
    Replies: 9
    Last Post: September 22nd, 2011, 11:17 AM
  2. By using java how to listout sharing files in LAN...?
    By ram07 in forum Java Networking
    Replies: 4
    Last Post: March 26th, 2011, 10:18 PM
  3. Sharing my ByteStream, feel free to improve!
    By Verficon in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: March 7th, 2011, 10:44 AM
  4. Set headers for HttpServletRequest object?
    By FailMouse in forum Web Frameworks
    Replies: 3
    Last Post: December 1st, 2010, 03:00 PM
  5. class extending
    By Reem in forum What's Wrong With My Code?
    Replies: 4
    Last Post: November 18th, 2010, 01:49 AM