Getting ServletRequest in a JSP page?

Sorry about the newbie question, but how do you access the ServletRequest object in a JSP page? Specifically, the getParameter() functions? In servlets it's easy, the objects are passed in the doget() and dopost() functions, but I have no clue how to access it in JSP. Thanks.

Hi!
In JSP u've got implicit objects.
like how u use out.print in jsp. coz out is an implicit object. and for ServletRequest and ServletResponse u've request and response resp.ly.
http://java.sun.com/webservices/docs/ea1/tutorial/doc/JSPIntro7.html
click here to see other objects.

Similar Messages

  • How to get multiple selections from jsp page in my servlet

    Hello Everyone,
    I've a list that allows users to make multiple selections.
    <select name=location multiple="multiple">
        <option>
             All
        </option>
        <option>
             Hyd
        </option>
        <option>
             Dub
        </option>
        <option>
             Mtv
        </option>
      </select>I want to get the selections made by user in jsp page from my servlet, selections can be multiple too.
    ArrayList locList = new ArrayList();
    locList = request.getParameter("location");when I do so, I get compilation error as the request returns string type. How do I then get multiple selections made by the user.
    Please let me know.

    For those kind of basic questions it would help a lot if you just gently consult the javadocs and tutorials.
    HttpServletRequest API: [http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServletRequest.html]
    Java EE tutorial part II: [http://java.sun.com/javaee/5/docs/tutorial/doc/]
    Coreservlet tutorials: [http://courses.coreservlets.com/Course-Materials/]

  • Unable get complete filepath from jsp page using request.getParameter()

    Hey all,
    i am actually trying to get the selected file path value using request.getParameter into the servlet where i will read the (csv or txt) file but i dont get the full path but only the file name(test.txt) not the complete path(C:\\Temp\\test.txt) i selected in JSP page using browse file.
    Output :
    FILE NAME : TEST
    FILE PATH : test.txt
    Error : java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:106)
    at java.io.FileReader.<init>(FileReader.java:55)
    at com.test.TestServlet.processRequest(TestServlet.java:39)
    at com.test.TestServlet.doPost(TestServlet.java:75)
    JSP CODE:
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>DEMO SERVLET</title>
    </script>
    </head>
    <body>
    <h2>Hello World!</h2>
    <form name="myform" action="TestServlet" method="POST"
    FILE NAME : <input type="text" name="filename" value="" size="25" /><br><br>
    FILE SELECT : <input type="file" name="myfile" value="" width="25" /><br><br>
    <input type="submit" value="Submit" name="submit" />
    </form>
    </body>
    </html>
    Servlet Code :
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, FileNotFoundException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
    String filename = request.getParameter("filename");
    out.println(filename);
    String filepath = request.getParameter("myfile");
    out.println(filepath);
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet TestServlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");
    if (filepath != null) {
    File f = new File(filepath);
    BufferedReader br = new BufferedReader(new FileReader(f));
    String strLine;
    String[] tokens;
    while ((strLine = br.readLine()) != null) {
    tokens = strLine.split(",");
    for (int i = 0; i < tokens.length; i++) {
    out.println("<h1>Servlet TestServlet at " + tokens[i] + "</h1>");
    out.println("----------------");
    out.println("</body>");
    out.println("</html>");
    } finally {
    out.close();
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    Needed Output :
    FILE NAME : TEST
    FILE PATH : C:\\Temp\\test.txt
    Any suggestions Plz??

    As the [HTML specification|http://www.w3.org/TR/html401/interact/forms.html] states, you should be setting the enctype to multipart/form-data to be able to upload files to the server. In the server side, you need to process the multipart/form-data binary stream by parsing the HttpServletRequest#getInputStream(). It is a lot of work to get it to work flawlessly. There are 3rd party API's around which can do that for you, such as [Apache Commons FileUpload|http://commons.apache.org/fileupload] (carefully read the User Guide how to use it).
    You can also consider to use a Filter which makes use of the FileUpload API to preprocess the request so that you can continue writing the servlet code as usual. Here is an example: [http://balusc.blogspot.com/2007/11/multipartfilter.html].

  • How to get ep authority in jsp page

    Hi all:
    I want to create a j2ee project and some jsp pages to deploy to EP server.
    My question is how to get user name or user authority in jsp page.
    Is there any APIs to use or something else.
    Thanks in advance.
    Allen

    Hai ,
    I Think  This will help ful for u check it ,
    File=new FileLog("f:/WebServiceTrace/trace2.%g.log", 800000, 10,                                        new  TraceFormatter());
    The above code specifies the path for your log file.
    Then add this file as a log location and then log the traces. For this you can use the following code like:
    Location location=Location.getLocation(className);
              location.addLog(file);
              location.setEffectiveSeverity(Severity.ALL);
              location.entering(methodName);
    To Create j2ee apllication
    In path new-j2ee-jsp to create JSP's can only be used for J2EE applications.
    So as you are using this in Portal Application, this does not work.
    You can test this bahavior by creating a new Web Application (New-Project-J2EE-Web Module Project)
    In this Web Module Project, try creating JSP, this will work.
    So dont use new-j2ee-jsp to create JSP in Portal Application instead use New-File and name the file as jsp.
    Regards ,
    venkat

  • How to get table headers in jsp page

    hi,
    this is praveen, can any one help me to solve this problem.
    how to get table headers in a jsp page. whether it is possible using javascript or is there any other way.
    pls send rep.
    thank u.

    Hai ,
    I Think  This will help ful for u check it ,
    File=new FileLog("f:/WebServiceTrace/trace2.%g.log", 800000, 10,                                        new  TraceFormatter());
    The above code specifies the path for your log file.
    Then add this file as a log location and then log the traces. For this you can use the following code like:
    Location location=Location.getLocation(className);
              location.addLog(file);
              location.setEffectiveSeverity(Severity.ALL);
              location.entering(methodName);
    To Create j2ee apllication
    In path new-j2ee-jsp to create JSP's can only be used for J2EE applications.
    So as you are using this in Portal Application, this does not work.
    You can test this bahavior by creating a new Web Application (New-Project-J2EE-Web Module Project)
    In this Web Module Project, try creating JSP, this will work.
    So dont use new-j2ee-jsp to create JSP in Portal Application instead use New-File and name the file as jsp.
    Regards ,
    venkat

  • How to get Tree structure in JSP page?

    Hi,
    I would like get data from the database and display the data in tree structure with the check boxes at each nodes on a jsp page with out using any third party tools. how can i do that? Do i require any new tags to fulfill this requirement?
    can any one help me out by sending any example code?
    thanks in advance.
    Regards,
    Reddy

    Once you have the data in a list or something, can't you just use <c:forEach> and then output standard nested <ul> and <li> tags to give the tree structure.
    <html>
         <style>
              li
                   list-style-type:none;
         </style>
         <body>
              <form>
                   <ul>
                        <li>
                             <input type="checkbox">Check 1</input>
                             <ul>
                                  <li>
                                       <input type="checkbox">Check 1A</input>
                                  </li>
                                  <li>
                                       <input type="checkbox">Check 1B</input>
                                  </li>
                             </ul>
                        </li>
                        <li>
                             <input type="checkbox">Check 2</input>
                             <ul>
                                  <li>
                                       <input type="checkbox">Check 2A</input>
                                  </li>
                             </ul>
                        </li>
                        <li>
                             <input type="checkbox">Check 3</input>
                        </li>
                   </ul>
              </form>
         </body>
    </html>

  • Problem in getting an object in JSP page.

    Hi experts,
    I am forming a javabean object in the controller(servlet) and passing the object to a JSP page by setting that object as an attribute. But in that jsp page, when i compile, its not able to locate the class. At the beginning itself while typecasting the attribute as that bean object, i get an error. All the servlet, bean files are in the default package only.
    This is how i used..
    <%
    String m = (String) request.getAttribute("mode");
    //My bean object below.
    adjuster_bean res=(adjuster_bean)request.getAttribute("data");
    %>
    And i am using like, calling the bean object's get method to set values of the text boxes in the JSP page. I need help please....

    Vigsen wrote:
    Hi experts,
    I am forming a javabean object in the controller(servlet) and passing the object to a JSP page by setting that object as an attribute. But in that jsp page, when i compile, its not able to locate the class. At the beginning itself while typecasting the attribute as that bean object, i get an error. All the servlet, bean files are in the default package only.
    This is how i used..
    <%
    String m = (String) request.getAttribute("mode");
    //My bean object below.
    adjuster_bean res=(adjuster_bean)request.getAttribute("data");
    %>
    And i am using like, calling the bean object's get method to set values of the text boxes in the JSP page. I need help please....Are you importing the bean class in your jsp? Something like this...
    <%@ page import="java.util.*, yourpackage.YourBeanClass" %> Secondly, I see standards not followed in your code...
    a) Firstly, as someone else pointed out in this same post. Avoid as much as possible using java scriplets in JSPs. Instead try use JSTL and EL expressions.
    b) A java class name should always start with capital letter for every word in the class name and with no underscores. Your bean class name (adjuster_bean) should be changed to something like AdjusterBean
    If you want to become a good Java programmer then standards are essential. But, again, it is totally up to you to follow.

  • How get ServletContext from within JSP-page

    Hi! I was wondering how to get the ServletContext from within a JSP-page?
    /Ernstad

    The "application" implicit scripting variable is the same thing. e.g
    application.getAttribute(...);

  • Can a servlet get paramters from two jsp pages?

    Hi all,
    I am writing a servlet to get the parameters from two different jsp pages, but I can not find any solution for this problem. Is there any way to solve this problem ?
    Any suggestion ?
    Thanks in advance.

    I am writing a servlet to get the parameters from two
    different jsp pages, what do you mean by that?
    please elaborate your question.

  • Best practice of getting request parameters in JSP page

    int period_Id = 0;
    try
    period_Id = Integer.parseInt(request.getParameter("period_id"));
    catch(Exception e)
      period_Id = 0;
    }This is the normal way we use to get parameters from previous page.
    But I am not sure if it is thebest practice.
    Please respond if anyone knows a better way.
    Regards

    Using java code in a JSP is a horrible practice. There are far better ways to write JSP's nowadays in the form of custom tags, JSTL and possibly JSF. Combined with servlets this will make your code clean, reusable and maintainable.
    However if you insist and using scriptlets, I'd say create your own request bean that wraps around the HttpServletRequest and write methods getParameterInt(), getParameterDouble(), etc. Such a method could look like this:
    public int getParameterInt(String name, int default)
    String paramstr = request.getParameter(name);
    if(paramstr == null || paramstr.length() == 0){
      return default;
    try{
       return Integer.parseInt(paramstr);
    } catch(Exception e) {
      return default;
    }With such a bean you never have to do that exception catching yourself again: you can just pass the parameter name and a default value that will be returned if the parameter does not exist or is not a valid integer.

  • How to get current time in jsp page?

    my problem is :-
    i have a radio buttons with name as 9am, 11am ,1pm, 3pm , 5pm , 7pm , 9pm , 11pm , 1am , 3am ,5am 7am. what ever the current time may be the radio button of four hour plus than current time should be atomatically checked and previous radio buttons should be disabled. for example suppose current time is 11.02am than the radio button of 3pm should be automatically checked and previous radio buttons should be disabled.
    please help me if u can?

    This should work but it needs testing out around midnight ( not sure if it is 00:00 or 24:00):
    <%@ page import="java.util.*" %>
    <html>
    <head><title>Time Page</title>
    </head>
    <body>
    <% Calendar c = Calendar.getInstance();
       c.add(Calendar.HOUR_OF_DAY, 4);
       int h = c.get(Calendar.HOUR_OF_DAY); %>
    The current hour is <%= h %><br>
    <% for (int i=0; i < 24; i++) { %>
       <input type=radio name=time <%= (i < h) ? "disabled" : ""%><%= (i == h) ? "checked" : ""%>><%= (i < 10) ? "0" : ""%><%= i %>:00<br>
    <% } %>
    </body>
    </html>

  • Get username in external jsp page + oracle10g 10.1.2 portal server

    &lt;%@page contentType="text/html; charset=windows-1252"
    import="oracle.portal.provider.v2.render.PortletRenderRequest"
    import="oracle.portal.provider.v2.http.HttpCommonConstants"
    import="oracle.portal.provider.v2.ParameterDefinition"
    %&gt;
    &lt;%
    PortletRenderRequest pReq = (PortletRenderRequest)
    request.getAttribute(HttpCommonConstants.PORTLET_RENDER_REQUEST);
    %&gt;
    <p>
    Hello &lt;%= pReq.getUser().getName() %&gt;.
    </p>
    The above code will show the userName in java pdk portlet.
    But I want to show the username in external jsp.which I uploaded into oracle10g 10.1.2 portal server.
    what can i do?
    Please help me in this issue?
    Thanks
    uday.
    Edited by: Shubhadeep on Oct 30, 2008 11:43 AM

    &lt;%@page contentType="text/html; charset=windows-1252"
    import="oracle.portal.provider.v2.render.PortletRenderRequest"
    import="oracle.portal.provider.v2.http.HttpCommonConstants"
    import="oracle.portal.provider.v2.ParameterDefinition"
    %&gt;
    &lt;%
    PortletRenderRequest pReq = (PortletRenderRequest)
    request.getAttribute(HttpCommonConstants.PORTLET_RENDER_REQUEST);
    %&gt;
    <p>
    Hello &lt;%= pReq.getUser().getName() %&gt;.
    </p>
    The above code will show the userName in java pdk portlet.
    But I want to show the username in external jsp.which I uploaded into oracle10g 10.1.2 portal server.
    what can i do?
    Please help me in this issue?
    Thanks
    uday.
    Edited by: Shubhadeep on Oct 30, 2008 11:43 AM

  • How to get Parameters in a jsp page called by VB program via xmlHttp

    I have a VB programm sending a request using xmlHttp.
    xmlHttp.Open "POST", varTarget, True 'True means asynchronous
    xmlHttp.Send xmlSendStr
    This worked fine with ASP
    the crucial ASP code was:
         set xml = server.createObject("MSXML2.DOMDocument")
         xml.load(request)
         VBData = cstr(xml.getElementsByTagName("value").item(0).firstChild.nodeValue)
    now I have a webserver (tomcat) and try to have a simular functionality
    but
    request.getParameter()
    seems not to do the job.
    what do I have to do
    I am thankfully looking forward to you reply
    peter

    Hi,
    thanks for your reply!
    If I have the parameters in the URL and use the method GET it works all right.
    but I need the method to be POST. I suppose, I have the wrong way identifying the parameter name
    This is from VB
    varTarget = "http://localhost:9090/gm/getData" ' getData is my servlet
    xmlSendStr = "SQLStmt=SELECT TCPD_Cars.* From TCPD_Cars WHERE (((TCPD_Cars.CarIdent)=45));"
        xmlHttp.Open "POST", varTarget, True   'True means asynchronous
        xmlHttp.Send xmlSendStrthis is part of my Servlet
         protected void doPost(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, IOException {
              response.setContentType("text/html");
              PrintWriter writer  = response.getWriter();
              String SQLStmt = request.getParameter("SQLStmt") ;
            //make the database query and get the returns
            writer.println(GetSQLData(SQLStmt));
            //close the write
            writer.close();                    
         }I would appreciate any suggestions

  • How can I get the "pageContext" object in jsp page?

    Hi everyone:
    I want to get struts's DataSource object in jsp page.So I should get the PageContext object in jsp page.My code is:
    ///////////////////datatest.jsp///////////////////////////////////
         DataSource ds=(DataSource)pageContext.getAttribute(Action.DATA_SOURCE_KEY);
         conn=ds.getConnection();
              stm=conn.createStatement();
              rs=stm.executeQuery(insertsql);
    Is right?But I get the "NullPointerException" error in Tomcat.The connection pool in struts-config.xml is:
    <data-sources>
    <data-source key="mydatasource">
    <set-property property="autoCommit"
    value="false"/>
    <set-property property="description"
    value="MyWebSite Data Source Configuration"/>
    <set-property property="driverClass"
    value="org.gjt.mm.mysql.Driver"/>
    <set-property property="maxCount"
    value="4"/>
    <set-property property="minCount"
    value="2"/>
    <set-property property="password"
    value="qijiashe"/>
    <set-property property="url"
    value="jdbc:mysql://localhost:3306/myweb"/>
    <set-property property="user"
    value="lyo"/>
    </data-source>
    </data-sources>
    I can query the database in servlet.
    I think the method that I get the context is not right.Had someone get the pagecontext in jsp page?help :(

    Sorry I forgot that I had change the code:
    DataSource ds=(DataSource)pageContext.getAttribute(Action.DATA_SOURCE_KEY);
         conn=ds.getConnection();
              stm=conn.createStatement();
              rs=stm.executeQuery(insertsql);
    to the code:
    DataSource ds=(DataSource)pageContext.getAttribute("mydatasource");
         conn=ds.getConnection();
              stm=conn.createStatement();
              rs=stm.executeQuery(insertsql);
    mydatasource is the struts datasource in "struts-config.xml". I couldn't work

  • The Page is directly getting redirected to the next page

    I have tried using response.redirect("filename.jsp") in the two buttons as shown below but the pages are getting directly to the next page without loading the first page.Even though i write a .js file and include it in the jsp file that method is not getting called into the jsp page.Please advice.....stuck here.
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Main</title>
    <script src="All.js">
    </script>
    </head>
    <body>
    <form name="one" >
    <h1>Please Choose : </h1>
    <table width="158" border="1">
    <tr>
    <td>
    <input type="button" value="Insert Record" onclick=""/>
    <a href="# onclick="insert();"></a>
    </td>
    </tr>
    <tr>
    <td align="left" valign="middle"><input type="submit" value="Delete/View" /><a href="# onclick="" target="insert()"></a></td>
    <!--td align="left" valign="middle"><input type="submit" value="Delete/View" /><a href="# onClick="insert();" target="_self""></a></td-->
    </tr>
    </table>
    </form>
    </body>
    </html>

    where you use response.redirect()? What is in insert()?

Maybe you are looking for

  • HT201071 Why no Raw support for Fujifilm XF 1 in Aperture?

    When will Apple support my camera the Fujifilm XF1, I prefer using Aperture but will be forced in to Lightroom.

  • Query regarding interface

    Hi All, I have one interface with method XYZ... i am implementing that method with the help of classes ZCL and ZCL1 ...suppose when i am implemetig interface with class ZCL then its output is 123 and with class ZCL1 output is 456 ...when i call the i

  • BR1310G AP issue

                       I have 2 BR1310G APS configured for bridge mode to extend a LAN between two buildings. The setup worked for 3 years flawlessly. One day, they started having network problems across the bridge. Pinging across the bridge shows time-o

  • Dead message queue

    Intial information: SUN MQ 4.3 Local installation Purpose: use dead message queue. As per refered in SUN MQ admin guide have updated the broker imqcmd update dst -t q -n TestQueue1 -o useDMQ=true imqcmd update dst -t q -n TestQueue1 -o MaxBytesPerMsg

  • "SFC /VERIFYFILE" doesn't work. Is it a BUG?

    Hello to all. Original topic: hxxp://answers.microsoft.com/en-us/windows/forum/windows8_1-performance/sfc-verifyfile-doesnt-work-is-it-a-bug/17542cd5-1eee-4cb1-948c-d9ff68267e3a I found that SFC /VERIFYFILE doesn't work on my machine. I can't know if