Redirecting the servlet output to jsp

Hi i need to redirect my servlet out put to jsp
in result set's every row i have 9 columns
this result set how can i redirct to jsp
plz can any one let me know with an example
thanks a lot in advance

inamdar wrote:
Hi i have never used DTO's and DAO classes
plz colud u let me know without using that..Huh? It is never too late to start with it. Just create two simple classes. A DTO class is basically a simple javabean with private (encapsulated) properties and a public getter and setter for each property. A DAO class is basically a class which contains purely JDBC code.
Sample DTO:public class MyData {
    private Long id;
    private String name;
    private Integer value;
    public Long getId() { return id; }
    public String getName() { return name; }
    public Integer getValue() { return value; }
    public void setId(Long id) { this.id = id; }
    public void setName(String name) { this.name = name; }
    public void setValue(Integer value) { this.value = value; }
}Sample DAO:public class MyDataDAO {
    public List<MyData> listAll() {
        String listAllQuery = "SELECT id, name, value FROM data";
        List<MyData> myDataList = new ArrayList<MyData>();
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = getConnectionSomehow(); // DriverManager or Connection Pool, your choice.
            statement = connection.createStatement();
            resultSet = statement.executeQuery(listAllQuery);
            while(resultSet.next()) {
                MyData myData = new MyData();
                myData.setId(new Long(resultSet.getLong("id")));
                myData.setName(resultSet.getString("name"));
                myData.setValue(new Integer(resultSet.getInt("value")));
                myDataList.add(myData);
        } catch (SQLException e) {
            // Handle it. Print it, throw it, log it, mail it, your choice.
            e.printStackTrace();
        } finally {
            // You can write an utility class/method for those lines as well.
            if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } }
            if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } }
            if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } }
        return myDataList;
}Sample Servlet code:List<MyData> myDataList = new MyDataDAO().listAll();
request.setAttribute("myDataList", myDataList);
request.getRequestDispatcher("someJspFile.jsp").forward(request, response);Sample JSTL code in someJspFile.jsp:<table>
    <c:forEach items="${myDataList}" var="myData">
        <tr>
            <td>${myData.id}</td>
            <td>${myData.name}</td>
            <td>${myData.value}</td>
        </tr>
    </c:forEach>
</table>Simple and clean, isn't it?

Similar Messages

  • Is the raw output from JSP and XSQLServlet the same?

    Hi
    Is there is difference between the raw output from XSQLServlet and JSP? For example, assuming the same content is being generated, is there some additional header information emitted by XSQLServlet that is not done by JSP?
    I am using software that successfully consumes generated content from a JSP OK, but the same content (using the same XML/XSL) generated from XSQLServlet is being rejected. I am puzzled by this. Maybe this is due to some differences in servlet output or an encoding issue? The content is not HTML but XML-like with an "application" contentType, like Steve's SVG example.
    It seems that XSQLServlet is showing some data prior to emitting the actual content, i.e. HTTP version, responding server version, content type and date, e.g.
    HTTP/1.0 200 OK^M
    Server: Resin/2.0.5^M
    Content-type: application/x-sky; charset=UTF-8^M
    Date: Thu, 28 Mar 2002 06:45:34 GMT^M
    ^M
    (then the generated content)
    Is this preamble usually generated by a JSP also?
    If not, can this information be turned off, or put another way, can XSQLServlet's raw output be set to be exactly like JSP? If not, is there a workaround?
    I have tried setting the following XSQLConfig.xml
    <suppress-mime-charset> for the mime-type &
    <character-set-conversion>
    <none/>
    </character-set-conversion>
    also, but to no avail.
    Please help! I really want to use XSQLServlet!
    Thanks.
    Michael.

    Yes, just less fine control over the process but the same engine.
    Regards
    TD

  • Can you redirect the audio output of iTunes via Apple TV?

    I currently have iTunes running on Windows XP with an Airport Express connected to my home stereo. I toggle the iTunes audio between my PC and the Airport Express via the iTunes speaker setting. With Apple TV, will I be able to toggle the audio output from the Apple TV interface?
    Thanks,
    Chaaad

    No, you can use AppleTV like an Express to have audio playing in iTunes relayed to it, but you can't play something on AppleTV and direct the output to the Express.
    AC

  • How to print out the exception caught in the servlet controller to JSP?

    May I know how to print the Exception caught and the stacktrace thing? What i try to do this in the databaseErrata.jsp code was not given me any answer. Instead, causing a number of errors.
    Below are my servlet controller code and databaseErrata.jsp code.
    ----$CATALINA_HOME/webapps/mvct/WEB-INF/classes/Action.java----
    import java.io.*;
    import java.sql.*;
    import java.text.*;
    import javax.naming.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import foo.*;
    public class Action extends HttpServlet
      public void doGet(HttpServletRequest request,
    HttpServletResponse response)
        throws ServletException, IOException
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        // find real web resource
        String forward = request.getServletPath();
    //'forward' is a string variable consist of url
        if(forward.endsWith(".do"))
          forward = forward.substring(1, forward.length()
    -3) + ".jsp";
        else
          throw new ServletException(
          "Action servlet called with illegal path: " +
    forward); //display the defined error msg and error
    url within the 'forward'
    out.println("forward after forward.substring() = " +
    forward + "</br>");
        // build and validate view page attributes
        HttpSession session = request.getSession();
        try
          byEmployeeId convert =
    (byEmployeeId)session.getAttribute("convert");
          if(convert == null)
            session.setAttribute("convert", convert = new
    byEmployeeId());
          convert.start("11145");
        catch(NamingException ex)
          request.setAttribute("exception", ex);
          forward = "databaseError.jsp";
        catch(SQLException ex)
          request.setAttribute("exception", ex);
          forward = "databaseErrata.jsp";
        catch(IllegalArgumentException ex)
          request.setAttribute("message", "<FONT COLOR='red'>"+ex.getMessage()+"</font>");
        // forward request
        RequestDispatcher rd =
    request.getRequestDispatcher(forward);
        rd.forward(request,response);
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
        throws ServletException, IOException
          doGet(request, response);
    }----$CATALINA_HOME/webapps/mvct/databaseErrata.jsp----
    <% String message = (String)request.getAttribute("message"); %>
    <HTML>
    <HEAD>
    <TITLE>databaseErrata.jsp Page</TITLE>
    </HEAD>
    <BODY>
    <% if (message != null) { %>
    Message = <%= message %>
    <H1>databaseErrata.jsp Page</H1>
    </BODY>
    </HTML>

    You're missing a closing curly bracket in the JSP page.
    Also, this will only print the exception message. I would recommend passing on the whole Exception object.
    ie request.setAttribute("theException", ex);
    That way you have the exception object to print the stacktrace from.
    However, you are doing this manually. The container can handle this stuff for you if you so wish.
    Check the documentation on error pages. You are able to set up an error page in the web.xml, that all exceptions/errors get directed to.
    something like:
    <error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/errorPages/debugError.jsp</location>
    </error-page>
    You then write the JSP page something like this
    <%@ page language="java" %>
    <%@ page isErrorPage="true" %>
    <%@ page import="java.util.*, java.io.*" %>
    <h1>Programming error <BR> FOR DEBUGGING PURPOSES ONLY</h1>
    <p>This page is only for debugging purposes.  Should not be deployed to live environment.</p>
    <p>Details of the error are as follows:</p>
    <table border = 1 width=200>
    <tr><td valign=top><strong>Error :</strong></td><td><%=exception.getMessage()%></td></tr>
    <tr><td valign=top width='80%'><strong>Trace :</strong></td><td><pre><% exception.printStackTrace(new PrintWriter(out));%></pre></td></tr>
    </table>
    <br>Cheers,
    evnafets

  • Redirect the class output.

    Hi!
    I am new to java.
    I have a class file that print to output a result from three parameters I pass to it, this class are byte code compiled and I am not have the source code.
    I want to know how to redirect this output to an variable into my program.
    thank in advance.
    Paulo

    It's possible, although slightly involved. If you look at the System class, you'll see a method [url http://java.sun.com/j2se/1.4/docs/api/java/lang/System.html#setOut(java.io.PrintStream)]setOut. This allows you to set the stream to which the other class is writing its output. So what to set it to? Well, you presumably want to get the output as a String, so I suggest the following: import java.io.*
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    System.setOut(new PrintStream(out));
    // Call other class here.
    String output = out.toString();

  • Redirect the refcursor output of an SP to a table ?

    hi.
    i have an SP which returns a refcursor. now what i need is to get this output to a table so that i can manupulate the data.
    this is how i executed the table
    var a refcursor
    exec packagename.spname(:a,'inputchar');
    print :a;
    please help.
    i tried create table temp as select * from :a
    and
    create table temp as select * from table (cast a as a)
    but both didnt work..
    what am i missing here ????

    novicedba wrote:
    the SP is not mine. so i cannot alter it.So? That does not make something less wrong.
    suppose the refursor returns itemcode, purchase_time, price. and details of 100+ items are returning in thi refcursor. what i need is first to get the results. and then filter it only to view detaild of one item. Why? That cursor does work (in the SQL engine) to find the relevant rows (using indexes and/or tables reading data blocks). It does +"x"+ amount of work to output the results for that SQL select statement.
    Now you want to filter, in PL/SQL or another client language, the output of that cursor. That filtering should be done by the SQL engine - as it is best suited for doing that work. And the workload of +"x"+ that was needed, can now be +"x/2"+ as a result - as the filtering and elimination of columns not needed from the SQL projection can significantly decrease the workload and increase performance.
    So what benefits are there to filter the output of a cursor? NONE! There are no benefits. Not a single one.
    this is why i need to get the Output into a table.The cursor returns data from the SQL engine. This data needs to be pushed from the SGA db buffer cache all the way to the client language. In the case of PL/SQL, into the private heap space of the process (called the PGA).
    Then you take that very same data, create an insert SQL cursor, and send that data back to the SQL engine to be inserted.
    So what benefits are there pushing and pulling SQL data like this across memory and process and even platform boundaries, when the both the read data and write data processes could have been done as a SQL "+insert .. select+" cursor? NONE! There are no benefits. Not a single one.
    (no wonder this sounds like TSQL coz i am more familiar to TSQL than PL ;) (irrelevant stuff) )Treating PL/SQL like TSQL 'cause your are "familiar" with TSQL is, bluntly put, idiotic. PL/SQL is not TSQL. Oracle is not MS-SQL Server.
    if i am going for a cast.. what should i do ?I would go instead for the manuals.. and educate myself on the concepts and fundamentals of the product and languages I'm using. And design and write robust and performant and flexible and scalable code.

  • The PDF output is not always displayed!

    Hello
    I'm tryin' to build some PDF outputs and I have the next problem: I have 20 reports to make it on PDF form (viewed with the Acrobat plugin from IE 5.5 or higher) and when I try to see what was builded the PDF it's not always displayed ( mean it's not readed by the plugin). I generate the PDF output from a servlet (which also set the servlet output context as 'application/pdf') and, if the output it's generated too fast (meanning the report information was too small), the Acrobat plugin doesn't catch him ! I think that I have to slow down the servlet response to allow the plugin complete loading, but I don't khow how to do this (and, ofcourse, if it's possible).
    Please, I need a solution. !
    Thanx!

    Hi,
    setting content type as application/pdf is quite enough for the plugin to catch
    I generate the PDF output from a servlet
    (which also set the servlet output context as
    'application/pdf') and, if the output it's generated
    too fast (meanning the report information was too
    small), the Acrobat plugin doesn't catch him !but i think IE has a problem catching this, cause i also once ran thro this kind of problem
    I think that I have to slow down the servlet response to allow
    the plugin complete loading, but I don't khow how to
    do this (and, ofcourse, if it's possible). Yes it is possible.... if ur sevrvlet ehich is displaying pdf is http://host/PdfServert
    just make in such a way that the extention is pdf..
    http://host/PdfServert?xy=z.pdf or register the servlet with .pdf ext
    http://host/PdfServert.pdf...
    belive it really worked perfect for me..
    regards,
    Arun.N

  • How to display outsream from a servlet in a JSP

    I wrote a jsp file to call a Servlet, then want to display the result from the servlet in another jsp file. Anyone can give me possible solution or an example to illustrate it.
    Many thanks in advance.
    the file that call servlet in a jsp is as follow
    <form method="POST" action="myservlet">
    <table>
    <tr>
    <th align="center" colspan="2">
    Enter The query words
    </th>
    </tr>
    <tr>
    <th align="right">query words:</th>
    <td align="left">
    <input type="text" name="querywords" size="60">
    </td>
    </tr>
    <tr>
    <td align="right">
    <input type="submit" value="Search">
    </td>
    <td align="left">
    <input type="reset" value="Reset">
    </td>
    </tr>
    </table>
    </form>
    ............

    I would suggest that you use the Servlet to retrieve the data you are after and store it in the session. Then forward the user onto the JSP page where it can retrieve the object from the session and present it to the user in a formatted view.

  • Servlet Output Streams and clearing

    I am using servlets, and I want to be able to print something repeatedly. Well, that's not exactly true: I can print something repeatedly. Using a ServletOutputStream, it doesn't seem possible to clear what has already been written. Here's the code:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.io.*;
    public class AlwaysTime extends HttpServlet {
         public void doPost(HttpServletRequest req, HttpServletResponse res)                throws ServletException, IOException {
              HttpServletResponse oldRes = res;
              Date now = new Date();
              res.setContentType("text/html");
              ServletOutputStream out = res.getOutputStream();
              out.println("<html>");
              out.println("<head>");
              out.println("<title>Clock</title>");
              out.println("</head>");
              out.println("<body>");
              out.println("<h1 align=\"Center\">");
              out.println(now.toString());
              out.println("</h1>");
              out.println("</body>");
              out.println("</html>");
              try {
                 Thread.sleep(1000);
              } catch (InterruptedException ie) {}
              // Do nothing: wait for 1 second.
              doPost(req, oldRes);
         public void doGet(HttpServletRequest req, HttpServletResponse res)
              throws ServletException, IOException {
              doPost(req, res);
    }This code prints the time every second, but I want to clear the previous output stream. I thought the code shown above would work, but of course, oldRes points to the same object as res. But I don't know how to clear an output stream, so that it is completely empty. Instead, each of the new lines are appended to the same output stream.
    This doesn't only apply to servlet output streams: is there some way to clear the System output stream, for instance?
    But mainly the servlet output stream ...

    You would not want to use HTTP for this type of functionality. HTTP is known as a 'stateless' protocol that simply returns one exact response for each request. So, there is not way to 'clear' the stream (technically, you would not do so for 'normal' streams either, but when you add HTTP into the mix, the task is definitely not possible).
    You could implement the above using a RSS feed, or by using HTTP meta-refresh tags on the page itself ot resubmit the requests every second (though this would be inefficient). An applet would also do the task.
    - Saish

  • Is this the best way to redirect using servlet?

    I making a servlet application where the user sends some FORM value to a servlet. I want the servlet to redirect to the answer page after processing the page. Do you think the following code is the correct way of doing?
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            String dnaText = request.getParameter("dnaText");
            /*Getting the tranlated output from dnaToRna method*/
            String finalVal = null;
            String link="http://www.mail.yahoo.com";
            try{
                 finalVal = String.valueOf(dnaToRna(dnaText));
                 response.sendRedirect(link);
                }catch(Exception ex){}
        }

    Many thanks for replying.
    My output file have lots of html code and I dont want to make my servlet heavy with unnecessary code. So I have decided to use another page result.jsp as output file. In result.jsp I intend to call these objects which is storing the value here to display the result.
    As I am new to jsp. I am still in the processing of thinking the best way to handle errors. I have created a method which takes in int values and returns corresponding String values. Like this
    public class DnaToRna extends HttpServlet {
       String error=" * NULL *";
    private String printError(int i) {
            if(i==1){
                error = "There is an error in String to char array";
            }else if (i==2){
                error = "There is an error in your DNA sequence";
            return error;
        }Since error is declared as a class object, if there is no error then I think it should rerun the String NULL. Which can be used to tell people if there is no error. On the contrary if there is really an error, I can use this to tell what is exactly causing the error.
    Although I am new to web programing. I think this would be nice.
    Here is the other method
    public String dnaToRna (String dnaText) throws Exception{
                /*Trim()*/
                dnaText = dnaText.trim();
                /*Codes for Dna to Rna translation*/
                if(Pattern.matches(".*[^atgc]+.*",dnaText))
                return printError(2);
                return dnaText.replaceAll("t","u");
                }

  • Capturing the output from jsp selvlet

              Hi,
              I have a requirement where I need to capture the output of the JSP generated servlet
              , and do something with it before it get's to the client side.
              Has someone done something like this before.Any ideas, suggestions .
              Thanx,
              Tajdar
              

    You can set the MIME content type as .doc and try to open the Page.
    res.setContentType("application/vnd.ms-excel"); to generate the Page output as Excel
    res.setContentType("application/vnd.ms-word"); to generate the Page output as MS Word doc
    Hope this helps..

  • How to specify the servlet in the ACTION field in FORM in jsp, html pages?

    I have problem when I return back to the page prova3.html from the servlet because in the address bar it give me this path:
    http://192.168.161.209:8988/Workspace3-Project1-context-root/servlet/servlet/Servlet1
    two times servlet/ why? and what I have to put in the action field?
    This is my form in page prova3.html:
    <form action="servlet/Servlet1" method="post" id="search" style="font: bold 80% Arial,sans-serif; color: #334d55;" >
    <input type="hidden" name="pagina" value="1"/>
         user<input name="username" type="text" size="10" style="font-size: 12px;"/> 
    password<input name="password" type="password" size="10" style="font-size: 12px;"/>
         <input name="login" type="submit" value="Login" style="font-size: 12px; font-family: Arial,sans-serif;"/>
    </form>
    The redirection form servlet to pages is:
    private void toProvaPage(HttpServletRequest request, HttpServletResponse response) throws
    ServletException, IOException {
    RequestDispatcher rd = getServletContext().getRequestDispatcher(
    "/prova.jsp");
    rd.forward(request, response);
    private void toIndexPage(HttpServletRequest request, HttpServletResponse response) throws
    ServletException, IOException {
    RequestDispatcher rd = getServletContext().getRequestDispatcher(
    "/prova3.html");
    rd.forward(request, response);
    Thanks, but I can solve this problem.

    This is my web.xml file where the mapping is specified, this is the thing that I can't understand.
    <web-app>
    <description>Empty web.xml file for Web Application</description>
    <display-name>public_html</display-name>
    <servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-class>servlet.Servlet1</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/servlet1</url-pattern>
    </servlet-mapping>
    <session-config>
    <session-timeout>35</session-timeout>
    </session-config>
    <mime-mapping>
    <extension>html</extension>
    <mime-type>text/html</mime-type>
    </mime-mapping>
    <mime-mapping>
    <extension>txt</extension>
    <mime-type>text/plain</mime-type>
    </mime-mapping>
    </web-app>
    Thanks

  • How to compress JSP/Servlet output with WebCache?

    Hello,
    I have an application using servlet/JSP. A request coming from the browser is handle by a servlet, and then forward the processing to a JSP page that produces the response. The requests are like http://host:port/athena/execute/action and we use POST method. It seems WebCache does not compress the output if I specify this compression rule
    URL expression: ^/athena/.*$
    Method POST
    POST Body Expression .*
    What's wrong ??
    Thanks in advance.

    This is already answered in another identical thread.

  • Controlling JSP/servlet output buffering

    I'm doing some performance testing on some JSPs and I need to be able
              to separate client side rendering/javascript execution time from
              server side execution of the (JSP-generated) servlet.
              The normal way for the servlet generated from the JSP to behave is
              that the output stream to the browser is buffered - that is, as the
              servlet generates output it is written to the buffer in chunks and the
              buffer is written to the browser in chunks. On all but the shortest
              pages the content from the bottom of the JSP hasn't even been
              generated yet at the time the buffer starts writing to the browser.
              I want to turn this behavior off. I want no output sent to the browser
              until the whole output is generated. This way I can put timers in my
              client side Javascript and know they are measuring only the client
              side execution time, not the server side.
              Does anyone know how to do this?
              Eliot Stock
              Premiere Retail Networks
              San Francisco
              

    Hi Eliot,
              you can use the page directive's buffer and autoFlush attributes to
              control the size of the output buffer.
              <%@ page buffer="100kb" autoFlush="false" %>
              Here's a link:
              http://java.sun.com/products/jsp/tags/10/syntaxref10.fm7.html
              Nils
              Eliot Stock wrote:
              >
              > I'm doing some performance testing on some JSPs and I need to be able
              > to separate client side rendering/javascript execution time from
              > server side execution of the (JSP-generated) servlet.
              >
              > The normal way for the servlet generated from the JSP to behave is
              > that the output stream to the browser is buffered - that is, as the
              > servlet generates output it is written to the buffer in chunks and the
              > buffer is written to the browser in chunks. On all but the shortest
              > pages the content from the bottom of the JSP hasn't even been
              > generated yet at the time the buffer starts writing to the browser.
              >
              > I want to turn this behavior off. I want no output sent to the browser
              > until the whole output is generated. This way I can put timers in my
              > client side Javascript and know they are measuring only the client
              > side execution time, not the server side.
              >
              > Does anyone know how to do this?
              >
              > Eliot Stock
              > Premiere Retail Networks
              > San Francisco
              ============================
              [email protected]
              

  • How to use the same bean from Jsp and Servlet

    I want to use the same bean instance from both the servlet and jsp.
    for eg. if a create a bean using the jsp:useBean in servlet and if a modify some values, that values should be reflected while i access the same bean from the servlet. But instead of that the servlet is creating a new instance of the bean.
    is it possible?
    Thanks in advance

    Hi,
    When you call jsp:useBean you inform a scope (session, request, page...)
    This means the bean instance will be stored in that scope.
    So, if the informed scope is session, then, in the servlet you could get the bean instance back from the session, this way:
    HttpSession session = request.getSession();
    Bean b = (Bean) session.getAttribute("bean_id");
    Regards,
    Filipe Fedalto

Maybe you are looking for

  • How can I install an E-Mail CA Certificate?

    I have a friend who just bought an iPhone within the past month. Where can I find the information necessary on how to guide her to install an E-Mail CA Certificate on her iPhone?

  • Mac running Yosemite now very slow with crashes

    Can anyone help? I'm running Yosemite 10.10.2 on a MacBook Air (Late 2010) and it's got progressively worse since upgrading from Mavericks. I'm seeing unbelievably slow and sluggish behaviour across the system. A reboot helps initially, but then it g

  • File Receiver Adapter - time stamp in front possible ?

    Hi all together, is it possible with the file receiver adapter to add a time stamp in front of the filename? f.ex. <timestamp>_SUFFIX.dat With file creation mode "use timestamp" and file name scheme SUFFIX_.dat it will create SUFFIX_<timestamp>.dat  

  • Supported flat panel displays for an ATI Rage 128 Pro/G4 500

    I originally was using an Apple 21" CRT display with my G4/500 until the display's picture tube failed. I am now looking to purchase a flat panel w/DVI, using my G4's DVI video port and the Rage 128 Pro card. I have found conflicting information on r

  • Workspace issue in EPM 11.1.2.1

    Hello Experts, I have an issue in EPM 11.1.2.1 workspace.I have epm 11.1.2.1 windows 2003 server 32 bit,sql server 2005.I have installed HFM,FDQM,ESSBASE AND Planning While I am registering the HFM application it is throwing error like Invalid or cou