Reputation: 6399
The below is my requirement.
There is a screen in which an user enters a file name and clicks on submit.
On click of submit , a spring batch job must be triggered. The batch job reads the file and populates a database.
How do we call a spring batch job from a java code(specifically from a struts action class code ) ?
Also,I need to pass the file name(that the user entered on the screen) to the batch program. How do we achieve this ?
Upvotes: 4
Views: 7709
Reputation: 22509
Spring Batch jobs are launched (e.g. run) via a JobLauncher. One of the implementations of the launcher is provided by the framework that you can use outside of the box: SimpleJobLauncher. Take a look at the Configuring a JobLauncher section of the docs
While most of the time batch jobs are launched from a command line ( scheduled or not ), there are several ways to do it from the web. Take a look at Running Jobs from within a Web Container section of Spring Batch docs.
The idea is simple. You just call jobLauncher.run
from within a controller:
@Controller
public class JobLauncherController {
@Autowired
JobLauncher jobLauncher;
@Autowired
Job job;
@RequestMapping("/jobLauncher.html")
public void handle() throws Exception{
jobLauncher.run(job, new JobParameters());
}
}
This is Spring MVC (not Struts), but you can see it is very simple, and would work for any controller / action class:
jobLauncher
and job
are injected => setJobLauncher(...) / setJob(...)jobLauncher
runs the job from a jobLauncher.html
page (note: the call to run
does not block)Another way to launch Spring Batch jobs without worrying about Spring MVC and Struts at all is to use a Spring Batch Admin which is there to solve this exact problem and more (monitoring / stopping / etc..)
Upvotes: 5
Reputation: 23587
Struts action classes are normal classes and you can write any code which you want to write inside this. S2 will by dafault call the execute method insdie your action class untill you have specified any other method name in your configuration file. all you need to do the following steps
For sending the value of file name from your jsp all you need to create an input field like
<s:textfield name="fileName" id="fileName"/>
create a property in your action class with name fileName
and its getter and setter.All you need to pass the file name to your batch processing service class method.In short you should have a flow similar to this
public class BatchProcessingAction extends ActionSupport{
private string fileName;
private ServiceClass serviceClass;
getter ans setter for above defined properties
public string execute() throw Exeption{
serviceclass=new ServiceClass(); // can use Di or factory for this
serviceClass.executeBatchProcessing(fileName);
return SUCCESS;
}
}
Upvotes: 1