0

I am working on a sports-betting website. I have a program that fetches sports data and writes/updates a MySQL db. This program stays running on my local PC, where the DB is also located.

In order to retrieve the data, the client (the web browser) creates a new "bean" object. The bean's constructor is to populate some HashMaps with values queried from the DB. Then, the JSP iterates through the bean's HashMaps and displays the content. Here is what the code looks like:

            <%
                Bean m = new Bean();
            %>

            <table style="width: 100%">
                <tr>
                    <th colspan="2" align="center">NBA</th>
                </tr>
            </table>



            <% //Iterates through the NBA hashmap
                Iterator itrNba = m.getNbaM().entrySet().iterator();
                for (Map.Entry<Integer, Match> entry : m.getNbaM().entrySet()) {
                    Match value = entry.getValue();
            %>



            <div class="bs-example"> // Creates a table row for every Match object in the hashmap, and outputs its values
                <table>
                    <col width="100">
                    <col width="20">
                    <col width="100">

                    <tr>
                        <td align="left"><%=value.getTeam0Name()%></td>
                        <%
                            if (value.getStatus() != 0) {
                        %>
                        <td align="center"><%=value.getTeam0Score()%></td>
                        <td align="right" rowspan="2"><%=value.getQuarter()%></td>
                        <%
                            } else {
                        %>

                        <td align="center"></td>
                        <td align="right" rowspan="2"><%=value.getQuarter()%></td>
                        <%
                            }
                        %>

                    </tr>
                    <tr>
                        <td align="left"><%=value.getTeam1Name()%></td>
                        <%
                            if (value.getStatus() != 0) {
                        %>
                        <td align="center"><%=value.getTeam1Score()%></td>
                        <%
                            }
                        %>

                </table>
            </div>
            <br>

            <%
                }
            %>

However, I haven't found a simple way to allow my values to refresh. My really simple temporary fix was to just refresh the whole page every X seconds, and then scroll down to where the user previously was viewing. A new bean is created, causing it to read from the DB again. However, this is an approach that is beyond ugly.

Is there a simple way for just the values to refresh? I realize that I may have to look into jQuery and servlets etc, which I am willing to do. However, I would like to stay away from JSON, JS, and lots of client side scripting. Id prefer to stick with JSP or a servlet which has a doPost that prints out html code, but how can I make this loop periodically?

Thanks.

Allen
  • 1
  • 2
  • unless you use js and ajax, there is no way to refresh just one part of a page. so yes, you're going to have some client-side scripting. – Marc B Dec 08 '14 at 20:39
  • Thanks Marc. Using JS and ajax, what would a sample implementation look like? Can this all be done client sided, or will I need additional server-side logic? – Allen Dec 08 '14 at 20:40
  • Would I basically be writing the whole "bean" object part in Javascript? Use javascript to access DB and construct the "bean" model? – Allen Dec 08 '14 at 20:42
  • you'd need server-side logic to serve up the content for whatever bits needs to be replaced. If they all update at the same time, then you can have ONE ajax request send over all of the new data at once then a bit of JS to break it apart and update the various areas as appropriate. – Marc B Dec 08 '14 at 20:42
  • @Allen you can create a webservice using java on your server and consume the webservice via jquery ajax client side then there would be no need to refresh page you could update elements using javascript or jquery – brso05 Dec 08 '14 at 20:45
  • @Allen look at jersey api for creating a restful webservice then look at jquery.ajax tutorials it isn't to hard it may take a little time to get everything setup but if you look at other examples hopefully you can figure it out and if you have specific questions or get stuck just post another question on so – brso05 Dec 08 '14 at 20:47
  • @brso05 so some kind of servlet that ajax can call which will return the newest values? – Allen Dec 08 '14 at 20:47
  • @Allen yes sortof - javascript views data in JSON format so you can use jersey libraries to serve up your data in JSON format. Jersey allows you to create a method in java for a get or post request then that method can return a java object and jersey can automatically create the json from the returned object. Then in jquery you can call that url passing parameters or whatever and get the returned json. Then you can use the returned data to update your html fields. – brso05 Dec 08 '14 at 20:50
  • @brso05 thanks, I'll look into jersey API – Allen Dec 08 '14 at 20:53
  • @Allen i posted a simple example of webservice in java and jquery ajax call there is a little more to it than I posted like web.xml configuration but you should be able to find tutorials online... – brso05 Dec 08 '14 at 20:55
  • @brso05 thanks a lot man, I appreciate it. I'm sure it will take me some time to get familiar with jQuery and Ajax, and the whole Jersey framework – Allen Dec 08 '14 at 20:59
  • @Allen your welcome...and yes it will take probably a couple days of work to get familiar but once you do it will open up a lot of possibilities for you in the future. – brso05 Dec 08 '14 at 21:01
  • Can use first answer on this : http://stackoverflow.com/questions/11306000/how-to-show-value-from-database-to-jsp-without-refreshing-the-page-using-ajax/11306701#11306701 – Ars Dec 09 '14 at 10:02
  • @brso05 It worked!! My page can refresh values from DB without reloading, and it is very smooth as you said. I wrote a webservice to deliver a json output, and i configured my project to consume it. Thank you very much once again! – Allen Dec 09 '14 at 13:40
  • @Allen your welcome! I'm glad you got it to work! – brso05 Dec 09 '14 at 13:41

1 Answers1

0

Here is a very basic example of a webservice and a ajax call. You would need to configure your web.xml for the webservice to work. There are tutorial online just look up jersey rest api and jquery.ajax calls.

Java code:

@Path("/sports")
public class Sports {
    @GET
    @Produces({MediaType.APPLICATION_JSON}) **//Notice it will automatically create the JSON for you**
    @Path("/getPlayer")
    public PlayerInfo getPlayerInfo(@QueryParam("player") String player) {
    PlayerInfo playerInfo = null;
    if(player == null)
    {
        player = "";
    }
    if(player.equalsIgnoreCase("Michael Jordan"))
    {
        playerInfo = new PlayerInfo("Basketball", "Bulls", 50);
    }
    else if(player.equalsIgnoreCase("Bo Jackson"))
    {
        playerInfo = new PlayerInfo("Football/Baseball", "Raiders/Royals", 52);
    }
    else
    {
        playerInfo = new PlayerInfo("No Data.", "No Data.", -1);
    }
    return playerInfo;
    }
}

JQuery Code:

function updatePlayer()
{
    var player = document.getElementById("athleteSelect").options[document.getElementById("athleteSelect").selectedIndex].innerHTML;
    $.ajax({type: "GET", url: ("http://localhost:8080/SportsWebService/sports/getPlayer?player=" + player), data: { get_param: 'value' }, dataType: 'json', success: function (data) {
    document.getElementById("playerInfoDisplay").innerHTML = ("Sport: " + data.sport + "<br/> Team: " + data.team + "<br/> Age: " + data.age);}});
}

Jersey configuration in web.xml(you will need jersey libraries Jersey 1.18):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
<display-name>WebServices</display-name>
<servlet>
        <servlet-name>Sports Service</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <!-- Register resources and providers under my.package. -->
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.yourpackage.yourpackage</param-value>
        </init-param>

        <!-- Enable Tracing support. -->
        <init-param>
            <param-name>jersey.config.server.tracing</param-name>
            <param-value>ALL</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Sports Service</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>

HTML script tag link for jquery:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" ></script>
brso05
  • 13,142
  • 2
  • 21
  • 40
  • thanks for the example, it is fairly simple and easy to understand. Does this include any Jersey methods, or is it plain jQuery and java? – Allen Dec 08 '14 at 21:13
  • The code itself is just java and jquery java imports are from `javax.ws.rs`. Getting the server to serve up the webservice is where jersey comes into play I will post an example of the web.xml. You will need the jersey libraries included on your server(tomcat) or whatever or in your project itself. You will also need the jquery libraries in your client application I'll show example of linking script tag to jquery library you can also put it in your application so you aren't linking externally. – brso05 Dec 08 '14 at 21:19
  • thanks for the detailed answers everytime. look forward to the web.xml example! – Allen Dec 08 '14 at 21:25
  • @Allen I posted the web.xml and the script tag link. I want to note that you should host the client application and the webservice application on the same server or even just make them into one application. If you host a webservice on one server and access using jquery ajax on another server you will run into cross domain problems if you don't use jsonp or cors or something which is more advanced than you should need. – brso05 Dec 08 '14 at 21:28
  • @Allen note this configuration is for Jersey 1.18 so you should use that version if you want it to work with this code. If you get a newer or older version the configuration could be different but you would just need to do some research online how to configure it... – brso05 Dec 08 '14 at 21:31
  • @Allen I would start with a small example like this so you get an understanding for how it works and then try to integrate it into your project. Just get a working webservice(you can test by entering webservice url in browser) then try access the webservice in a simple html page using jquery when you have that down then try implementing in your current project. – brso05 Dec 08 '14 at 21:33
  • thanks for the tips. you are right in that I will start with a very small example to just see how it works, before I attempt to integrate it into my project. for now, I downloaded an example project from http://coenraets.org/blog/2011/12/restful-services-with-jquery-and-java-using-jax-rs-and-jersey/. Youve been very helpful so far and it will be a while before I can absorb all your teachings. I wanna keep you updated on my progress! Is there any other way I can contact you? – Allen Dec 08 '14 at 21:36
  • @Allen your welcome I know it can seem overwhelming at first but it's really not that bad it sounds like you already know java so the webservice part shouldn't be to hard for you and the jquery part is pretty simple to. The nice thing about using webservices with ajax is your applications will be extremely fast compared to refreshing the entire page. This way you don't have to re-create all the html elements for a page refresh. You can just update the ones you have already created no need to refresh the page. You should notice a huge difference in speed. – brso05 Dec 08 '14 at 21:40