Learn JSTL

Hi,
I used to have scriptlet in jsp page and normally use System.out.println to debug any jsp problems. Now I want to change them to use JSTL. Following I am trying to output all options and make one of selected:
      <% if(myBean.getOptions() != null) {
                  List list = myBean.getOptions();
                  for (int i=0; i < list.size(); i++) {
                       HashMap map = (HashMap)list.get(i);
                       String id = (String)map.get("id");
                       String description = (String)map.get("name");
      %>
      <option value="<%= id %>" <%= MiscUtil.optionSelected(id, myBean.getBookId())%>> <%= description %></option>
      <% } } %>I made it as:
<c:if test="${myBean.options}">
     <c:forEach var="item" items="#{myBean.options.items}">
          <c:set var="id" value="${item.value.id}"/>
          <c:set var="description" value="${item.value.name}"/>
      <option value="${ id }" <c:out value="DON'T KNOW HOW TO DO THIS"/>> ${ description }</option>
      </c:forEach>
</c:if>It shows empty list and don't know how to do default "select" in option. Maybe it's quite obviously wrong but can't really figure it out. How can I debug this? Thanks

Let me see if I understand your datastructures here:
You have a List that you iterate through
Each entry in the list is a map
The map has in it keys "id" and "value" which you want to display in the dropdown box.
The MiscUtil call looks to be a static method. My guess is that it wil return "selected" if the id is the same as myBean.getBookId()?
Lets take these one at a time:
First the forEach loop, the 'items' attribute should be your list (myBean.getOptions()) which translates to ${myBean.options}
Each 'item" will then be a Map.
map.get("id") can be written as ${map['id']} or just ${map.id}
similar for map.get("name");
This leads to the following code for rendering the dropdown list:
<c:forEach var="mapItem" items="${myBean.options}">
  <c:set var="id" value="${mapItem.id}"/>
  <c:set var="description" value="${mapItem.name}"/>
  <option value="${id}" >${description}</option>
</c:forEach>Next: the selected value.
There are two ways you could do this
1 - in JSTL with an if statement
<c:if test="${id == myBean.bookId}"> selected </c:if>2 - use a JSTL custom function tag to wrap the call to MiscUtil
In a tld file:
<taglib>
<function>
  <name>optionSelected</name>
  <function-class>com.mypackage.MiscUtil</function-class>
  <function-signature>
      java.lang.String optionSelected(java.lang.String, java.lang.String)
  </function-signature>
  </function>
</taglib>You would then import that tld into your jsp page (much like you do the JSTL)
Something like:
<%@ taglib prefix="misc" uri="http://MyMiscUtil"%>
and invoke it via
${misc:optionSelected(id, myBean.bookId}
The final thing:
<c:forEach var="mapItem" items="${myBean.options}">
  <c:set var="id" value="${mapItem.id}"/>
  <c:set var="description" value="${mapItem.name}"/>
  <option value="${id}" <c:if test="${id == myBean.bookId}"> selected </c:if>>${description}</option>
</c:forEach>Cheers,
evnafets
Edit: The forum is not displaying my last code example directly. It has added an extra > character between the value="${id} and the <c:if>
I can't seem to stop it doing that, so just be careful about copying/pasting that code ;-)
Or even better, reply and then select "quote original"
That will return you an undoctored version.

Similar Messages

  • Is it worth learning JSTL?

    Hi,
    I know JSP and use it everyday.
    Now I want to generate my html pages fully with taglibs, but I wonder if it is worthwhile to learn JSTL, or just stick with Struts taglibs, or some taglibs from another MVC framework.
    What would be the advantages and disadvantages of learning JSTL?
    How does the efficiency of the JSTL is, compared to just plain JSP with scrptiles?
    TIA,
    Gabriel

    I have a slightly different take on this.
    Everyone here is a developer, and so JSTL is "easy to learn" since the concepts of control flow etc, are second nature. However, my experience is that the intended audience for JSTL (i.e. web designers, right?) rarely find it that easy. So I question the value of this standard library for all but the most technical/creative designers.
    In my personal real world, writing a tag takes less time than the discussion or design of one to meet the needs of that audience.
    In my own applications, I provide application-level custom tags designed for that specific application according to the current wants/needs of the designers. Obviously I have built up a library of generic tag code, which i extend to deliver against the latest request... usually in less than an hour.
    I don't know if you have tried to explain the concept of an iterator to a non-programmer, but in my experience it saves a lot of messing around and a lot of time-wasting "how do i" questions to give them the functionality in a way that they can understand, rather than the way dictated by concerns that they never face in the usual course of their work (not to mention the massive reduction in broken markup when things -- inevitably -- change in their design).
    A simple example:
    <table>
    <myapp:chat-list>
    <tr><td><myapp:chat-user property="username"/></td><td><myapp:chat-user property="logged-in"/></td></tr>
    </myapp:chat-list>
    </table>/k1

  • My question about JSTL

    First, sorry for not being a native English speaker.
    I started to learn JSTL for Web application a few days ago.
    Now I try to create a toy web app just to see how to use those JSTL tags.
    I created a simple web page as following:
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
        <body>
            <c:if test="${personlist==null}">
                AAA
            </c:if>
            <c:if test="${personlist!=null}">
                BBB
            </c:if>
        </body>
    </html>During the above, the personlist is the name of a object which I have not created. In my opinion, I think there should always one output when openning the page in the browser no matter the object personlist exists or not, but in fact, I was wrong, the fact is nothing displays on the screen. I don't know what's wrong. If you could give me some clue, it should be appreciated. Thank you.

    Hi your are right ,you should see AAA on your web page.
    I try it and your code is good ,i got it AAA on my web page you taglib is
    correct but it wont work if you don't put JSTL library in your project.
    So you must also add the JSTL library to the project.
    Find your JSTL 1.1 library and put it to your project.
    Try it!

  • ERRORS IN  RECOMMENDED JSTL BOOK & A BETTER TUTORIAL

    Hello,
    I think that my tutorial on JSTL in :
    http://in.geocities.com/rsramsam/jstl.htm
    is far better , hands-on and comprehensive than the recommended books by SUN.
    Some typos have been corrected in Rick's site.
    http://www.learntechnology.net
    Kindly use this tutorial on JSTL instead of the buggy and long-winding books.
    RSR

    Thoughts:
    This first link was very difficult to read.
    The second link is in a much more readable format than the first.
    The tutorial seems to cover JSTL1.0 only, and not the newer JSTL1.1 and how it integrates with JSP2.0.
    In fact the author refers to a JSP book for having an "error" using the JSTL1.1 uri, as opposed to the JSTL1.0. If you don't have that basic understanding, then you lose my vote at this point.
    Try reading
    [url http://forum.java.sun.com/thread.jspa?threadID=628740] This post and
    [url http://forum.java.sun.com/thread.jspa?threadID=629437&tstart=0] this post  on the differences between JSTL1.0 and JSTL1.1.
    It has a few good basic examples, but I don't think it is anything special.
    For really learning JSTL I would recommend getting the specification from [url http://java.sun.com/products/jsp/jstl/index.jsp] here 
    It is quite readable and an excellent reference on how the tags actually work
    Cheers,
    evnafets

  • Java code vrs JSTL

    I'm beginning to study jsp I have a knowledge in the Java language, let me know if you need to learn JSTL for JSP pages or just know java
    is more easy for me make the JSP page with java code. thanks for you answers

    981159 wrote:
    so I'm making a mistake when I'm studying JSP JSF should study?It's difficult to say if you are or not. It used to be a common question in enterprise architecture exams. When do you use JSP vs using JSF.
    These days the emphasis is on ease of development with many frameworks striving to solve as many common developer problems as they can so you can concentrate on writing only the business logic for your project. With plain JSPs you need to handle many cross cutting concerns yourself and develop filters and application controllers to deal with those concerns (otherwise you reuse by copy paste!). Because JSF (and many other frameworks) is a full MVC framework they already provide all those filters and application controllers while also improving the view with components, validation, templating and asynchronous request processing. Perhaps there are applications out there that don't need any of these, if they exist then those are the applications one could consider using plain JSPs for. It would be a shame if a developer has to take time from writing and testing business logic to developing functionality already made available by most frameworks. Also the arrival of Play! and other stateless MVC frameworks makes it even less likely that you'll find an application where an honest architecture choice process will pick JSP as most applicable.
    But your question is should you learn it? Well, there are lots of companies in the industry that have systems that use JSPs either alone or with other frameworks. Not only that but some of those companies have not changed their architecture choices to move away from it for various plausible reasons. Then there is products developed using JSP based technologies like Oracle ADF which uses JSF 1.2 (which used JSPs). If you intend to work for those companies or with those products at some point then you'll have to learn it to be most effective at your job. My suggestion was not necessarily to stop learning it, but to be aware of where JSPs stand in relation to other technologies.

  • Can't access requestScope attributes jstl?

    Hi,
    I'm just learning jstl, and trying a simple thing:
    A servlet creates an ArrayList, places it in the request and forwards to a jsp:
    request.setAttribute("list", list);
    request.getRequestDispatcher("admin.jsp").forward(request, response);Then in admin.jsp i try to access it, but I get no data at all.
    <c:forEach items="${requestScope.list}" var="obj">
         <c:out value="${obj.data}"/>
    </c:forEach>I tried the exact same operation with scriptlet and it worked fine, so the list is there. I have no idea why this isn't working.
    Any help is appreciated. Let me know if you need more info.

    Thanks, that makes sense!
    web.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
        version="2.5">jstl declaration in jsp:
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> Now, for development I am just using the built in J2EE preview server in eclipse. I'm not exactly sure about the details, so I guess that could be the problem! Maybe I need to add the jstl.jar and standard.jar on the server as well?
    I will try it soon.
    Thanks for your input!

  • Passing values from a jsp to a servlet

    I have a jsp which has a search form for customers, first it lets you search by colour, giving options of red, white or all, then gives three options of what price. Im trying to get my servlet to read these choices, and display the results. I have a statement in my serlvet which says:
    String price = request.getParameter("search preference colour");
    and the statment in the JSP is:
    <select name="search preference colour">
    <option value="Red">red</option>
    <option value="White">White</option>
    <option value="All">All</option>
    </select>
    I need to know how to define which option has been chosen, and have the chosen results displayed. I tried an 'if' statement but it didnt seem to work. Thanks

    yuvi wrote:
    i have a servlet from which i am passing result set values to a jsp page.Basically they are database records from a table named basic.
    and these selective fields have to be dissplayed on jsp.i have tried incorporating values into session variables and using them on jsp.it works fine for single record but when there are multiple results it fails!! :(Learn JSTL and use tags. Scriptlet code in JSPs is a bad idea.
    %

  • How often do I need to create a connection to DB ?

    Hello all, I am developing a site and my "Statement statement" line is bringing up an error when the program runs. My index.jsp contains a form for a username and password, it also has a <%@ include file="DBconn.jsp" %> statement for the connection to the DB
    DBconn.jsp contains:
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn =
    DriverManager.getConnection("jdbc:oracle:thin:etc etc
    I know I am getting connected because the above code displays a "connection established" message with a slight addition to the coding.
    The next JSP to load (Login.jsp) takes the username and password variable from the index.jsp form and tries to authenticate the user details with what is in the database. The next line in Login.jsp is causing a problem:
    Statement statement = conn.createStatement();
    I get an error that "conn cannot be resolved".
    Is that because the object conn was created in the DBconn file and is not accessible from Login.jsp ?? Is it a scope issue ?
    All subsequent pages will be accessing the database, what is the best structure of a jsp to retrieve and write data, I mean, do I have to connect to the database from scratch, run my query then disconnect from the database for every database action that I run ??
    Thanks
    Kevin

    Hello all, I am developing a site and my "Statement
    statement" line is bringing up an error when the
    program runs. My index.jsp contains a form for a
    username and password, it also has a <%@ include
    file="DBconn.jsp" %> statement for the connection to
    the DBI would not recommend any of this.
    If you absolutely must write SQL code in a JSP, please do yourself a favor and learn JSTL and its <sql> tags. There is no reason God's green earth for you to write scriplet code like this.
    The real solution is to move that code out of JSPs and into Java objects that run on the server side.
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn =
    riverManager.getConnection("jdbc:oracle:thin:etc etc
    I know I am getting connected because the above code
    displays a "connection established" message with a
    slight addition to the coding.
    The next JSP to load (Login.jsp) takes the username
    and password variable from the index.jsp form and
    tries to authenticate the user details with what is
    in the database. The next line in Login.jsp is
    causing a problem:
    Statement statement = conn.createStatement();Where's that connection coming from? The previous page? The second page has no knowledge at all about the first page. (That's how HTTP works.) If you need to make an object available to another page, you have to add it as an attribute at request/session/application scope.
    Is that because the object conn was created in the
    DBconn file and is not accessible from Login.jsp ??
    Is it a scope issue ?Yes and yes.
    All subsequent pages will be accessing the database,
    what is the best structure of a jsp to retrieve and
    write data, I mean, do I have to connect to the
    database from scratch, run my query then disconnect
    from the database for every database action that I
    run ??Yes. You'll get higher throughput that way. And it shouldn't be done in JSPs.
    Now you'll have another legitimate concern: The expense of opening and closing those connections. The proper thing to do is NOT to get a Connection from the DriverManager. Set up a connection pool and do a JNDI lookup to get it.
    %

  • Sql database connection in jsp

    Hi,
    I am new to java.
    I know how to connect the database in the java using the javacodings [jdbc] but i am don't know how to connect the database using the jsp.
    Is it easy. If so, can any one help me in this regards.
    Any sample codes or white paper available.
    thanks in advance,
    Regards,
    sa

    Hi,
    Here's a simple application i write to test JSTL.
    Using JSTL is easier.
    Create a directory named tests in your webapps tomcat directoty.
    In this, create a web-inf dir and inside a lib dir.
    Copy JSTL.JAR ans STANDARD.JAR in tests/web-inf/lib/ which are lib for JSTL (found on apache foundation web site, jakarta implementation).
    Copy you jdbc driver in jakarta-tomcat/common/lib dir.
    Here is a file to input some data from an HTML form:
    Create saisie.jsp and record.jsp in you tests apps dir.
    saisie.jsp:
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    <html>
    <head>
    <title>Simple Example</title>
    </head>
    <body>
        <h1> Saisie de donn�es  </h1>
        <form name="saisie" action="record.jsp" method="get">
            Code :<input type="text" name="code"/>
            Text :<input type="text" name="text"/>
            <input type="submit" name="submit"/>
        </form>
    </body>
    </html>and record.jsp:
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <%@ page isELIgnored ="false" %>
    <html>
    <head>
    <title>Simple Example</title>
    </head>
    <body>
    <sql:query var="result"  maxRows="100">
         select * from ess
    </sql:query>
    <table>
         <!-- Affichage de l'ent�te avec le nom des colonnes -->
         <tr>
         <c:forEach var="name" items="${result.columnNames}">
              <th>${name}</th>
         </c:forEach>
         </tr>
         <!-- Affichage des donn�es avec 'rowsByIndex' -->
         <c:forEach var="ligne" items="${result.rowsByIndex}">
         <tr>
              <c:forEach var="valeur" items="${ligne}">
                   <td>${valeur}</td>
              </c:forEach>
         </tr>
         </c:forEach>
    </table>
    <c:set var="code_id" value="${param.code}"/>
    <sql:update>
        INSERT INTO ESS (ID,TEXT) VALUES (?,?)
        <sql:param>${param.code} </sql:param>
        <sql:param>${param.text}</sql:param>
    </sql:update>
    </body>
    </html>Here's web.xml file to create in tests/web-inf dir:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE web-app
        PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
        <description>Learning JSTL (or whatever you like</description>
        <context-param>
              <param-name>javax.servlet.jsp.jstl.sql.dataSource</param-name>
              <param-value>jdbc:postgresql://127.0.0.1/gihe,org.postgresql.Driver,gihe,****<param-value>
         </context-param> 
    </web-app>web.xml contains the datasource definition, the jdbc driver, the url, user and password.
    saisie.jsp is a standard html file.
    record.jsp use web.xml datasource to connect to the database and use JSTL tag to insert some data.
    more explanations on java sun site.

  • JSP newbie.  Strange classnotfoundexception

    I have recently started writing JSPs. I am an experienced Java programmer, but have not ventured into JSPs until just now.
    While writing some test JSPs, I have run into a big problem that I cannot seem to resolve.
    While attempting to run my JSP from IE, tomcat throws the following exception in the console window: java.lang.ClassNotFoundException: RTSite
    Also, unless I change the SITES_FN to "C:\\sites.dat" and place the sites.dat file in C:\, it tells me it cannot find the file. For example, if I change SITES_FN to simply "sites.dat" and place sites.dat in the C:\tomcat_5.5\webapps\ROOT directory alongside my outages.jsp file, it tells me it can't find it!
    How on earth do I fix this? What am I doing wrong?
    Here is my JSP:
    ===================================
    <%@page import="java.util.*,java.io.*,test.RTSite"%>
    <HTML>
    <BODY>
    <%!
         String SITES_FN = "C:\\sites.dat";
         String OUTAGES_FN = "outages.dat";
         String OUTAGES_TXT_FN = "outages.txt";
         boolean eof = false;
         RTSite site;
         //site = new RTSite("http://www.georgianavigator.com/perl/trips", "ATL", "Atlanta", "GA");
    %>
    <%
         site = new RTSite("http://www.georgianavigator.com/perl/trips", "ATL", "Atlanta", "GA");
         out.println(site.getName());     
         try
              FileInputStream in = new FileInputStream(SITES_FN);
              ObjectInputStream s = new ObjectInputStream(in);
              while (!eof)
                   try
                        site = (RTSite)s.readObject();
                        out.println("TEST" + site.getCode());
                   catch (EOFException ex)
                        eof = true;
              //s.close();
              //in.close();
         catch (Exception ex)
              out.println(ex.getMessage());
              System.out.println("=====");
              ex.printStackTrace();
    %>
    </BODY>
    </HTML>
    ===========================================
    Here is my directory structure:
    C:\tomcat_5.5
    +-----webapps
    -------+----ROOT
    -------------+----outages.jsp
    -------------+----sites.dat
    -------------+----WEB-INF
    -------------------+----classes
    --------------------------+----test
    --------------------------------+----RTSite.class                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Too many things to count.
    "ClassNotFoundException" isn't strange. Sounds like you didn't deploy your Web app properly.
    Is RTSite a class that you wrote? Where is the .class file located? (Hint: Should be in the WEB-INF/classes directory for your Web app, in its package directory structure.)
    Tomcat won't deal with any servlets or Beans that aren't in a package. If you aren't using packages, you'd better start.
    You should not be putting your app in /ROOT. Learn how to deploy Web apps to Tomcat properly. The Tomcat site has "Your First Web App" to show you how.
    You shouldn't have scriptlet code in a JSP like that. Better to learn JSTL.
    Your Web app should be self-contained. I'd expect to see everything I needed within the Web context. Tossing files like that site.dat just anywhere in the file system is a bad idea.
    The JSP is compiled to a servlet and run on the host server. I'll assume that you know this, and will place that sites.dat file accordingly.
    I'd always prefer a relational database to a static text file in the file system, but that's just me.
    That's enough for now.
    %

  • % if () {%   %} if() {% %}% Why  does Error occur?

    Hi,
    can somebody help me to understand why does error occur in this example?
    <% if (k.equals("1")) {%>
    html tags
    <%}
    if (k.equals("2")) {%>
    html tags
    <%}%>
    If there is only one condition it works, but if tere are two, the second condition lead to the error on server.
    Thanks and Best Regards,
    sergey

    that's some ugly, hard to read scriptlet code. Go learn JSTL right away.
    Impossible to tell from what you've posted. Maybe the variable k isn't in scope for both or something like that.
    Your HTML tags might be wrong, too. Who knows? You've posted so little...

  • DAS Can't connect to mySQL ODBC

    Using:<BR>HPS 8.3<BR>Sun Solaris 8<BR>I've created a BQY in Intelligence Explorer that connects using mySQL ODBC in Windows XP and wanted to publish it to the web, but I needed to publish the OCE to the server and set it up with DAS.<BR><BR>Here are the steps I took<BR>1. Installed the mysql connector odbc 3.51.12 sun solaris2.8 sparc 64bit ODBC in Solaris.<BR>2. Created an odbc.ini file in Solaris with my mySQL connection settings in the home directory of the user running the services. I even made a copy of it in the $BP_HOME directory.<BR>3. Added the library path for my ODBC library to all my scripts.<BR>4. Added the data source using the service config tool.<BR>5. Restarted services<BR>6. published the OCE and BQY<BR><BR>When I access the BQY using the plug-in, it gives me <BR>"Server Error [2009]; Internal Error Detected in Data Access Service"<BR><BR>When I access it using the thin-client (iHTML), it gives me:<BR>"An Intelligence Service error has occurred.-Failed to acquire requested service"<BR><BR>What else needs to be done?<BR>I tried some the other suggestions to no avail:<BR>--added the library path  to the LD_PRELOAD variable in the $BP_HOME/bin/services.sh script<BR><BR>Also, I noticed that when I ran ServiceConfig.sh, there were no data sources to pick from the dropdown.  Anyone know how to make that active so I can just PICK the connection to use?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    I'd strongly recommend that you take all that JDBC code out of your JSP. Put it into a class that you can test on the command line. Once you have it working, you can use it to get at data and pass it along to your JSP for display.
    I'd also recommend that you not use scriptlets and learn JSTL right away. MVC separation suggests that putting Java code in a JSP is a very bad idea.
    %

  • Eliminate Scriptlet condtions in JSP

    I have a Servlet that checks for information and if there is an issue it forwards the message to presentation page (JSP). Now I want to stop using conditions in scriptlets in the JSP. Please advise how I can do it in this situation in my Tomcat 4.1.27 container:
    Servlet that forwards to JSP:
    String gotopage = "";
    if(mydata == 1)
         gotopage = /"pager.jsp?mymessage=err";
    else if(mydata == 34
       gotopage = /"pager.jsp?mymessage=duper";
    else
        gotopage = /"pager.jsp?mymessage=proc";
    RequestDispatcher dispatcher =
      getServletContext().getRequestDispatcher(gotopage);     
    dispatcher.forward(request, response);
    ...JSP
    <%
    String mymessage = request.getParameter("mymessage")
    if(mymessage.equals("err"))
         out.println("Error on the page");
    else if(mymessage.equals("dup"))
         out.println("Duplicate issue.");
    else if(mymessage.equals("proc"))
         out.println("Process message issue");
    %>I was thinking maybe a bean or regular Java class to handle this but not sure how. Here would be my method in a Java class:
    public void getMessage(String msg)
         if(msg.equals("err"))
             out.println("Error on the page");
    }Then I would put the method in a bean or what in JSP?
    The Servlet would stay the same?

    Put it in a bean or learn JSTL.
    OR you could just put the message you want to display into page scope and have the JSP display it. Since the servlet already knows which page it's sending, let it figure out what the message should be, too.
    no need for all that logic in the page.
    do learn JSTL. Scriptlet code is very bad for maintenance.
    %

  • How to display my ResultSet in a JSP??

    First off, I'm new to Java programming.
    Here's my problem. I have a set of users in my database. I'd like to retrieve all the user ID's (these are integers) from my User-table and display them in a JSP. Now, I realize that my coding below isn't very efficient as it's not exactly a MVC approach. I'm just trying to learn what a ResultSet is and how to manipulate it.
    I send my ResultSet to a JSP by "request.setAttribute("usersId", usersId);" but then I'm not sure what to do in my JSP to actually display my User ID's.
    My code:
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    try {
    String dbURL = "jdbc:mysql://localhost:3306/heading360";
    String username = "root";
    String password = "";
    Connection connection = (Connection) DriverManager.getConnection(
    dbURL, username, password);
    Statement statement = (Statement) connection.createStatement();
    ResultSet userId = (ResultSet) statement.executeQuery("SELECT UserId FROM User");
    request.setAttribute("userId", userId);
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/testUserId.jsp");
    dispatcher.forward(request, response);
    catch (SQLException e) {
    for (Throwable t : e)
    t.printStackTrace();
    }

    flukyspore wrote:
    OK thanks for the quick response.
    I am using using JSP EL to write my JSP's. Still learning JSTL.Bad idea. Learn JSTL.
    I understand everything you're saying, except I can't seem to find the exact approach to load my ResultSet into an object or collection. Could you give me an example of how to do that. My ResultSet is one column of User ID's, they are integers. Something like this:
    private static final String FIND_USER_ID_SQL = "SELECT USER_ID FROM USERS";
    private Connection connection;
    public List<Integer> findUserIds()
        List<Integet> userIds = new ArrayList<Integer>();
        Statement stmt = null;
        ResultSet rs = null;
        try
            stmt = connection.createStatement(sql);
            rs = stmt.executeQuery();
            while (rs.next())
                userIds.add(rs.getInt("USER_ID"));
        catch (SQLException e)
            e.printStackTrace();
        finally
            close(rs);
            close(stmt);
        return userIds;
    }Fill in the blanks.
    %

  • Is my computer too slow?

    Hey all
    I'm running Windows XP (sp2) on a intel celeron 1.2 ghz with 256 mb ram Dell stationary computer. I have set up a JSP/MySQL connection at work on a fast computer and know my way around stuff, but at home I when I use my Dell computer I constantly get this error report when I try to read from a single SQL table:
    javax.servlet.ServletException: Communications link failure due to underlying exception:
    ** BEGIN NESTED EXCEPTION **
    java.io.EOFException
    STACKTRACE:
    java.io.EOFException
         at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1903)
         at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:483)
         at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:965)...
    Last packet sent to the server was 63 ms ago.
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:848)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:781)
    com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
    ** BEGIN NESTED EXCEPTION **
    java.io.EOFException
    STACKTRACE:
    java.io.EOFException
         at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1903)
         at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:483)
    I've tried changing to different Connector/J versions but without avail, should I consider getting a faster computer to get it to work or do you think that it only is a software issue? I'm not running any other programs than Firefox and Tomcat along with JRE 1.5.0 when I try to connect to the database. As I earlier mentioned I've got this exact code along working fine at work, that's why I figure that it might be that my computer isn't up to par.
    Here's an excerpt from my get.jsp file that tries to read from the SQL database:
    </p>
              <%      String moviename;
                   Class.forName("org.gjt.mm.mysql.Driver").newInstance();
                   Connection visaConn = DriverManager.getConnection("jdbc:mysql://localhost:8080/test", "root", "*");
                   Statement visaStmt = visaConn.createStatement();
                   String visaQr = "SELECT * FROM movies";
                   ResultSet rslt = visaStmt.executeQuery(visaQr);
                   while(rslt.next())
                        moviename = rslt.getString("*");
                        out.println("Personnummer: <b>" + moviename + "</b><br/>");
                   rslt.close();
                   visaStmt.close();
                   visaConn.close(); %>

    What makes you think it's a hardware problem?
    This is not the code that's "working" somewhere else.
    I'll also question your statement "know my way around stuff". It's not apparent from your code.
    Look at the URL you use to connect to MySQL. Your host is "localhost" and your port is - 8080? That's the port that Tomcat listens on, not MySQL. The default MySQL port is 3306.
    In general, I object to putting scriptlet code in JSPs. If you must do database calls, I'd recommend learning JSTL. Better yet, move that code into an object that you can test without requiring a container. Have it working 100% and then get your JSP to call it.
    What if your result set or statement throw an exception when you close them? Your connection will never be closed, and your application will eventually exhaust the available connections.
    No connection pool? Your app won't scale very well.
    %

Maybe you are looking for

  • Creating user defined table in SBO-COMMON

    Hello experts, I'd like to create a user defined table in SBO-COMMON. I'll tell you why: I have successfully created a SAP B1 addon which adds freight costs to an order if the total amount is under a certain threshold. We have 2 administrations runni

  • Text Modules translation to logon language in Smartforms

    I have created a text module and included it in my smartform. Now what i want is to translate the form as well as the text module in the Logon language. In the general attributes for the smartform i have already selected Translate-> To all languages.

  • Safari can't browse to secure site

    We have an application that we are trying to access with Safari on the iPad and the iPhone. When browsing to the page, we get an error message. The site we are trying to get to is www.mainport.org Cannot Open Page Safari cannot open the page because

  • After updating firefox it will not startup. norton shows that update.exe is safe??????

    If i click on the popup window for norton i can delete the files in the "0" folder under mozilla-updates folder and firefox will work until it updates itself again. then the process starts over. What can i do to fix this? Without deleting the file, F

  • Need serious Help-Mail

    Hi all, Mail has gone crazy, cannot login to my original account, 1st .mac temporary account disappeared - now I'm - [email protected] -- keeps asking for password & refuses to send emails..incoming are ok...(elmac2)..L