Returning data in a jsp page.

Hello all! :-D
i need to build a simple web app, that retrieves data from an array list. Well my sequence is as follows:
1-JSP request:
2- Servlet:
3-Java Class
4-Back to the servlet
5- Show result in a table inside a jsp page.
How do i send the array list object into a jsp page so it shows the data in the table?
Thanks in advance!

hi,
servlet - you may use HttpSession:
example:
        ArrayList list = new ArrayList();
                  list.add("data1");
                  list.add('data2");
               session.setAttribute("lists", list);{code}
JSP:
{code}<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:forEach var="list" items="lists">
        ${list}
</c:forEach>{code}
I hope this could help
quince                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • Help fowarding data to a jsp page

    I know your not meant to double post but i was told it would be better if i post this message in here so:
    I am trying to create a bean that will connect to a database and bring back data depending on what a user typed into a html form. However i need some help, if the database does not find any data i want to send a message saying something like "no results" to a jsp page which then be displayed, if results are found i then want to pass on these results to another jsp page.
    My question is how would i pass on this data / message to a jsp page? Also if more then one piece of data is returned from the database how would i be able to make sure everything is sent to the jsp?

    In the above code a Servlet, a JavaBean, JDBC and everything else is combined into just one class. That is not how it is.
    A Servlet is a Servlet --- it is not a JavaBean ---- So create a dedicated class that is purely a Servlet and does what a Servlet is supposed to do. Taking the tutorial on Servlets will help you understand them better.
    A JavaBean is a JavaBean ---- it is not a Servlet --- Create a JavaBean class.
    Move the Database Connection code to the Data Access Layer --- this means create separate classes that are meant to only access data.
    It is better to learn each individual concept before attempting something more complex.
    Also build small code into your class, ---- understand what it's doing then compile it frequently.
    I'll give you hints on how you should properly implement an MVC pattern.
    JSP Page
    This page contains an HTML form , with form fields and a submit button.
    In the action attribute of the form you will specify the URL-pattern for the Servlet.
    The URL-pattern for the servlet will be defined in web.xml , for example
    <form action="/MyFirstServlet" method="post" >
    </form>Then create a Servlet , in its package , so for example
    com.myapp.servlet.MyFirstServlet.java
    Place the servlet file in a proper folder structure in the Java source folder.
    When the Servlet it compiled it needs to go under the corresponding folder structure under your applications /WEB-INF/classes/ folder.
    Your servlet will look something like this:
    package com.myapp.servlet.MyFirstServlet;
    //All import statements go here
    public class MyFirstServlet extends HttpServlet{
       public void doGet(HttpServletRequest request, HttpServletResponse response) throws ......... exceptions {
            doPost(request, response);
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ......... exceptions {
            //Process the request here
    request.getAttribute("someFormField");
    //similarly get all form fields
    //Store all fields into a JavaBean
    //Then call a method that saves the data to database
    saveToDatabase(pass the javabean here);
    private void saveToDatabase(SomeJavaBean someJavaBean){
        //Over here call a DataAccessObject -- DAO that saves the data
       // to the database.
    /WEB-INF/web.xml
    When you write a servlet you need to define it in web.xml and define a URL mapping also for it in web.xml
    JavaBean example
    com.myapp.beans.Person.java
    package com.myapp.beans.Person;
    //whatever import statements (if any) go here
    public class Person{
    private int age;
    private String firstName;
    public Person(){} //Every JavaBean must have a default constructor
    //Write the Getters and Setters for the private fields above.
    //in proper JavaBeans notation as follows
    public void setAge(int age){
      this.age = age;
    public int getAge(){
       return this.age;
    //Similarly write getter and setter for firstName
    }You would then use the above JavaBean to transport data between the database layer and JSP layer via the Servlet.
    If you are Saving to the Database , you read the HTML form's data and save it into one JavaBean and then pass the JavaBean to the database layer to be saved. In the Database layer you write JDBC code to save the data.
    If you are Reading from the database, you create an ArrayList of JavaBean objects in the database layer using JDBC code and then pass the ArrayList to the Servlet which stores it in the Request, then the servlet forwards control to the JSP which then reads the data from the request.
    Most of the above is pseudo code, it is just there to give you an idea about how do this properly in MVC --- you can then read tutorials on each of the above --- for example tutorial on Servlet, tutorial on JDBC, tutorial on Java Classes and then understand them more.

  • Problem in passing data from one .jsp page to another .jsp page

    i have a problem here
    Actually i have 2 jsp pages. What im trying to do here is actually i want to pass data from the first jsp page to the second for updating
    The first jsp page contains data that user wants to update in the form of table.
    <td><img src = "edit.gif" alt = "edit" border="0" ><td>
    <TD><%= Name %></td>
    <TD><%= rs.getInt("Age") %></td>
    <TD><%= rs.getString("Gender") %></td>
    So this page displays the data that users wants to update plus one image button (edit button). So when user clicks this button, all the data in this page will be brought to the second .jsp page called updatePersonal for updating.
    The problem here is that it is not displaying the existing data in the second .jsp page.
    The second page basically contains forms
    <INPUT TYPE="text" NAME="FirstName" maxlength="30" value = "<%=FirstName%>">
    Can someone please help me. I really dont know what to do..How do i get the data displayed in the text field that is passed from the first .jsp page..thankx in advance

    Please modify below code to:
    td><img src = "edit.gif" alt = "edit" border="0" ><td>
    -----------------modified code
    td><a href="updatePersonal.jsp?FirstName=<%=rs.getString(FirstName")%">&LastName=<%=rs.getString("LastName")%>&Age=<%=rs.getInt("Age")%>&Gender=<%=rs.getString("Gender")%>"><img src = "edit.gif" alt = "edit" border="0" ></a><td>
    I'm sure it works</a>

  • How can I display the date on a jsp page??

    Is there anyway to display the current date when someone views a jsp page??? Can I get it from the server or something like that?
    Thx
    Rich

    is there any type of formatting that goes witth
    that.....Most definitely -- check out the java.text.DateFormat object and its cohort java.text.SimpleDateFormat.
    For example, if you wanted to display the current date in MM/DD/YYYY format, you could do the following:
    <%-- This could go somewhere near the top of the JSP %>
    <%
    SimpleDateFormat f = new SimpleDateFormat("MM/dd/yyy");
    %>
    <% And later on, you could have... %>
    <%= f.format(new Date()); %>Note that I've omitted the proper <%import%> directives.
    -Navin

  • How to retrieve the data from a jsp page for print?

    i have a dynamic jsp file which will get the data at runtime.I have a print button in the jsp.When i chick the print button it should capture the data from the jsp and print it as LANDSCAPE mode. Now i am using Java Api for this
              Following code is a working sample which prints some data in LANDSCAPE mode..This is working fine....How can i modify this to get the data from a jsp?....I am using weblogic workshop for development
              package Awtjava;
              //working example
              import java.awt.*;
              import java.awt.print.*;
              public class testPrint implements Printable {
              private static String s[];
              private static Font f;
              private static int nLines;
              public static void main (String arg[]){
              s = new String[10];
              f = new Font("Arial", Font.PLAIN, 11);
              int i;
              s[0] = "This is a printer test";
              for (i=1; i<10; i++){
              s[i] = "The next line";
              nLines = 10;
              testPrint.printa();
              public static void printa(){
              System.out.println("public static void printa () ");
              PrinterJob pj=PrinterJob.getPrinterJob();
              Book b = new Book();;
              PageFormat pf = new PageFormat();
              pf = pj.defaultPage(pf);
              b.append(new testPrint(), pf, 2);
              pj.setPageable (b);
              try{
              if (pj.printDialog()){
              pj.print();
              catch (Exception e) { System.out.println ("Error"); }
              public int print (Graphics g1, PageFormat pf, int n){
              System.out.println("public int print");
              int x,y,i,fa,fh;
              FontMetrics fm;
              Graphics2D g = (Graphics2D) g1;
              pf.setOrientation(PageFormat.LANDSCAPE);
              fm = g.getFontMetrics (f);
              fa = fm.getMaxAscent();
              fh = fm.getHeight();
              x = (int)pf.getImageableX();
              y = (int)pf.getImageableY() + fa;
              g.setFont (f);
              g.setColor(Color.black);
              if (n==1){
              for (i=0; i<10; i++){
              g.drawString (s, x, y);
              y += fh;
              return PAGE_EXISTS;
              else {
              for (i=10;i<10; i++){
              g.drawString (s[i], x, y);
              y += fh;
              return PAGE_EXISTS;
              Hope you will reply soon...
              Thanks in advance
              Maria

    Hey, I got a doubt that who will call the print method in the same program and what about the g.drawString() it is showing any output effect. Finally how the variable n will get initializing to 0 and 1 for two times respectively. Can u please elaborate on this...

  • Posting huge data on to JSP page using JSTL tags

    Hi,
    I have one application where I have to post huge data (approximately 2000 rows of data) into JSP page. I am using JSTL tags and running on Tomcat 5.
    It is taking almost 20 to 25 seconds to load the entire page.
    Is it the optimal time to load or it could be improved?
    Please let me know.
    Thanks,
    --Subbu.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Hi Evnafets,
    Thank you for the response.
    Here are the tasks I am doing to display the data on JSP.
    0. We are running on Tomcat 5 and the memory size is 1024MB (1GB).
    1. Getting the data - I am not performing any database queries. The data is stored in the static cache memory. So the server side response is so quick - less than a milli second.
    2. Using Java beans to pass data to the presentation layer (JSP).
    3. 10 'if' conditions and 2 'for' loops and 2 'choose' statements are being used in the JSP page while displaying the data.
    4. Along with the above, there are 4 javascript files are being used.
    5. The jsp file size after rendering the data, is aprox. 160 kb
    Hope this information helps you to understand the problem.
    Thanks,
    --Subbu.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Returning Values to a JSP Page

    I have a servlet that recives data from a form using POST. Once I've processed the data I need to pass my new data (and some of the original data) to a new JSP page.
    This was originally done using response.sendRedirect with all the data held within a parameter string.
    We've now been told that we've not to pass any data via URL's, Is there a way to secruley pass data back to a jsp page.
    I thought about using:-
    protected void transferToRD(String target, HttpServlet servlet, HttpServletRequest req, HttpServletResponse res)
    try
    RequestDispatcher rd = servlet.getServletContext().getRequestDispatcher(target);
    rd.forward(req, res);
    catch (Exception exc)
    exc.printStackTrace();
    But I don;t have a servlet to pass in as a parameter
    Any help would be appreciated

    Or you can use one of these in the JSP page:
    <jsp:usebean id="var_name" class="class_name" scope="request">Only thing to remember is that if it can't find the variable name then it will call the default constructor to create a new instance, and if that doesn't exist then you will get a runtime error in your JSP page which looks pretty ugly.

  • (newbie) How to return error messages to JSP page.

    Hello,
    I'm using a very simple Model 1 architecture (no framework such as Struts used.) The webapp just consists of a login.jsp which collects database connection parameters and then activates a servlet to return a PDF report to the browser.
    I have a very common need: I would like the errors entered by the user on the login.jsp to be displayed at the top of a new return of the login.jsp (with the bottom of the JSP still providing the edit fields for reentry), errors such as:
    1.) User did not enter the username, password, and database name
    2.) Having a wrong username/password for the given database.
    (2) is more complex than (1), because it would involve feedback from the servlet (which makes the DB connection).
    I'm not sure how to code this, however, with just JSP, JSTL and JavaBeans. Does anyone know of an example with source code on the web where something similar to this is done?
    Thanks,
    Glen

    No problem on posting here. Seeing as JSP forum is not accessible, this is the next best choice.
    What sort of complexity are you after here?
    You can go with the very simple:
    Print out the error messages as you discover them.
    if (request.getParameter("username") == null){
      // print out the message
      out.println("Please enter your username");
      // or alternatively
      List errors = new ArrayList();
      errors.add("Please enter your username");
    }The best way to get feedback is to write your login method to return whether login succeeded or not. That can be a boolean true/false value, or you could return a User object to indicate success, and null to indicate failure.
    How much of the code is in servlet, how much in JSP?

  • How to retrieve data from a jsp page

    I have created a page with some text boxes, file, submit button. In my Ist jsp, i am dynamically add Text boxes and File (for Uploading).
    In the 2nd jsp, i am used Jakarata FileUpload API. I am able to retrieve all data and files except that value of dynamicall added text boxes. That is, I cannot retrieve data from dynamically added text boxes.
    Using Jakarata FileUpload API, i can retrieve values of form data using
    getString() method.
    I want to know that there is any way or method for retrieving form data values into String Array.
    regards
    madhu
    [email protected]

    Use parseRequest(request) to get the file information as you already are doing. However, I dont know how you can use request.getParameter("textField1") to get the other fields from the page. My work-around is as follows:
    Change your submit button to an ordinary button and add an onClick event to it. Then in the javascript function that supports the onClick, add the textField1 as follows:
    <form name="fileUploadForm" method="post" action="someAction" (((more code code here)))))
    function submitButtonClick(){
    document.fileUploadForm.action=
    document.fileUploadForm.action+
    "?textField1="+document.fileUploadForm.textField1.value"+
    "&textField2="+document.fileUploadForm.textField2.value"+
    "&textField3="+document.fileUploadForm.textField3.value";
    document.fileUploadForm.submit();
    As you can see in the above code, I append the textField1 name/value pair to the end of the action. Now in the server, you can use getParameter("textField1");

  • How can i display database data in my jsp page?

    actually i m doing a small appliaction of quiz test.
    where i m keeping my question and answers in the database.
    now i want to pull questions from the database and display in the jsp or html page.for each question i m having 4 options 4 them.
    like this user has to answer the question and display the resuklt in the end.
    so how can i do this?
    can i get any example or source code for this from any sites?

    I never tried this... but doesn't the normal html <applet> tag work?

  • How to get the current date using HTMLB JSP page

    Hi All, I developed an iview with several fields using PDK, I would like to know how can I include for a date field a dynamic value witch in this case is the current date.
    <hbj:inputField
    id="Date"
    type="date"
    maxlength="10"
    showHelp="TRUE"
    required="TRUE"
    value="???"
    />
    Thanks in advance
    Alexis

    Hi Alexis ,
    u can use the setDate("3.12.2003") function to set date for this input field.
    u just change the id = Date , because in jave we have Date class. rename it to another name..
    suppose id = systemDate
    <%
    Format formater = new SimpleDateFormat("dd.MM.yyyy");
    Date syDatum = new Date();
    %>
    then
    put
        systemDate.setDate(formater.format(syDatum));
    this will set the date .....
                        Regards
                        Kishor Gopinathan

  • Get the data form the jsp page

    My question is too simple that I think I don't need to explain
    <form action="test2.jsp" method="post">
    <%
    String name="";
    name = (String)request.getAttribute("names");
    out.print(name);
    %>
    <input type="submit" value="submit">
    </form>
    How can I get the value of name on the test2.jsp ???
    (I have tried many way , but they didn't work......)

    hi,
    Sample code
    test1.jsp
    <form action="test2.jsp" method="get">
    <%
    String name="xyz";
    out.print(name);
    out.println("<input type='hidden' value='"+ name +"' name='name'>");
    %>
    <input type="submit" value="submit">
    </form>
    test2.jsp
    <%   
            out.println(request.getParameter("name"));
    %>

  • Data communication between jsp pages in different context

    hi,
    I've two web applications one calling the other. The calling app needs to pass user id but not in the url
    How can this be acheived.?
    Even though i searched in several forums about forward and redirect, i donot have a clear idea.
    Please help.
    Thanks.

    Use POST. The form action URL can just point to a different context.

  • Dates in JSP page

    I have some dates fields on JSP page I want to store data in mysql databse. Can someone tell me how I can format dates as I do for other data types in servlet before I send data to add in databse: such as
    For int type data:
    String paymentID = request.getParameter("PaymentID")
    I format it like this for class Payment.
    Payment newPayment(int.parseInt(paymentID)               
    how do i work with date fields this is what I Am trying to do:
    Code patches....
    import java.text.DateFormat;\import java.text.ParseException;
    public date date1;
    try                               
          date1= format.parse(paymentStartDate);
    catch(ParseException pe)
    System.out.println("Problem found");
    ....I do not get any error but it leaves date fields empty because date1 formatting never goes to try... Always say "Problem found on console"
    Any help?

    I just realized I should post the whole file... here is code of the servlet that recieved dates from JSP and process it.
    package admin;
    import java.lang.Object.*;
    import java.text.DateFormat;
    import java.util.Date;
    import java.io.IOException;
    import java.text.ParseException;
    import data.*;
    import business.*;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class AddPaymentServlet extends HttpServlet{
         public Date date1;
         public Date date2;
        public DateFormat format;
         public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
    // Stores user entered Payment information in variables to create new Payment vector
              String paymentID = request.getParameter("paymentID");
              String clientName = request.getParameter("clientName");
             String paymentType = request.getParameter("paymentType");
              String paymentAmount = request.getParameter("paymentAmount");
             String paymentStartDate = request.getParameter("paymentStartDate");
              String paymentExpiryDate = request.getParameter("paymentExpiryDate");
              String paymentDescription = request.getParameter("paymentDescription");
              String paymentState1 = request.getParameter("paymentState"); // use String type of PaymentType
    //-----------------------------------Format dates----------------------------------------------------------          
             DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.SHORT);
           //    System.out.println("Date1--->"+date1);
                  try
                       {    date1 = format.parse(paymentStartDate);
                        //    System.out.println("Date1--->"+date1);
                     catch(ParseException ps)
                            System.out.println("can't format dates");     
                      try
                       date2 = format.parse(paymentExpiryDate);
                  catch(ParseException pe)
                       System.out.println("can't format dates");
    // get old Payment object from session
    //--------------------------------Send new PAyment Information to Vector Payment in Payment.jave-----------------------------
              Payment newPayment = new Payment(clientName,paymentType,Double.parseDouble(paymentAmount),date1,date2,paymentDescription,paymentState1);
    //------------------------------ Call PaymentDB function Add() to store new payment infomration in the databse
             PaymentDB.addRecord(newPayment);
    // over-write Payment object in session
              request.getSession().setAttribute("payment",newPayment);
              request.getSession().setAttribute("payments",PaymentDB.readRecords());
    //---------------------------------- Send results back to payment.jsp for updated information----------------------
              RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Admin/payments.jsp");
              dispatcher.forward(request, response);
         public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
              doGet(request, response);
    }

  • JSP and servlets(displaying Data On JSP page)

    Hiii all
    i am new to JSP ...also to servets
    tell me hw to print my data on the JSP page,
    i can print my data on the server,that data i want to print on JSP page
    if u all have e.g's it will be very good
    Thanks in advance
    Take Care
    Rahul :)

    What do you mean "print data on a JSP?" If you simply mean display dynamic content, you should def read up both on sun's resources and other googled resources for JSP walkthroughs...

Maybe you are looking for

  • I keep getting a message on my iPhone?

    It's really annoying me! It only started happening 2 days ago. When I plug my iPhone 4 in to charge, either through the wall or plug the USB into the laptop, I'll get the same message, " Charging is not supported with this accessory". and it'll stop

  • New WiFi behavior in OS 10.5.4

    Over the last couple of weeks or so (I guess since installing the latest system update), my MacBook Pro no longer automatically connects to the last WiFi network used when it wakes from sleep - I have to select the network manually each time. Has any

  • ADDING SOURCE SYSTEM FIELD IN MY QUERY

    HI ALL, i WANT TO DEVELOP A CUSTOM REPORT WITH SOURCE SYSTEM FIELD IN MY QUERY WHICH THE FIELD IS NOT COMING FROM THE CUBE . PLEASE COULD SOMEONE HELP ME IN THIS REGARD. MAX PTS GIVEN REGARDS, AXEL

  • RFC not found error

    Hi people, I have developed a Z RFC in R/3 system and the same is activated and used there. But when I try to use the same RFC in BW system through 'Pattern' function, it gives me as error that the Function Module not found. Do I need to create the s

  • Why can't I export from Premeier Pro CS5 to Encore CS5?

    I have edited, renderred, and attempted to export to Encore to attempt to transfer to DVD Premiere Pro CS5.5 with 5.5.2 update just downlaoded today Windows 7 64 bit Source AVCHD 1080p 25 Anamorphic Error: ..\..\src\AMEPresetProber.cpp-265 I wasa exp