Spring JSF application flow - spring

I have previously written Spring MVC web applications where there is a front controller and we have a request mapping in each of the methods and this method in turn invokes a service implementation finally returning a view to the UI. Now when I design JSF applications am not able to understand the flow as such -
This is what I currently have in my application:
The initial index.html redirects to the login page.
A backing bean for the login page which populates label values. Since it is an input form there is no other logic involved.
Once the user clicks on submit -> in the action method I have logic which will invoke the service(No.1) for authentication process and redirect the user to the home page by returning the name of the page
The home page displays various fields which are bound to a backing bean whose fields have to be populated by another web service call(No.2).
It is between the steps (3) and (4), I have a confusion. Previously in Spring I had an explicit mapping and I can "actually" control the logic in the front controller method. In JSF, I dont know whether the logic for No.2 web service call should be combined along with authentication call since I dont have a method to populate the beans.
It is as if I dont have the explicit control over the flow. I have read many articles trying to understand this but not am able to understand. Please provide me pointers and also some references which will actually explain this better.

Why can't you control the logic in JSF bean?Example usage with EJB
#ManagedBean
#RequestScoped
public class LoginBean {
#EJB
private AuthBean authBean;
#EJB
private UserSettings settingsBean;
private String name, password;
#PostConstruct
private void init() {
//do your initialization here
}
public String loginAction() {
User user = authBean.authenticate(user, password);
if(user != null) {
UserSetting settings = settingsBean.getSettings(user.getId());
return "home";
}
}
//setters and getters
}

Related

Access other service's API

In our Angular + Spring boot application application, we have 2 Controllers (2 Services are internally referenced). In first controller, We are sending a File from UI and reading the content of the file , query an external application and retrieve a set of data and return only a sub-set of Data, for entering as recommendation for UI fields. why we are returning only sub-set of data received from the external application? Because, we need only those sub-set data for showing recommendations in UI.
Once the rest of the fields are filled, then, we call another controller to generate a report. But, for generation of files, the second service requires the rest of the data from external application, which is received by the first service. I understand that Autowiring the first service in the second service, will create new instance of the first service and I will not get the first service instance, which is used to query the external application. I also like to avoid calling the external application again to retrieve the same data again in the second service. My question is how to fetch the data received by the first service in the second service?
For example:
First controller (ExternalApplicationController), which delegates loading of loading/importing of data from files
public class Department{
private Metadata metadata; // contains data such as name, id, location, etc.,
private Collection<Employee> employees; // the list of employees working in the department.
}
#RestController
#RequestMapping("/externalApp")
public class ExternalApplicationController{
#Autowired
private ExternalApplicationImportService importService;
#PostMapping("/importDepartmentDataFromFiles")
public Metadata importDepartmentDataFromFiles(#RequestParam("files") final MultipartFile[] files) {
return this.importService.loadDepartmentDetails(FileUtils.getInstance().convertToFiles(files)).getMetadata();
}
}
The first service (ExternalApplicationImportService), which delegates the request to the external application for loading of department data.
#Service
public class ExternalApplicationImportService{
private final ExternalApp app;
public Department loadDepartmentDetails(File file){
return app.loadDepartmentDetails(file);
}
}
The Metadata from the ExternalApplicationController is used to populated UI fields and after doing some operations (filling up some data), user requests to generate a report(which contains details from the employees of that department)
#RestController
#RequestMapping("/reportGenerator")
public class ReportController{
#Autowired
private ReportGenerationService generationService;
#PostMapping("/generateAnnualReports")
public void generateAnnualReports(){
generationService.generateAnnualReports();
}
}
#Service
public class ReportGenerationService{
public void generateAnnualReports(){
//here I need access to the data loaded in the ExternalApplicationImportService.
}
}
So, I would like to access the data loaded in the ExternalApplicationImportService in the ReportGenerationService.
I also see that there would be more services created in the future and might need to access the data loaded in the ExternalApplicationImportService.
How can this be designed and achieved?
I feel that I'm missing something how to have a linking between these services, for a given user session.
Thanks,
Paul
You speak about user session. Maybe you could inject the session of your user directly in your controllers and "play" with it?
Just adding HttpSession as parameter of your controllers' methods and spring will inject it for you. Then you just have to put your data in the session during the first WS call. And recover it from the session at the second WS call.
#RestController
#RequestMapping("/reportGenerator")
public class ReportController{
#PostMapping("/generateAnnualReports")
public void generateAnnualReports(HttpSession session){
generationService.generateAnnualReports();
}
}
Alternatively for the second call you could use:
#RestController
#RequestMapping("/reportGenerator")
public class ReportController{
#PostMapping("/generateAnnualReports")
public void generateAnnualReports(#SessionAttribute("<name of your session attribute>") Object yourdata){
generationService.generateAnnualReports();
}
}
You are starting from a wrong assumption:
I understand that Autowiring the first service in the second service, will create new instance of the first service and I will not get the first service instance, which is used to query the external application.
That is not correct: by default, Spring will create your bean as singleton, a single bean definition to a single object instance for each Spring IoC container.
As a consequence, every bean in which you inject ExternalApplicationImportService will receive the same instance.
To solve your problem, you only need a place in where temporarily store the results of your external app calls.
You have several options for that:
As you are receiving the same bean, you can preserve same state in instance fields of ExternalApplicationImportService.
#Service
public class ExternalApplicationImportService{
private final ExternalApp app;
// Maintain state in instance fields
private Department deparment;
public Department loadDepartmentDetails(File file){
if (department == null) {
department = app.loadDepartmentDetails(file);
}
return department;
}
}
Better, you can use some cache mechanism, the Spring builtin is excellent, and return the cached result. You can choose the information that will be used as the key of the cached data, probably some attribute related to your user in this case.
#Service
public class ExternalApplicationImportService{
private final ExternalApp app;
#Cacheable("department")
public Department loadDepartmentDetails(File file){
// will only be invoked if the file argument changes
return app.loadDepartmentDetails(file);
}
}
You can store the information returned from the external app in an intermediate information system like Redis, if available, or even in the application underlying database.
As suggested by Mohicane, in the Web tier, you can use the http sessions to store the attributes you need to, directly as a result of the operations performed by your controllers, or even try using Spring session scoped beans. For example:
#RestController
#RequestMapping("/externalApp")
public class ExternalApplicationController{
#Autowired
private ExternalApplicationImportService importService;
#PostMapping("/importDepartmentDataFromFiles")
public Metadata importDepartmentDataFromFiles(#RequestParam("files") final MultipartFile[] files, HttpSession session) {
Deparment department = this.importService.loadDepartmentDetails(FileUtils.getInstance().convertToFiles(files));
session.setAttribute("department", department);
return deparment.getMetadata();
}
}
And:
#RestController
#RequestMapping("/reportGenerator")
public class ReportController{
#Autowired
private ReportGenerationService generationService;
#PostMapping("/generateAnnualReports")
public void generateAnnualReports(HttpSession session){
Department department = (Department)session.setAttribute("department");
// Probably you need pass that information to you service
// TODO Handle the case in which the information is not present in the session
generationService.generateAnnualReports(department);
}
}
In my opinion, the second of the proposed approaches is the best one but all are valid mechanisms to share your data between the two operations.
my recommendation for you will be to revisit your design of classes and build a proper relationship between them. I feel you need to introduce the extra logic to manage your temporal data for report generation.
#Mohicane suggested to use HTTP Session in above answer. It might be a possible solution, but it has an issue if your service needs to be distributed in the future (e.g. more than one runnable instance will serve your WEB app).
I strongly advise:
creating a separate service to manage Metadata loading process, where you will have load(key) method
you need to determine by yourself what is going to be a key
both of your other services will utilize it
this service with method load(key) can be marked by #Cacheable annotation
configure your cache implementation. As a simple one you can use In-Memory, if a question becomes to scale your back-end app, you can easily switch it to Redis/DynamoDB or other data storages.
Referances:
Spring Caching
Spring Caching Guide

Spring sending user to a view when no view is being requested

I have written a book catalog in Spring.
It collects books (pdf, epub, mobi, ebook) from a directory, collects some metadata from them, stores them in a DB and then puts them in a List that is made available to my views:
#Slf4j
#Controller
public class BookCatalogController {
// == Fields ==
private final BookService bookService;
#Autowired
public BookCatalogController(BookService bookService){this.bookService = bookService; }
// == Model attributes ==
#ModelAttribute
public List<Book> bookData(){ return bookService.getBooksFromMemory(); }
public static final File bookDirectory= new File("D:\\edu_repo\\ebooks_test\\");
.
.
.
// Catalog Simple View
#GetMapping(Mappings.CATALOG_SIMPLE)
public String catalogSimple(Model model){
log.info("catalogSimple method called");
// This is adding the entire BookManager book list into the model.
model.addAttribute(AttributeNames.BOOK_DATA, bookData());
return ViewNames.CATALOG_SIMPLE;
}
// Catalog Detail View
#GetMapping(Mappings.CATALOG_DETAIL)
public String catalogDetail(Model model){
log.info("catalogDetail method called");
// This is adding the entire BookManager book list into the model.
model.addAttribute(AttributeNames.BOOK_DATA, bookData());
return ViewNames.CATALOG_DETAIL;
}
.
.
.
#GetMapping(Mappings.LOAD_BOOKS)
public void loadBooks(Model model) {
bookService.loadBooksFromDirectory(bookDirectory);
}
}
Obviously I'm not using #GetMapping(Mappings.LOAD_BOOKS) properly as you can see in the error below:
The error:
There was an unexpected error (type=Internal Server Error, status=500).
Error resolving template [load-books], template might not exist or might not be accessible by any of the configured Template Resolvers
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [load-books], template might not exist or might not be accessible by any of the configured Template Resolvers
How does one invoke a method like I am doing but without Spring trying to redirect the user to another view?
I'm not expecting the page to update at all since I'm not returning a View!
When you click a link in your browser with a load-books anchor, your browser sends it to the server and waits for result, which causes your page to be reloaded. Once the request to a load-books endpoint reached to the server, Spring MVC handles this and starting to looking up an appropriate controller with its method. It founds public void loadBooks(Model model) in your case. When Spring MVC invokes the method, it expects to obtain a view name to resolve and return back to your browser.
Since you haven't provided a View or String as a return type, Spring MVC used the endpoint's path as a view name (I'm not seeing your Mappings.LOAD_BOOKS constant, but it supposed to be load-books).
If you're not going to return any view back to the browser, you can annotate the method like that:
#GetMapping(Mappings.LOAD_BOOKS)
#ResponseBody
public void loadBooks(Model model) {
which tells Spring to treat void as a response body.
But it's not preventing a page refreshing, you'll just see an empty page after clicking the link. In order to fix this you can redirect a user to another page by returning the following string (without ResponseBody annotation on the method)
return "redirect:/path-to-redirect";
When Spring MVC sees this prefix it redirects you to another controller, but user going to notice that too.
If you really don't want to see a blank page for a moment, you'll have to use some JavaScript to perform AJAX request to the server when button is clicked.
Actually, it seems that you want to preload some files in a service by a given path. If it's all you want to do, you can use Spring's runners like that:
#Component
class Preloader implements ApplicationRunner {
private final BookCatalogService bookService;
#Autowired
public Preloader(BookCatalogService service) {
this.bookService = service;
}
#Override
public void run(ApplicationArguments args) throws Exception {
bookService.loadBooksFromDirectory(BookCatalogController.bookDirectory);
}
}
Spring automatically calls all registered runners when application is ready, so your code will be executed without having a user to visit load-books endpoint.

Best Practices for Struts 2 CRUD

So I've found a bunch of Struts 2 CRUD examples around the web:
Struts 2 CRUD Demo
and a few books:
Apache Struts 2 Web Application Development ISBN: 978-1847193391
Struts 2 Design and Programming ISBN: 978-0980331608
But all of them differ a little bit on how to do form population.
Some suggest implementing the Java interfaces ModelDriven or Prepareable to call come prepare function to pre-populate any needed data members.
Others suggest creating your own PrepareForUpdate action that calls a pre-populate function then redirects to the main edit view.
They also very on how to pass around an object identifier to indicate what object to retrieve for editing. SOme suggest intercepters what others throw it in the URL parameters and retrieve it through ActionContext or pass it around through a s:hidden field.
Is there a Best Practices way to do form population in Struts 2?
What are the advantages/disadvantages to the methods mentioned above?
I'm not aware of any documented best practices, but I've been using Webwork and Struts2 for about three years now, so I can tell you what I've used in my projects. By the way, the CRUD demo documentation you linked to strikes me as a bit out of date (I realize its from the project site).
I split my CRUD work into three different actions:
An action that lists the entities. It supports pagination and populates some type of a table or grid view.
An action that handles both add and edit functionality. Uses a prepare() method to set up dropdowns, etc.
An action that handles delete functionality.
Some suggest implementing the Java interfaces ModelDriven or Prepareable to call come prepare function to pre-populate any needed data members.
That's the approach that I would advocate, although I don't use the ModelDriven interface. For details, check out how Struts2 ModelDriven interface works and the comments on my answer. Whether you use ModelDriven or not is just a personal choice. Also, check out why is model-driven action preferred over object backed bean properties.
Others suggest creating your own PrepareForUpdate action that calls a pre-populate function then redirects to the main edit view.
I have not seen that before and based on your description, I would avoid that technique. It seems wasteful to do a redirect and create an additional HTTP request to achieve the same thing that the prepare() method was designed to handle.
They also very on how to pass around an object identifier to indicate what object to retrieve for editing.
Just pass the identifier in the URL or the form. That's the standard approach for web applications.
I've been using Struts 2 for about 3 years. I use ModelDriven and Prepareable together in the same action. Each domain object (model) has a struts action class that returns a list or single object depending on if the id was passed to the action. This works pretty well for me, and the only time it's been problematic is when using Ajax. I usually separate my Ajax actions into a separate action for the model, if I am using them. I store the model id, as well as any related objects that I might need as hidden HTML fields in the view.
Using this approach, the action and the view are restful. You can leave the page for a long period of time and invoke the action without fear that the action will fail. Here's an example:
public class ApplicationAction extends MyBaseAction
implements ModelDriven<Application>, Preparable {
private static final long serialVersionUID = 7242685178906659449L;
private ApplicationService applicationService;
private Application application;
private Integer id;
List<Application> allApplications;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Application getModel() {
return application;
}
public void prepare() throws Exception {
if(id == null || id.intValue() == 0){
application= new Application();
}else{
application= applicationService.getApplication(id);
}
}
#SkipValidation
public String list() throws Exception {
allApplications = applicationService.getApplications();
return SUCCESS;
}
#Validations( visitorFields = {#VisitorFieldValidator(message = "Validation Error", fieldName = "model", appendPrefix = false)})
public String update() throws Exception {
applicationService.saveApplication(application);
addActionMessage("Application Saved Successfully.");
return SUCCESS;
}
public void setApplicationService(ApplicationService applicationService) {
this.applicationService = applicationService;
}
public List<Application> getAllApplications() {
return allApplications;
}
}

JSF: Showing page while backingBean is still working

maybe this title is not really precise, but here's the problem.
I'm doing some JSF project and I need a following:
When user logs on my application (ie. when he navigates to Home page), a method, which gets some money exchange rates from the internet and/or database, needs to be called. The execution of that method (page parsing, data saving etc.) lasts about 5-6 seconds. I don't want that navigation from Login to Home page lasts 5-6 seconds, i want one of these (didn't decide which one yet) to happen:
1) When user logs in, he sees Home page (immediately, not after 5-6 seconds) and is able to click and/or navigate while method is working in background.
2) When user logs in, he sees Home page (immediately), some loading sign in one part of the page and after method is executed, he sees dataTable with exchange rates.
Question is, how to do any of this?
If I put that method in HomePageBean constructor, page wont be displayed until method is executed. Maybe i can put some invisible element on Home page and call that method within some Getter, but i don't know if that's the right way to do (seems like hack) or will it actually work.
I'm using JSF 2.0 and Primefaces.
Thanks in advance
Use ApplicationScoped bean like in example below:
#ManagedBean(name = "exchRateBean", eager = true)
#ApplicationScoped
public class ExchRateBean {
public List<Rate> getRates(Date date) {
// cached data or DAO methods here
}
#PostConstruct
public void init() {
// Initial web-app initialization, will run once upon deploy
}
}
And here is your backing bean accessing application-scoped bean.
#RequestScoped
public class MyBean {
#ManagedProperty(value="#{exchRateBean}")
private ExchRateBean exchRateBean;
// your JSF methods
public List<Rate> getRates(Date date) {
return getExchRateBean().getRates(date);
}
// G&S
public ExchRateBean getExchRateBean() {
return exchRateBean;
}
public void setExchRateBean(ExchRateBean exchRateBean) {
this.exchRateBean = exchRateBean;
}
}

Struts2 - Session Troubles

I make (thanks with some users on this portal) my application that implements SessionAware.
This is my actual code :
public class UserManager extends ActionSupport implements SessionAware {
private Map<String, Object> session;
#Override
public String execute() throws Exception {
return SUCCESS;
}
public void setSession(Map<String, Object> map) {
this.session=map;
}
public String checkLogin() {
session.put("loggedOn", true);
return SUCCESS;
}
public String checkLogout() {
session.clear();
return SUCCESS;
}
}
And i check these variables on my .jsp :
<s:if test="#session['loggedOn']!=true">
DIV LOGIN
</s:if>
<s:else>
DIV LOGOUT
</s:else>
An easy piece of code.
What i'd like to know is this :
1 - the bean is (as default) request scoped. So when the request is finished it will be destroyed. But i see that, when i put a variable in the Map, it still alive on the server. How is possible? Is a variable of my Bean.
2 - Who call the setSession method? I think the servlet, due to the fact I implements that interface?
3 - I would like to detach about saving object/bean on a Session Object. I'd like to use the Bean session scoped (as for any kind of MVC framework). How can I do it on struts2?
Hope you can make clear these questions :) Cheers
1) Your bean is a struts2 action as such it is action scoped (which is a more restrictive scope than request). I say that action is a lesser scope because you can forward an action to another action in which case the previous action goes out of scope, request scoped objects however will stay in scope until the request is served. When you implement SessionAware you are provided with a reference to the SessionObject you are then putting your object into the Session object who's life span is much longer than your action. Clear your browser cache will remove the session value... you can also remove them by code be implementing SessionAware and removing the value from the map.
2 - The session already exists. You can get the session and add keys but even if you don't put anything in it, it will be there for use.
3 - You have a later question already for this topic see my answer there.

Resources