LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 02-05-2018, 11:17 AM   #1
mfoley
Senior Member
 
Registered: Oct 2008
Location: Columbus, Ohio USA
Distribution: Slackware
Posts: 2,564

Rep: Reputation: 177Reputation: 177
How to reference "global" variable in java function


I have a function, referenced by numerous other programs, whose parameters are not able to be changed:
Code:
static void reportDetail(Statement stmt, BufferedWriter outFile, String detailColumn) throws Exception
However, the body of the function is defined locally in any given program. What I need to do in one particular program is reference a string defined in the main program, e.g.:

String localVar = globalVar;

where globalVar is defined outside the scope of reportDetail().

Is there a way to do this? (this is jsp BTW)

To be specific, I need a way of getting the UserAgent string: (request.getHeader( "User-Agent" ), in a function without passing it as a function parameter.

Last edited by mfoley; 02-05-2018 at 11:34 AM.
 
Old 02-05-2018, 12:13 PM   #2
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 11,235

Rep: Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320
The method is static! Just add the user agent to its class as a static variable.

Code:
class ReportDetail implements IReportDetail
{
    @Override
    public static void reportDetail(Statement stmt, BufferedWriter outFile, String detailColumn) throws Exception
    {
        System.out.println(userAgent);
    }

    public static string userAgent;

public class Main
{
    public static void main(String[] args)
    {
        ReportDetail.userAgent = request.getHeader("User-Agent");
        ReportDetail.reportDetail(/* parameters go here */);
    }
}

Last edited by dugan; 02-05-2018 at 01:35 PM.
 
1 members found this post helpful.
Old 02-05-2018, 03:38 PM   #3
mfoley
Senior Member
 
Registered: Oct 2008
Location: Columbus, Ohio USA
Distribution: Slackware
Posts: 2,564

Original Poster
Rep: Reputation: 177Reputation: 177
Not sure if I did it right:
Code:
IReportDetail cannot be resolved to a type
455: 
456: //HttpSession sessionObject = session;
457: 
458: class ReportDetail implements IReportDetail
459: {
460:     @Override
461: public static void reportDetail(Statement stmt, BufferedWriter outFile, String detailColumn) throws Exception

An error occurred at line: [461] in the jsp file: [/printAPchecks.jsp]
The method reportDetail cannot be declared static; static methods can only be declared in a static or top level type
458: class ReportDetail implements IReportDetail
459: {
460:     @Override
461: public static void reportDetail(Statement stmt, BufferedWriter outFile, String detailColumn) throws Exception
462: {
463:     ResultSet rs = null;
464:     SimpleDateFormat mmddyyyy = new SimpleDateFormat("MM/dd/yyyy");

An error occurred at line: [461] in the jsp file: [/printAPchecks.jsp]
The method reportDetail(Statement, BufferedWriter, String) of type printAPchecks_jsp.ReportDetail must override or implement a supertype method
458: class ReportDetail implements IReportDetail
459: {
460:     @Override
461: public static void reportDetail(Statement stmt, BufferedWriter outFile, String detailColumn) throws Exception
462: {
463:     ResultSet rs = null;
464:     SimpleDateFormat mmddyyyy = new SimpleDateFormat("MM/dd/yyyy");


An error occurred at line: [133] in the jsp file: [/include/pdfMerge.inc]
The method reportDetail(Statement, BufferedWriter, String) is undefined for the type printAPchecks_jsp
130: 
131: 	// Optionally call reportDetail() function to create detail lines on the page
132: 
133: 	if (stmt != null) reportDetail(stmt,outFile,rs.getString(detailColumn)); // note, need maxDetailLines/page
134: 
135: 	outFile.write("<div style=\"page-break-before:always\"></div>\n");
136:     }
Is your example missing a '}'? I've added one after "public static string userAgent;".

This whole thing may not work with jsp per the error at 461. I don't believe JSP has the ability to create classes outside of main.
 
Old 02-05-2018, 03:46 PM   #4
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 11,235

Rep: Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320
Quote:
Originally Posted by mfoley View Post
Is your example missing a '}'?
Might well be. I wrote it to get the architectural idea across, not to be compileable (and I did not try to compile it).

Note that "IReportDetail" was a placeholder for the name of the superclass that contains the reportDetail method. You did not name it, and it wasn't in your code sample, so I could not use its actual name in my reply. If you're pasting "IReportDetail" into your actual code, you've misunderstood the recommendation.

Last edited by dugan; 02-05-2018 at 03:54 PM.
 
Old 02-05-2018, 05:24 PM   #5
mfoley
Senior Member
 
Registered: Oct 2008
Location: Columbus, Ohio USA
Distribution: Slackware
Posts: 2,564

Original Poster
Rep: Reputation: 177Reputation: 177
Well, as mentioned, I'm using JSP which creates the main class as part of its compilation of the jsp. The generated .java code has for the main class:
Code:
public final class printAPchecks_jsp extends org.apache.jasper.runtime.HttpJspBase
     implements org.apache.jasper.runtime.JspSourceDependent,
                  org.apache.jasper.runtime.JspSourceImports { ...}
which is likely the equivalent of your 'public class Main{}'. All jsp code is actually expanded within this printAPchecks_jsp class and you cannot define classes external to this class, which is probably what is needed in your example.

In the generated .java code the reportDetail() is simply a function, not a class:
Code:
static void reportDetail(Statement stmt, BufferedWriter outFile, String detailColumn) throws Exception { ... }
So either there is no "super class" or printAPchecks_jsp { ... } is the super class.

Perhaps this cannot be done this way (or at all?) in JSP.
 
Old 02-05-2018, 05:56 PM   #6
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 11,235

Rep: Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320
Quote:
Originally Posted by mfoley View Post
However, the body of the function is defined locally in any given program.
Post an example of how that would be done.

reportDetail() is part of a class. Your example should include that class.

Last edited by dugan; 02-05-2018 at 06:24 PM.
 
Old 02-05-2018, 08:13 PM   #7
mfoley
Senior Member
 
Registered: Oct 2008
Location: Columbus, Ohio USA
Distribution: Slackware
Posts: 2,564

Original Poster
Rep: Reputation: 177Reputation: 177
Here is a complete (probably compilable) .jsp program. Unless escaped with some form of "<%", lines in the code are assumed to be HTML statements, like the 1st 3 lines in the example. Java code is bracket by <% someJavaCode %>. The <%@ ... %> delimiters are for including files or imports. The <%! ... %> delimiters are for function definitions. In this example, the main logic calls the pdfmergeDoc() function which, in-turn, calls reportDetail().
Code:
<!DOCTYPE html>
<html>
<body>

<%@ page import="javax.naming.Context,
  javax.naming.NamingException,
  javax.sql.DataSource,
  javax.servlet.http.Cookie,
  java.sql.*,
  java.lang.String, java.lang.Object,
  java.io.*, java.util.*,
  java.util.Calendar, java.util.Date, java.text.SimpleDateFormat" %>
<%
String ua = (request.getHeader( "User-Agent" ) == null) ? "" : request.getHeader( "User-Agent" );

String pdfURL =  mergeDoc();

out.println("</body></html>");
%>

<%!
static void reportDetail(Statement stmt, BufferedWriter outFile, String detailColumn) throws Exception
{
// doSomething
}
%>
The .java generated from this .jsp is 1,552 lines and begins as follows:
Code:
/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/8.5.23
 * Generated at: 2018-02-05 23:21:50 UTC
 * Note: The last modified time of this file was set to
 *       the last modified time of the source file after
 *       generation to assist with modification tracking.
 */
package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.servlet.http.Cookie;
import java.sql.*;
import java.lang.String;
import java.lang.Object;
import java.io.*;
import java.util.*;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.lang.StringBuffer;
import java.text.FieldPosition;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Random;
import java.lang.Runtime;
import java.io.*;
import java.util.Random;

public final class printAPchecks_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent,
                 org.apache.jasper.runtime.JspSourceImports {
:
:
static void reportDetail(Statement stmt, BufferedWriter outFile, String detailColumn) throws Exception
{
:
:
}

}

Last edited by mfoley; 02-05-2018 at 08:25 PM.
 
Old 02-05-2018, 09:00 PM   #8
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 11,235

Rep: Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320
Okay, this demo does work. It prints "the user agent":

Code:
class GlobalData
{
    static String userAgent;
}

final class printAPChecks_jsp
{
    static void reportDetail()
    {
        System.out.println(GlobalData.userAgent);
    }
}

public class GlobalDataDemo
{
    public static void main(String[] args)
    {
        GlobalData.userAgent = "The user agent";
        printAPChecks_jsp.reportDetail();
    }
};
What I have in mind is:

Code:
<%@ page import="GlobalData %>
<%
GlobalData.ua = (request.getHeader( "User-Agent" ) == null) ? "" : request.getHeader( "User-Agent" );
%>

<%!
static void reportDetail(Statement stmt, BufferedWriter outFile, String detailColumn) throws Exception
{
// doSomething with GlobalData.ua
}
%>
This does depend on the "page imports" working consistently across the <%%> and <%!%> sections. If not, then I'm out of ideas.

Last edited by dugan; 02-05-2018 at 09:18 PM.
 
Old 02-05-2018, 09:27 PM   #9
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 11,235

Rep: Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320
Could you perhaps put the user-agent in a session? That's a global store... A number of the hits I got when I googled this recommended exactly that.

Last edited by dugan; 02-05-2018 at 09:30 PM.
 
  


Reply

Tags
global, java, jsp, variable



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Global variable "sensors_proc_chips" is NULL after installing lm-sensor package . viveksr89 Linux - Newbie 1 08-25-2015 07:33 AM
Can not access Global variable in C "expected expression before â??:â?? token" golden_boy615 Programming 1 11-16-2011 02:30 PM
how can i create a global variable called "dogpatch" with a value of "woof" earthdog Linux - Newbie 9 12-15-2009 01:03 AM
c++ - "index" is a global scope variable in <string>???? BrianK Programming 2 03-18-2008 08:05 PM
"undefined reference" to a template class function btb Programming 3 08-25-2005 05:02 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 01:38 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration