0

My Struts2 web applications' index page has a two buttons as below.

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<link href="assets/css/lib/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/lib/bootstrap-responsive.min.css"
rel="stylesheet">
<link href="css/report.css" rel="stylesheet">
<title></title>
<script type="text/javascript">
function listReports() {
    var xhttp = new XMLHttpRequest();

    xhttp.open("GET", "myReportAction.action", true);
    xhttp.send();

    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            window.location = '/ReportBuilder/myreports.jsp';
        }
    }
}   
</script>
</head>

<body>
<div id="form-wrapper"
    style="text-align: center; vertical-align: middle">
    <form action="reporttype.jsp" method="post" class="row-centered">
        <button type="submit" class="btn btn-primary">Create Report</button>
    </form>
    <div>
        <button id="myReports" class='btn btn-info' onclick="listReports()">My
            Reports</button>
    </div>
</div>

Once click the My Reports button, it calls myReportAction. Here is my struts.xml file.

<action name="myReportAction" class="net.java.com.reports.MyreportsAction"
        method="execute">
        <result name="success">/myreports.jsp</result>
        <result name="error">/error.jsp</result>
    </action>

MyreportsAction.java class.

package net.java.com.reports;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;

public class MyreportsAction extends ActionSupport implements
    ServletRequestAware {
private List<String> myreports;

HttpServletRequest servletRequest = ServletActionContext.getRequest();
HttpServletResponse servletResponse = ServletActionContext.getResponse();

@Override
public String execute() throws Exception {
    myreports = new ArrayList<String>();
    Connection connection = null;
    Statement stmt = null;
    ResultSet rs = null;

    System.out.println("-------- PostgreSQL "
            + "JDBC Connection Testing ------------");

    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        return ERROR;
    }

    System.out.println("PostgreSQL JDBC Driver Registered!");
    System.out.println("Database connection established!");

    try {
        connection = DriverManager.getConnection(
                SelectAction.getDatabase(), SelectAction.getUser(),
                SelectAction.getPassword());

        if (connection != null) {
            System.out.println("Database connection established!");

            stmt = connection.createStatement();
            // creating Query String
            String query = "SELECT report_id\n" + "FROM reports\n";

            // Executing query
            rs = stmt.executeQuery(query);
            while (rs.next()) {
                myreports.add(rs.getString("report_id"));
            }
            System.out.println(myreports);
            connection.close();
            return SUCCESS;
        } else {
            System.out.println("Failed to make connection!");
            return ERROR;
        }

    } catch (SQLException e) {
        System.out.println("Connection Failed!");
        e.printStackTrace();
        return ERROR;
    }

}

@Override
public void setServletRequest(HttpServletRequest arg0) {
    // TODO Auto-generated method stub

}

public List<String> getMyreports() {
    return myreports;
}

public void setMyreports(List<String> myreports) {
    this.myreports = myreports;
}

public HttpServletResponse getServletResponse() {
    return servletResponse;
}

public void setServletResponse(HttpServletResponse servletResponse) {
    this.servletResponse = servletResponse;
}

public HttpServletRequest getServletRequest() {
    return servletRequest;
}

}

myreports.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                      "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link href="assets/css/lib/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/lib/bootstrap-responsive.min.css"
rel="stylesheet">
<link href="css/report.css" rel="stylesheet">
<title></title>
</head>
<body>
<div id="form-wrapper"
    style="text-align: center; vertical-align: middle">

    <div class="container">
        <select id="myreports" name="myreports" >
            <s:iterator value="myreports">

                <option value="<s:property />"><s:property /></option>

            </s:iterator>
        </select>

    </div>
</div>
</body>
</html>

Once click My Reports button I need to go to the myreports,jsp page and it should populate myreports drop down list. Above is the attempt that I have tried. It redirect to the myreports.jsp page but the drop down list id empty.

Any suggestions are appreciated.

Thank You

Andrea Ligios
  • 46,329
  • 24
  • 102
  • 208
Rose18
  • 2,462
  • 5
  • 39
  • 90

1 Answers1

1

There are a lot of things gone wrong.

The most important one is that you must always call an action that then renders a JSP, you should never call directly a JSP. Instead, you are calling

window.location = '/ReportBuilder/myreports.jsp';

that will open a JSP without passing through an action. And hence, without having any action data to pass to it and populate your select.

Actually, the action data is available only in the xhttp.onreadystatechange = function() { function, then you create another request and lost it.

You need to do something like window.location = "/some.action"; where some.action will load the data needed by the select and forward to your JSP, and then it will work, but since you've already called the action needed to populate the select before, the whole thing need to be rethinked.


That is the error, but after thant, here are some suggestions:

  1. Using an <s:iterator> to populate a select ? It's better to use the <s:select /> tag. It's all described in this answer that I suggest you to read, along with the question, to also understand why and how you could shape better your application's layers, instead of putting business logic in the actions, that in fact are presentational controller.

  2. Using vanilla Javascript instead of jQuery is a bad idea for beginners who are not forced by company rules to explicitly avoid jQuery. If you can use it, just use it.

  3. Take a look at the Struts2 jQuery plugin, that will allow you to use jQuery without even knowing it, by just using Struts2 tags.

  4. Use HTML5 DTD. It's backward compatible and it's way better than 4.01 that will force strange quirks on different browsers.

  5. CSSs are better than in-page <style> blocks that are better than inline styles.

  6. Changing a page to populate a select ? Isn't it better to populate a select on the same page ?

Community
  • 1
  • 1
Andrea Ligios
  • 46,329
  • 24
  • 102
  • 208