Rectangle 27 181

For small applications I highly recommend passing parameters directly from the caller to the controller - it's simple, straightforward and requires no extra frameworks.

For larger, more complicated applications, it would be worthwhile investigating if you want to use Dependency Injection or Event Bus mechanisms within your application.

Passing Parameters Directly From the Caller to the Controller

Pass custom data to an FXML controller by retrieving the controller from the FXML loader instance and calling a method on the controller to initialize it with the required data values.

Something like the following code:

public Stage showCustomerDialog(Customer customer) {
  FXMLLoader loader = new FXMLLoader(
    getClass().getResource(
      "customerDialog.fxml"
    )
  );

  Stage stage = new Stage(StageStyle.DECORATED);
  stage.setScene(
    new Scene(
      (Pane) loader.load()
    )
  );

  CustomerDialogController controller = 
    loader.<CustomerDialogController>getController();
  controller.initData(customer);

  stage.show();

  return stage;
}

...

class CustomerDialogController() {
  @FXML private Label customerName;
  void initialize() {}
  void initData(Customer customer) {
    customerName.setText(customer.getName());
  }
}

A new FXMLLoader is constructed as shown in the sample code i.e. new FXMLLoader(location). The location is a URL and you can generate such a URL from an FXML resource by:

new FXMLLoader(getClass().getResource("sample.fxml"));

FXMLLoader instances themselves never know anything about domain objects. You do not directly pass application specific domain objects into the FXMLLoader constructor, instead you:

  • Get a controller from the FXMLLoader instance.
  • Invoke methods on the retrieved controller to provide the controller with references to the domain objects.

Setting a Controller on the FXMLLoader

CustomerDialogController dialogController = 
    new CustomerDialogController(param1, param2);

FXMLLoader loader = new FXMLLoader(
    getClass().getResource(
        "customerDialog.fxml"
    )
);
loader.setController(dialogController);

Pane mainPane = (Pane) loader.load();

You can construct a new controller in code, passing any parameters you want from your caller into the controller constructor. Once you have constructed a controller, you can set it on an FXMLLoader instance before you invoke the load() instance method.

fx:controller

Due to the limitation on the fx:controller definition in FXML, I personally prefer getting the controller from the FXMLLoader rather than setting the controller into the FXMLLoader.

Having the Controller Retrieve Parameters from an External Static Method

FXMLLoader supports dependency injection systems like Guice, Spring or Java EE CDI by allowing you to set a custom controller factory on the FXMLLoader. This provides a callback that you can use to create the controller instance with dependent values injected by the respective dependency injection system. There is a sample of integrating FXML with the Spring dependency injection system (unfortunately the link is dead and the content is gone, if anybody knows of a similar example, please edit this question to reference it), though it's a bit clunkier than it would be using the new custom controller factory features made available in JavaFX 2.2.

A really nice, clean dependency injection approach is exemplified by the afterburner.fx framework with a sample air-hacks application that uses it. afterburner.fx relies on JEE6 javax.inject to perform the dependency injection.

Greg Brown, the original FXML specification creator and implementor, often suggests considering use of an event bus for communication between FXML instantiated controllers and other application logic.

The EventBus is a simple but powerful publish/subscribe API with annotations that allows POJOs to communicate with each other anywhere in a JVM without having to refer to each other.

on first method, why do you return Stage? The method can be void as well because you already giving the command show(); just before return stage;. How do you plan usage by returning the Stage

It is a functional solution to a problem. A stage is returned from the showCustomerDialog function so that a reference to it can be stored by an external class which may wish to do something, such as hide the stage based on a button click in the main window, at a later time. An alternate, object-oriented solution could encapsulate the functionality and stage reference inside a CustomerDialog object or have a CustomerDialog extend Stage. A full example for an object-oriented interface to a custom dialog encapsulating FXML, controller and model data is beyond the scope of this answer, but may make a worthwhile blog post for anybody inclined to create one.

The question of how to do it "The Spring Boot Way", there was a discussion about JavaFX 2, which I anserwered in the attached permalink. The approach is still valid and tested in March 2016, on Spring Boot v1.3.3.RELEASE: https://stackoverflow.com/a/36310391/1281217

FXMLLoader constructors only take URLs as parameters.. what's the correct way to instantiate the FXMLLoader?

the event bus website alluded to states, "Update 3/2013: The EventBus has gone stale..."

for godshake is there anything simple for doing this tiny work in JavaFx? its a very common feature to pass data in constructor and javafx requires this hell of things all together just to send one name or one value?

Passing Parameters JavaFX FXML - Stack Overflow

javafx parameters dependency-injection parameter-passing fxml
Rectangle 27 181

For small applications I highly recommend passing parameters directly from the caller to the controller - it's simple, straightforward and requires no extra frameworks.

For larger, more complicated applications, it would be worthwhile investigating if you want to use Dependency Injection or Event Bus mechanisms within your application.

Passing Parameters Directly From the Caller to the Controller

Pass custom data to an FXML controller by retrieving the controller from the FXML loader instance and calling a method on the controller to initialize it with the required data values.

Something like the following code:

public Stage showCustomerDialog(Customer customer) {
  FXMLLoader loader = new FXMLLoader(
    getClass().getResource(
      "customerDialog.fxml"
    )
  );

  Stage stage = new Stage(StageStyle.DECORATED);
  stage.setScene(
    new Scene(
      (Pane) loader.load()
    )
  );

  CustomerDialogController controller = 
    loader.<CustomerDialogController>getController();
  controller.initData(customer);

  stage.show();

  return stage;
}

...

class CustomerDialogController() {
  @FXML private Label customerName;
  void initialize() {}
  void initData(Customer customer) {
    customerName.setText(customer.getName());
  }
}

A new FXMLLoader is constructed as shown in the sample code i.e. new FXMLLoader(location). The location is a URL and you can generate such a URL from an FXML resource by:

new FXMLLoader(getClass().getResource("sample.fxml"));

FXMLLoader instances themselves never know anything about domain objects. You do not directly pass application specific domain objects into the FXMLLoader constructor, instead you:

  • Get a controller from the FXMLLoader instance.
  • Invoke methods on the retrieved controller to provide the controller with references to the domain objects.

Setting a Controller on the FXMLLoader

CustomerDialogController dialogController = 
    new CustomerDialogController(param1, param2);

FXMLLoader loader = new FXMLLoader(
    getClass().getResource(
        "customerDialog.fxml"
    )
);
loader.setController(dialogController);

Pane mainPane = (Pane) loader.load();

You can construct a new controller in code, passing any parameters you want from your caller into the controller constructor. Once you have constructed a controller, you can set it on an FXMLLoader instance before you invoke the load() instance method.

fx:controller

Due to the limitation on the fx:controller definition in FXML, I personally prefer getting the controller from the FXMLLoader rather than setting the controller into the FXMLLoader.

Having the Controller Retrieve Parameters from an External Static Method

FXMLLoader supports dependency injection systems like Guice, Spring or Java EE CDI by allowing you to set a custom controller factory on the FXMLLoader. This provides a callback that you can use to create the controller instance with dependent values injected by the respective dependency injection system. There is a sample of integrating FXML with the Spring dependency injection system (unfortunately the link is dead and the content is gone, if anybody knows of a similar example, please edit this question to reference it), though it's a bit clunkier than it would be using the new custom controller factory features made available in JavaFX 2.2.

A really nice, clean dependency injection approach is exemplified by the afterburner.fx framework with a sample air-hacks application that uses it. afterburner.fx relies on JEE6 javax.inject to perform the dependency injection.

Greg Brown, the original FXML specification creator and implementor, often suggests considering use of an event bus for communication between FXML instantiated controllers and other application logic.

The EventBus is a simple but powerful publish/subscribe API with annotations that allows POJOs to communicate with each other anywhere in a JVM without having to refer to each other.

on first method, why do you return Stage? The method can be void as well because you already giving the command show(); just before return stage;. How do you plan usage by returning the Stage

It is a functional solution to a problem. A stage is returned from the showCustomerDialog function so that a reference to it can be stored by an external class which may wish to do something, such as hide the stage based on a button click in the main window, at a later time. An alternate, object-oriented solution could encapsulate the functionality and stage reference inside a CustomerDialog object or have a CustomerDialog extend Stage. A full example for an object-oriented interface to a custom dialog encapsulating FXML, controller and model data is beyond the scope of this answer, but may make a worthwhile blog post for anybody inclined to create one.

The question of how to do it "The Spring Boot Way", there was a discussion about JavaFX 2, which I anserwered in the attached permalink. The approach is still valid and tested in March 2016, on Spring Boot v1.3.3.RELEASE: https://stackoverflow.com/a/36310391/1281217

FXMLLoader constructors only take URLs as parameters.. what's the correct way to instantiate the FXMLLoader?

the event bus website alluded to states, "Update 3/2013: The EventBus has gone stale..."

for godshake is there anything simple for doing this tiny work in JavaFx? its a very common feature to pass data in constructor and javafx requires this hell of things all together just to send one name or one value?

Passing Parameters JavaFX FXML - Stack Overflow

javafx parameters dependency-injection parameter-passing fxml
Rectangle 27 230

Varargs gotchas #3: passing an array of primitives

Yes, a T... is only a syntactic sugar for a T[].

The last formal parameter in a list is special; it may be a variable arity parameter, indicated by an elipsis following the type.

If the last formal parameter is a variable arity parameter of type T, it is considered to define a formal parameter of type T[]. The method is then a variable arity method. Otherwise, it is a fixed arity method. Invocations of a variable arity method may contain more actual argument expressions than formal parameters. All the actual argument expressions that do not correspond to the formal parameters preceding the variable arity parameter will be evaluated and the results stored into an array that will be passed to the method invocation.

public static String ezFormat(Object... args) {
    String format = new String(new char[args.length])
        .replace("\0", "[ %s ]");
    return String.format(format, args);
}
public static void main(String... args) {
    System.out.println(ezFormat("A", "B", "C"));
    // prints "[ A ][ B ][ C ]"
}

And yes, the above main method is valid, because again, String... is just String[]. Also, because arrays are covariant, a String[] is an Object[], so you can also call ezFormat(args) either way.

How varargs are resolved is quite complicated, and sometimes it does things that may surprise you.

static void count(Object... objs) {
    System.out.println(objs.length);
}

count(null, null, null); // prints "3"
count(null, null); // prints "2"
count(null); // throws java.lang.NullPointerException!!!

Due to how varargs are resolved, the last statement invokes with objs = null, which of course would cause NullPointerException with objs.length. If you want to give one null argument to a varargs parameter, you can do either of the following:

count(new Object[] { null }); // prints "1"
count((Object) null); // prints "1"

The following is a sample of some of the questions people have asked when dealing with varargs:

As you've found out, the following doesn't "work":

Because of the way varargs work, ezFormat actually gets 2 arguments, the first being a String[], the second being a String. If you're passing an array to varargs, and you want its elements to be recognized as individual arguments, and you also need to add an extra argument, then you have no choice but to create another array that accommodates the extra element.

static <T> T[] append(T[] arr, T lastElement) {
    final int N = arr.length;
    arr = java.util.Arrays.copyOf(arr, N+1);
    arr[N] = lastElement;
    return arr;
}
static <T> T[] prepend(T[] arr, T firstElement) {
    final int N = arr.length;
    arr = java.util.Arrays.copyOf(arr, N+1);
    System.arraycopy(arr, 0, arr, 1, N);
    arr[0] = firstElement;
    return arr;
}

Now you can do the following:

String[] myArgs = { "A", "B", "C" };
    System.out.println(ezFormat(append(myArgs, "Z")));
    // prints "[ A ][ B ][ C ][ Z ]"

    System.out.println(ezFormat(prepend(myArgs, "Z")));
    // prints "[ Z ][ A ][ B ][ C ]"
int[] myNumbers = { 1, 2, 3 };
    System.out.println(ezFormat(myNumbers));
    // prints "[ [I@13c5982 ]"

Varargs only works with reference types. Autoboxing does not apply to array of primitives. The following works:

Integer[] myNumbers = { 1, 2, 3 };
    System.out.println(ezFormat(myNumbers));
    // prints "[ 1 ][ 2 ][ 3 ]"

Using Object... variadic parameters makes it difficult to use additional signatures as the compiler identifies ambiguity between the signatures where even a primitive argument can be autoboxed to Object.

There is a missing gotcha : if your method has a last param of type Object... and you call it passing a String[] for instance. The compiler doesn't know if your array is the first item of the varargs or is the equivalent of all the varargs. It will warn you.

Can I pass an array as arguments to a method with variable arguments i...

java arrays backwards-compatibility variadic-functions
Rectangle 27 16

If you are passing more than 3 or so parameters (especially intrinsic types/objects), it's not that it's "Too many" but that you may be missing a chance to create a new object.

Look for groups of parameters that get passed into more than one method--even a group passed into two methods almost guarantees that you should have a new object there.

Then you refactor functionality into your new object and you wouldn't believe how much it helps both your code and your understanding of OO programming.

Please, name a language that doesn't use routines nor parameters. I can't think of one, even assembly could be considered to have routines (labels).

Sorry, "ret", not "return". Sighs. It's been a long day already.

Sorry about the ambiguous phrasing Auron, I believe I fixed it. It was my answer that was language-specific, not the question.

Not all languages allow passing structures. Also, passing a structure means that the receiving method has to have the code to handle the structure and may, therefore, need more parameters. Also, in a non-oo language, you generally need an extra parameter--all OO languages have a "Hidden" parameter of "this" that should otherwise be passed in (or, in a more horrific language/design, might be globally accessible)

design - How many parameters are too many? - Stack Overflow

design parameters language-agnostic
Rectangle 27 3

According to what I read version 2.1 of the Unified Expression Language, included in Java EE 6, has support for invoking arbitrary methods and passing arguments to them.

I think you are mistaken. This support was introduced in JSP 2.2 (which is required to meet the JEE6 spec).

The main change in this release is the addition of method invokations with parameters in the EL, such as #{trader.buy(JAVA)}.

Since Tomcat 6 is a JSP 2.1 container, you might consider upgrading to Tomcat 7.

Tested with Tomcat 7 and it works.It seems you are right.So for invocation with params I should use Tomcat 7 although it is in beta?

@user384706 - implementations for the most recent Servlet and JSP specs are still a bit thin on the ground. I'm not aware of any that are GA other than Glassfish 3 and JBoss 6 (full JEE servers). I believe you can get equivalent functionality with JBoss EL/Seam 2.2, but I'm not sure what the compatibility story is with this stack.

java - jsf Invoking Arbitrary Methods via EL - Stack Overflow

java jsf jsf-2 el
Rectangle 27 6

@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
application/x-www-form-urlencoded

Edited: You can use FormParams only with POST:

SRV.4.1.1 When Parameters Are Available The following are the conditions that must be met before post form data will be populated to the parameter set:

  • The request is an HTTP or HTTPS request.
  • The servlet has made an initial call of any of the getParameter family of methods on the request object. If the conditions are not met and the post form data is not included in the parameter set, the post data must still be available to the servlet via the request objects input stream. If the conditions are met, post form data will no longer be available for reading directly from the request objects input stream.

Yes, I am specifying content type as {application/x-www-form-urlencoded} while sending request

Oh, didn't pay attention that you use PUT: you must use POST with form parameters.

If you want to change the resource you should use PUT. POST method is used when you want to create resource. Here I want to change Person details so used PUT. Should I use POST instead?

Yes, I know, but form parameters will work only with POST. See the edited answer.

You may also get nulls If you set the "id" tag instead of the "name" tag in your html form field definitions. So <input type="text" id="username" /> will return null but <input type="text" name="username" /> will return the proper result.

java - JAX-RS with Jersey: Passing form parameters to PUT method for u...

java rest jaxb jersey jax-rs
Rectangle 27 8

why, how and which parameters are passed to Asynctask<>, see detail here. I think it is the best explanation.

Google's Android Documentation Says that :

An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

AsyncTask's generic types :

The three types used by an asynchronous task are the following:

Params, the type of the parameters sent to the task upon execution. Progress, the type of the progress units published during the background computation. Result, the type of the result of the background computation. Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

private class MyTask extends AsyncTask<Void, Void, Void> { ... }

Or You Can clear whats the role of AsyncTask by refering Sankar-Ganesh's Blog

Well The structure of a typical AsyncTask class goes like :

private class MyTask extends AsyncTask<X, Y, Z>

    protected void onPreExecute(){ 

    }

This method is executed before starting the new Thread. There is no input/output values, so just initialize variables or whatever you think you need to do.

protected Z doInBackground(X...x){

}

The most important method in the AsyncTask class. You have to place here all the stuff you want to do in the background, in a different thread from the main one. Here we have as an input value an array of objects from the type X (Do you see in the header? We have ...extends AsyncTask These are the TYPES of the input parameters) and returns an object from the type Z.

} This method is called using the method publishProgress(y) and it is usually used when you want to show any progress or information in the main screen, like a progress bar showing the progress of the operation you are doing in the background.

} This method is called after the operation in the background is done. As an input parameter you will receive the output parameter of the doInBackground method.

What about the X, Y and Z types?

As you can deduce from the above structure:

X  The type of the input variables value you want to set to the background process. This can be an array of objects.

 Y  The type of the objects you are going to enter in the onProgressUpdate method.

 Z  The type of the result from the operations you have done in the background process.

How do we call this task from an outside class? Just with the following two lines:

MyTask myTask = new MyTask();

myTask.execute(x);

Where x is the input parameter of the type X.

Once we have our task running, we can find out its status from outside. Using the getStatus() method.

myTask.getStatus(); and we can receive the following status:

RUNNING - Indicates that the task is running.

PENDING - Indicates that the task has not been executed yet.

Do not call the methods onPreExecute, doInBackground and onPostExecute manually. This is automatically done by the system.

You cannot call an AsyncTask inside another AsyncTask or Thread. The call of the method execute must be done in the UI Thread.

The method onPostExecute is executed in the UI Thread (here you can call another AsyncTask!).

The input parameters of the task can be an Object array, this way you can put whatever objects and types you want.

methods - Android: How can I pass parameters to AsyncTask's onPreExecu...

android methods parameters android-asynctask
Rectangle 27 1

ObjectA needs a reference to arrA. Typically this is done by passing it as a parameter to that function:

public class ObjectA {
    ...
    public void doThis(ArrayofObjectA arrA) {
        arrA.doSomething(); // <-- Here's the issue
    }
}

By doing this, you ensure that a reference is 'in scope' for that function. Normally functions can only 'see' parameters passed to them and member fields of their class. So, the other way it can call doSomething() is if there is a reference in the class itself:

public class ObjectA {
    private ArrayofObjectA arrA;

    public ObjectA(ArrayofObjectA a) {
      this.arrA = a; ///'this' is optional but makes it clear we are talking about a member field.
    }

    public void doThis(ArrayofObjectA arrA) {
        this.arrA.doSomething(); // <-- Here's the issue
    }
}

Note that a 'reference' is essentially some handle that allows you to refer to a particular instantiation of an object. You need a reference to call any non-static method. See this answer for more information on the difference between those two things.

Also note that despite naming your class ArrayofObjectA, it is not actually an array. There is only one instance of it declared (in your MainClass) and it (currently) possess no references to any ObjectA instantiations. More properly you might name this ArrayHolder:

public class ArrayHolder {
    private ObjectA[] arrA;//note that the [] indicates it's an array.

    public ArrayHolder() {
        this.arrA = new Object[10];//Length of ten
        for (int idx=0; idx<10; idx++) {
            this.arrA[idx] = new ObjectA(this);//pass new ObjectA a REFERENCE to 'this' object (ArrayHolder)
        }
    }

    public void doSomething() {
        //This is now callable from all ObjectA objects.
    }
}

He said "arrA holds an array of ObjectA objects"...

Wouldn't the second way just cause each ObjectA object to store an array of ObjectA objects including itself? That would be more memory heavy than going the getter-setter route.

No: it's not storing an array, it's storing a reference to an array. A reference you need in order to have access to that array.

Oh that's right, I see. Then it seems as though the second way would be the easiest to implement. Thanks.

java - How to call a method of an object that was instantiated in anot...

java arrays object methods getter
Rectangle 27 8

Passing parameters to method calls is not specific to JSF 2. It is specific to EL 2.2, which is in turn part of JSP 2.2 / Servlet 3.0 / Java EE 6. JSF 2 just happens to be part of Java EE 6 as well. In other words, if you deploy your JSF 1.2 web application to a Servlet 3.0 compatible container like Tomcat 7, Glassfish 3, etc and your web.xml is declared conform Servlet 3.0 spec version, then it'll just work out the box for JSF 1.x as well.

If you're however still targeting a container of an older Servlet version, then you need to supply a different EL implementation which supports invoking methods with arguments. One of those implementations is JBoss-EL which you can install by just dropping the jboss-el.jar file in /WEB-INF/lib of your webapp and adding the following context parameter to the web.xml. Here's a Mojarra-specific example (Mojarra is the codename of JSF RI):

<context-param>     
    <param-name>com.sun.faces.expressionFactory</param-name>
    <param-value>org.jboss.el.ExpressionFactoryImpl</param-value>   
</context-param>

If you're using MyFaces as JSF implementation, you need the following context parameter instead:

<context-param>
    <param-name>org.apache.myfaces.EXPRESSION_FACTORY</param-name>
    <param-value>org.jboss.el.ExpressionFactoryImpl</param-value>   
</context-param>

Invoking methods with parameters by EL in JSF 1.2 - Stack Overflow

jsf el jsf-1.2
Rectangle 27 8

Passing parameters to method calls is not specific to JSF 2. It is specific to EL 2.2, which is in turn part of JSP 2.2 / Servlet 3.0 / Java EE 6. JSF 2 just happens to be part of Java EE 6 as well. In other words, if you deploy your JSF 1.2 web application to a Servlet 3.0 compatible container like Tomcat 7, Glassfish 3, etc and your web.xml is declared conform Servlet 3.0 spec version, then it'll just work out the box for JSF 1.x as well.

If you're however still targeting a container of an older Servlet version, then you need to supply a different EL implementation which supports invoking methods with arguments. One of those implementations is JBoss-EL which you can install by just dropping the jboss-el.jar file in /WEB-INF/lib of your webapp and adding the following context parameter to the web.xml. Here's a Mojarra-specific example (Mojarra is the codename of JSF RI):

<context-param>     
    <param-name>com.sun.faces.expressionFactory</param-name>
    <param-value>org.jboss.el.ExpressionFactoryImpl</param-value>   
</context-param>

If you're using MyFaces as JSF implementation, you need the following context parameter instead:

<context-param>
    <param-name>org.apache.myfaces.EXPRESSION_FACTORY</param-name>
    <param-value>org.jboss.el.ExpressionFactoryImpl</param-value>   
</context-param>

Invoking methods with parameters by EL in JSF 1.2 - Stack Overflow

jsf el jsf-1.2
Rectangle 27 8

Passing parameters to method calls is not specific to JSF 2. It is specific to EL 2.2, which is in turn part of JSP 2.2 / Servlet 3.0 / Java EE 6. JSF 2 just happens to be part of Java EE 6 as well. In other words, if you deploy your JSF 1.2 web application to a Servlet 3.0 compatible container like Tomcat 7, Glassfish 3, etc and your web.xml is declared conform Servlet 3.0 spec version, then it'll just work out the box for JSF 1.x as well.

If you're however still targeting a container of an older Servlet version, then you need to supply a different EL implementation which supports invoking methods with arguments. One of those implementations is JBoss-EL which you can install by just dropping the jboss-el.jar file in /WEB-INF/lib of your webapp and adding the following context parameter to the web.xml. Here's a Mojarra-specific example (Mojarra is the codename of JSF RI):

<context-param>     
    <param-name>com.sun.faces.expressionFactory</param-name>
    <param-value>org.jboss.el.ExpressionFactoryImpl</param-value>   
</context-param>

If you're using MyFaces as JSF implementation, you need the following context parameter instead:

<context-param>
    <param-name>org.apache.myfaces.EXPRESSION_FACTORY</param-name>
    <param-value>org.jboss.el.ExpressionFactoryImpl</param-value>   
</context-param>

Invoking methods with parameters by EL in JSF 1.2 - Stack Overflow

jsf el jsf-1.2
Rectangle 27 2

However, I gather that it is inadvisable (and inconvenient) to pass methods as parameters in Java, and doing so generically might be impossible

Since Java 8, you can pass such generic methods as arguments; and what you want here is a Runnable.

Provided you have two methods in a same class:

public final class Foo
{
    void f1() { /* whatever */ }
    void f2() { /* whatever */ }
}

then you can time both in code using method references, as in:

final Runnable r1 = Foo::f1;
final Runnable r2 = Foo::f2;

and then use those method references (which are valid lambdas) into some timing code:

long start, end;

Stream.of(r1, r2).forEach(r -> {
    start = System.nanoTime();
    r.run();
    end = System.nanoTime();
    System.out.println("Time spent in ns: " + (end - start));
});

After that, you can further refine your code so as to use, for instance, IntConsumers.

Now, admittedly, for benchmark purposes, one run won't do it. There is the JIT to consider, and the JIT will only kick in after a certain amount of executions of the same code path, for some definition of a "certain amount". So, while the code above will give you an indication (for what this indication is worth), you should not take it as an absolute in any event.

algorithm - Passing methods to a benchmark program in Java - Stack Ove...

java algorithm parameter-passing benchmarking timing
Rectangle 27 4

First of all, the only way you'll get parameters passed to a method with the [AcceptVerbs(HttpVerbs.Get)] attribute is via query parameters. Example:

http://localhost/Task/Index/?task=mytask&todolist=a,b,c,d

Many of the action methods you see with complex parameters are called via post and would most likey be a candidate for [AcceptVerbs(HttpVerbs.Post)].

Create the following sample method:

public ActionResult Index(int id, FormCollection form)
{

}

If you where to inspect the form collection you might have something like the following after a form post:

form["name"] = "bob"
form["city"] = "LA"
form["state"] = "CA"
form["zip"] = "90210"

in this case asp.net mvc has simply parsed the form values and thrown them into the form collection object. Of course now you have to extract each parameter manually to access the values. Wouldn't it be nice if there was way that asp.net mvc would handle that process for you? If you had the following class:

public class User
{
    string string Name {get; set;}
    string string City {get; set;}
    string string State {get; set;}
    string string Zip {get; set;}
}
public ActionResult Index(int id, User user)

asp.net mvc will use reflection to popuplate the user parameter prior to calling your action method. In effect it is doing the following, for each key in the form collection it it uses reflection to locate that property om the list of parameters declared in your action method. If it finds a property that matches it will attempt to set it's value.

user.Name = form["name"]
user.City = form["city"]
user.State = form["state"]
user.Zip = int.Parse(form["zip"])

However, the id value gets set from the routing values as opposed to the form collection.

c# - Can you explain to me the Action parameters for MVCs Controller m...

c# asp.net asp.net-mvc
Rectangle 27 92

The workarounds above (thanks!) don't properly address the problem of getting back the objects provided to the deferred's resolve() method because jQuery calls the done() and fail() callbacks with individual parameters, not an array. That means we have to use the arguments pseudo-array to get all the resolved/rejected objects returned by the array of deferreds, which is ugly:

$.when.apply($,deferreds).then(function() {
     var objects=arguments; // The array of resolved objects as a pseudo-array
     ...
};

Since we passed in an array of deferreds, it would be nice to get back an array of results. It would also be nice to get back an actual array instead of a pseudo-array so we can use methods like Array.sort().

Here is a solution inspired by when.js's when.all() method that addresses these problems:

// Put somewhere in your scripting environment
if (typeof jQuery.when.all === 'undefined') {
    jQuery.when.all = function (deferreds) {
        return $.Deferred(function (def) {
            $.when.apply(jQuery, deferreds).then(
                function () {
                    def.resolveWith(this, [Array.prototype.slice.call(arguments)]);
                },
                function () {
                    def.rejectWith(this, [Array.prototype.slice.call(arguments)]);
                });
        });
    }
}

Now you can simply pass in an array of deferreds/promises and get back an array of resolved/rejected objects in your callback, like so:

$.when.all(deferreds).then(function(objects) {
    console.log("Resolved objects:", objects);
});

You might want to use resolveWith and rejectWith just so you get the same original deferreds as 'this' deferred.resolveWith(this, [Array.prototype.slice.call(arguments)]) etc

There is just a small problem with your code, when there is only one element in the array the results array returns just that result, instead of a array with a single element (which will break the code that expects an array). To fix it, use this function var toArray = function (args) { return deferreds.length > 1 ? $.makeArray(args) : [args]; } instead of Array.prototype.slice.call.

Found the reason, .fail should be .reject instead - so it can catch 404's.

javascript - Pass in an array of Deferreds to $.when() - Stack Overflo...

javascript jquery argument-passing jquery-deferred .when
Rectangle 27 8

The standard way of passing/submitting data to the server in the pure Servlets/JSP world (as in your case from the JSP to the servlet) is by using HTML form, i.e. the same way as when using other technologies (ASP.NET, PHP etc). And it doesn't matter whether it is a pure HTML page or JSP page. The recommended/most used method of submitting data from the form to the server is POST.

You also can pass data in the query string that is contained in the request URL after the path (this also happens when instead of POST you use GET method in the form). But that is for the simple cases, like constructing URLs for the pagination etc (you can see the example of constructing URLs with the additional queries here: Composing URL in JSP) Example of passing parameters in the URL:http://example.com/foo?param1=bar&page=100

difference between submitting data using GET and POST methods

So you can configure some servlet to process data sent/submitted from a JSP or HTML etc. It is highly recommended to submit data using POST method and respectively to process the submitted data using the doPost() method in your servlet. You will then get the parameters passed by the client in the request by using one of the following ServletRequest methods:

Another way of exchanging data using Java EE is by storing data as attributes in different scopes. (Following is the excerpt from one of my answers on SO)

You can store some data in all the above scopes by setting the appropriate attribute.

void setAttribute(java.lang.String name,
                  java.lang.Object o)

Stores an attribute in this request. Attributes are reset between requests. This method is most often used in conjunction with RequestDispatcher. ...

So with every new request the previous attributes you have set in request will be lost. After you have set an attribute in a request, you must forward the request to the desired page. If you redirect, this will be a totally NEW request, thus the attributes previously set will be lost. (If you still want use redirection read this: Servlet Redirection to same page with error message)

Those attributes that are set in a HttpSession (in the session scope) will live as long as the session lives and, of course, will be available to only the user to which session belongs.

As for the context attributes they are meant to be available to the whole web application (application scope) and for ALL users, plus they live as long as the web application lives.

Also pay attention to the following issue. You wrote (quote):

I know , We can pass variable from servlet to jsp by using request.setAttribute(key , value) But when I used it to set variable in jsp and again get it by using session.getAttribute(key ) then result is null.

As the users @neel and @Sanchit have noticed, you are setting an attribute in the request object, but trying to get it back from the session. No wonder you are getting null in this case.

@SanjayaPandey You are welcome!

java - Passing variables from JSP to servlet - Stack Overflow

java jsp servlets httprequest
Rectangle 27 11

Apart from the syntax error (you can never nest EL expressions like as #{#{}}), the following is valid in EL 2.2 which is in turn part of Servlet 3.0 / Java EE 6:

<h:outputText value="#{bean.getValue(item.product).component.address}" />

So if you have a Servlet 3.0 compatible target runtime (Tomcat 7, Glassfish 3, JBoss 6, etc) with a Servlet 3.0 compatible web.xml, then you can invoke non-getter methods with arguments like this.

However, based on your question history you're using JSF 1.2 and the chance is big that you're also targeting an older container where the above wouldn't work. If it is a Servlet 2.5 container, then you could use JBoss EL to get this EL syntax to work.

jsf - Passing parameters to a method in h:outputtext tag - Stack Overf...

jsf el
Rectangle 27 3

If the parameters you're passing in can be grouped together logically you could think about using a parameter object (Refactoring, Martin Fowler, p295), that way if you need to add more parameters you can just add more fields to your parameter class and it won't break existing methods.

method overloading - Should my PHP functions accept an array of argume...

php method-overloading
Rectangle 27 3

If the parameters you're passing in can be grouped together logically you could think about using a parameter object (Refactoring, Martin Fowler, p295), that way if you need to add more parameters you can just add more fields to your parameter class and it won't break existing methods.

method overloading - Should my PHP functions accept an array of argume...

php method-overloading
Rectangle 27 3

You cannot send complex objects as route parameters.B'cos it's converted into query string when passing to the action methods.So always need to use primitive data types.

@Html.ActionLink("Return to Incentives", "provider", new { action = "index", controller = "incentives" , providerKey = Model.Key }, new { @class = "actionButton" })

Your route table should be looks like below.Consist of primitive data types.

routes.MapRoute(
     "Default", // Route name
     "{controller}/{action}/{id}", // URL with parameters
     new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

You can send a Id of the model as a parameter with ActionLink and then get the necessary object from the database for further processing inside the controller's action method.

You can use TempData for send objects from one Action Method to another. Simply it's share data between controller actions.You should only use it during the current and the subsequent requests only.

As an example

public class CreditCardInfo
{
    public string CardNumber { get; set; }
    public int ExpiryMonth { get; set; }
 }
[HttpPost]
public ActionResult CreateOwnerCreditCardPayments(CreditCard cc,FormCollection frm)
  {
        var creditCardInfo = new CreditCardInfo();
        creditCardInfo.CardNumber = cc.Number;
        creditCardInfo.ExpiryMonth = cc.ExpMonth;

    //persist data for next request
    TempData["CreditCardInfo"] = creditCardInfo;
    return RedirectToAction("CreditCardPayment", new { providerKey = frm["providerKey"]});
  }


 [HttpGet]
 public ActionResult CreditCardPayment(string providerKey)
  {
     if (TempData["CreditCardInfo"] != null)
        {
         var creditCardInfo = TempData["CreditCardInfo"] as CreditCardInfo;
        }

      return View();

    }

If you need more details about TempData then you can check blog post which I have written.

c# - Passing multiple parameters to action - Stack Overflow

c# asp.net-mvc-3 asp.net-mvc-routing
Rectangle 27 3

You cannot send complex objects as route parameters.B'cos it's converted into query string when passing to the action methods.So always need to use primitive data types.

@Html.ActionLink("Return to Incentives", "provider", new { action = "index", controller = "incentives" , providerKey = Model.Key }, new { @class = "actionButton" })

Your route table should be looks like below.Consist of primitive data types.

routes.MapRoute(
     "Default", // Route name
     "{controller}/{action}/{id}", // URL with parameters
     new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

You can send a Id of the model as a parameter with ActionLink and then get the necessary object from the database for further processing inside the controller's action method.

You can use TempData for send objects from one Action Method to another. Simply it's share data between controller actions.You should only use it during the current and the subsequent requests only.

As an example

public class CreditCardInfo
{
    public string CardNumber { get; set; }
    public int ExpiryMonth { get; set; }
 }
[HttpPost]
public ActionResult CreateOwnerCreditCardPayments(CreditCard cc,FormCollection frm)
  {
        var creditCardInfo = new CreditCardInfo();
        creditCardInfo.CardNumber = cc.Number;
        creditCardInfo.ExpiryMonth = cc.ExpMonth;

    //persist data for next request
    TempData["CreditCardInfo"] = creditCardInfo;
    return RedirectToAction("CreditCardPayment", new { providerKey = frm["providerKey"]});
  }


 [HttpGet]
 public ActionResult CreditCardPayment(string providerKey)
  {
     if (TempData["CreditCardInfo"] != null)
        {
         var creditCardInfo = TempData["CreditCardInfo"] as CreditCardInfo;
        }

      return View();

    }

If you need more details about TempData then you can check blog post which I have written.

c# - Passing multiple parameters to action - Stack Overflow

c# asp.net-mvc-3 asp.net-mvc-routing