JSF-SPRING-HIBERNATE architecture- Backing bean related best practice - spring

I am developing a web project and after much research I have decided to go ahead with JSF+Primefaces, Spring and Hibernate approach. While designing the architecture of my project I have finalized the following approach :
Actor --> JSF+PrimeFaces page --- > Backing Bean -- > Service Bean -- > Dao -- > Hibernate
Service Bean and DAO are spring beans with dependency injection.
My concern now is now with respect to backing bean:
I plan to use multiple backing beans for UI page depending upon the type of Page I need to render.
Now for example: For a new user registration page i have UserProfile.xhtml which uses UserBackingBean. UserBackingBean has UserServiceBean injected by spring. UserServiceBean has UserDao injected by Spring.
Now in UserBackingBean when the user enters the form data from UserProfile.xhtml I will have to populate the User.java domain(ORM) object.
a) What is the best practice for this ? Should I initilize the User.java in the constructor on UserBackingBean ? Is this the proper approach ? Please suggest if there is any other way out ?
b) Also please suggest on the above architecture I have decided upon for my project ? Is it the proper approach ?

The general rule I follow is that transaction boundaries are marked in the service beans therefore I don't like to modify hibernate POJO outside of a service because I don't know if there is a transaction already running. So from the backing bean I would call the service layer pass in the parameters that the service layer needs to build up the hibernate pojo and save it, update it, ... etc.
Another way to do this would be have your backing bean implement an interface defined by the service layer and then pass the backing bean to the service layer. For example.
public interface UserInfoRequest {
public String getName();
}
#Service
public class SomeSpringService {
#Transactional(.....)
public void registerNewUser(UserInfoRequest request)
{
}
}
public class SomeBackingBean implements UserInfoRequest {
private SomeService someSpringService;
public void someMethodBoundToSJF()
{
this.someSpringService.registerNewUser(this);
}
}
Regarding your last question I am not a fan of JSF, I think JSF is fundamentally flawed because it is a server component based framework. So my argument against JSF is a generic argument against server side component based frameworks.
The primary flaw with server side component based frameworks is that you don't control what the component will output which means you are stuck with the look of the component, if you want something that looks different you have to write your own component or you have to modify an existing component. Web browsers are currently evolving very quickly adding new features which can really improve the quality of an application UI but to you those features you have to write HTML, CSS, and JavaScript directly and the server side components make that harder.
Client side component architectures are here and much better than doing components on the server side. Here is my recommend stack.
Client Side Architecture:
jquery.js - Basic libary to make all browser look the same to JavaScript
backbone.js + underscore.js - High level client side component based architecture
handlebars.js - for the client side templates
Twitter bootstrap - to get a decent starter set of CSS & widgets
You write code in HTML, CSS and JavaScript organized as backbone views that talk to server side
models using AJAX. You have complete control over the client side user experience with enough
structure to really make nice reusable code.
Server Side Architecture:
Annotation Driven Spring MVC, Services and Dao (#Controller, #Service, #Repository)
Spring component scanning with autowiring by type (#Autowired, #Inject)
AspectJ Load Time Weaving or Compile Time Weaving
Hibernate
Tomcat 7
JSP as the view technology for Spring MVC (yes it cluncuky but you wont be creating
too many jsp pages, mostly for usng <% #inculde > directive
Tooling:
- Spring Tool suite
- JRebel (so that you don't have to start and stop the server) it really works really worth the money
- Tomcat 7

Related

Difference between #Controller and RouterFunction in Spring 5 WebFlux

There are two ways to expose HTTP endpoints in spring 5 now.
#Controller or #RestController by making the controller's class, e.g.
#RestController
#RequestMapping("persons")
public class PersonController {
#Autowired
private PersonRepo repo;
#GetMapping("/{id}")
public Mono<Person> personById(#PathVariable String id){
retrun repo.findById(id);
}
}
Route in #Configuration class by using RouterFunctions:
#Bean
public RouterFunction<ServerResponse> personRoute(PersonRepo repo) {
return route(GET("/persons/{id}"), req -> Mono.justOrEmpty(req.pathVariable("id"))
.flatMap(repo::getById)
.flatMap(p -> ok().syncBody(p))
.switchIfEmpty(notFound().build()));
}
Is there any performance difference in using anyone approach? Which one should I use when writing my application from scratch.
Programming Paradigm: Imperative vs Functional
In the case with the #Controller or #RestController annotations, we agree with the annotation-based model where we use annotations for mappings (and not only) and as a result side effects (that is not allowed in the functional world) to make our API works. Such side effects could be #Valid annotation that provides inbuilt bean validation for requests' bodies or #RequestMapping with the root path for the whole controller.
On the other hand, with the router functions, we get rid of annotations that consist of any side effects in terms of API implementation and delegate it directly to the functional chain: router -> handler. Those two are perfectly suited for building the basic reactive block: a sequence of events and two protagonists, a publisher and a subscriber to those events.
MVC Legacy: Servlets Stack vs Netty Stack
When we are talking about #Controller I would say that we usually will think in term of synchronous Java world: Servlets, ServletContext, ServletContainerInitializer, DispatcherServlet etc. Even if we will return Mono from a controller to make our application reactive we still will play in terms of Servlet 3.0 specification that supports java.nio.* and running on the same servlets containers such as Jetty or Tomcat. Subsequently, here we will use corresponding design patterns and approaches for building web apps.
RouterFunction on the other hand was inspired by the true reactive approach that originates from the async Java world - Netty and its Channel Model.
Subsequently new set of classes and their APIs for reactive environment emerged: ServerRequest, ServerResponse, WebFilter and others. As for me, they were designed by the Spring team in accordance with the previous years of maintaining the framework and understanding new web systems requirements. The name for those requirements is Reactive Manifesto.
Use Case
Recently my team faced the issue that it is impossible to integrate Swagger with RouterFucntion endpoints. It could upvote for #Controlers, but the Spring team introduced their solution - Spring REST Docs that could be easily connected to reactive WebTestClient. And I use here word 'connected' cause it follows true reactive meaning behind: instead of Swagger with its overloaded configurations and side-effect annotations, you easily could build your API docs in tests without touching your working code at all.
Update 2020: Despite since now Spring Webflux already could be integrated with Swagger subsequently using OpenAPI specification, it still lacks configuration simplicity and transparency that, in my humble opinion, is the consequence of being a part of the archaic MVC approach.
Closure (opinion)
Cause of no performance impact it's likely to hear something similar to 'it is absolutely based on individual preference what to use'. And I agree that it's individual preference indeed among two options: moving forward or moving backwards when you let yourself stay in the same domain for a decade. I think that reactive support for #Controller was done by the Spring team to make it possible for old projects to somehow be in tune with requirements of time and have at least the opportunity for the migration.
If you are going to create a web application from scratch then do not hesitate and use the introduced reactive stack.
Though it's a bit late, but this may be useful for future readers.
By switching to a functional route declaration:
you maintain all routing configuration in one place
you get almost the same flexibility as the usual annotation-based approach in terms of accessing incoming request parameters, path variables, and other important components of the request
you get an ability to avoid the whole Spring Framework infrastructure being run which may decrease the bootstrapping time of the application
Regarding point 3, there are some cases where the whole functionality(IoC, annotation processing, autoconfiguration) of the Spring ecosystem may be redundant, therefore decreasing the overall startup time of the application.
In the era of tiny microservices, Amazon Lambdas, and similar cloud services, it is important to offer functionality that allows developers to create lightweight applications that have almost the same arsenal of framework features. This is why the Spring Framework team decided to incorporate this feature into the WebFlux module.
The new functional web framework allows you to build a web application without starting the whole Spring infrastructure. The main method in that case should be somewhat like the following(note, there is no #SpringBootApplication annotation)
class StandaloneApplication {
public static void main(String[] args) {
HttpHandler httpHandler = RouterFunctions.toHttpHandler(
routes(new BCryptPasswordEncoder(18))
);
ReactorHttpHandlerAdapter reactorHttpHandler = new ReactorHttpHandlerAdapter(httpHandler);
HttpServer.create()
.port(8080)
.handle(reactorHttpHandler)
.bind()
.flatMap(DisposableChannel::onDispose)
.block();
}
static RouterFunction<ServerResponse> routes(PasswordEncoder passwordEncoder ) {
return
route(
POST("/check"),
request -> request
.bodyToMono(PasswordDTO.class)
.map(p -> passwordEncoder
.matches(p.getRaw(), p.getSecured()))
.flatMap(isMatched -> isMatched
? ServerResponse
.ok()
.build()
: ServerResponse
.status(HttpStatus.EXPECTATION_FAILED)
.build()
)
);
}
}

How to make Interaction with GWT - Spring RestTemplate

This is the continuation of issue
I'm currently working on a task where it has GWT, Restful and Spring Framework environment.
It has two application; Application #1 which expose some information through Restful Webservice and Application #2 which consume that service and display those details in GWT.
For Application #2, I have used Spring RestTemplate to consume the Restful Webservice and return backs the List of Details through an Interface. And at the GWT end, there was some DataListProvider to set the Data List in GWT-DataGrid.
Now the problem is, I doesn't know how to make the interaction with GWT DataListProvider with my DetailService Class(this returns the List<Details> in a method). When I directly call the Service Class in GWT- OnModule() method, during GWT Compile, i'm facing some UnResolved Type Error, Since this class indirectly calls the Spring Libraries classes, thus GWT cannot compile this.
com.google.gwt.dev.jjs.InternalCompilerException: Failed to get JNode
at com.google.gwt.dev.jjs.impl.TypeMap.get(TypeMap.java:140)
at com.google.gwt.dev.jjs.impl.TypeMap.get(TypeMap.java:71)
at com.google.gwt.dev.jjs.impl.BuildTypeMap.getType(BuildTypeMap.java:730)
at com.google.gwt.dev.jjs.impl.BuildTypeMap.createField(BuildTypeMap.java:570)
at com.google.gwt.dev.jjs.impl.BuildTypeMap.access$300(BuildTypeMap.java:99)
at com.google.gwt.dev.jjs.impl.BuildTypeMap$BuildDeclMapVisitor.visit(BuildTypeMap.java:180)
at org.eclipse.jdt.internal.compiler.ast.FieldDeclaration.traverse(FieldDeclaration.java:285)
at org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.traverse(TypeDeclaration.java:1232)
at org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.traverse(CompilationUnitDeclaration.java:687)
at com.google.gwt.dev.jjs.impl.BuildTypeMap.createPeersForNonTypeDecls(BuildTypeMap.java:637)
at com.google.gwt.dev.jjs.impl.BuildTypeMap.exec(BuildTypeMap.java:514)
at com.google.gwt.dev.jjs.impl.BuildTypeMap.exec(BuildTypeMap.java:523)
at com.google.gwt.dev.jjs.JavaToJavaScriptCompiler.precompile(JavaToJavaScriptCompiler.java:599)
at com.google.gwt.dev.jjs.JavaScriptCompiler.precompile(JavaScriptCompiler.java:33)
at com.google.gwt.dev.Precompile.precompile(Precompile.java:284)
at com.google.gwt.dev.Precompile.precompile(Precompile.java:233)
at com.google.gwt.dev.Precompile.precompile(Precompile.java:145)
at com.google.gwt.dev.Compiler.run(Compiler.java:232)
at com.google.gwt.dev.Compiler.run(Compiler.java:198)
at com.google.gwt.dev.Compiler$1.run(Compiler.java:170)
at com.google.gwt.dev.CompileTaskRunner.doRun(CompileTaskRunner.java:88)
at com.google.gwt.dev.CompileTaskRunner.runWithAppropriateLogger(CompileTaskRunner.java:82)
at com.google.gwt.dev.Compiler.main(Compiler.java:177)
[ERROR] <no source info>: public class org.springframework.web.client.RestTemplate
extends org.springframework.http.client.support.InterceptingHttpAccessor
implements : Unresolved type org.springframework.web.client.RestOperations
Please provide your suggestion how to make an interaction between these Service Class and GWT.
You cannot have Spring in client side code.
Options available are:
A callback in a presenter where an asynchronous interface makes a GWT-RPC call to a service controller (on server-side of App#2). You could have an #RequestMapping annotated method whose internals employ the RestTemplate.
Have the presenter employ a RequestFactory and make use of GWT overlay feature for your payload.

Using a Stateful Session Bean to track an user's session

it's my first question here and I hope that I'm doing it right.
I need to work on a Java EE project, so, before starting, I'm trying to do something simple and see if I can do that.
I'm stuck with Stateful Session Beans.
Here's the question :
How can I use a SFSB to track an user's session?
All the examples that I saw, ended up in "putting" the SFSB into a HttpSession attribute.
But I don't understand why!
I mean, if the bean is STATEFUL, why do I have to use the HttpSession to keep it?
Isn't an EJB Container's task to return the right SFSB to the client?
I've tried with a simple counter bean.
Without using the session, two different browsers have the same counter bean (clicking on "increment" changed the value for both of them).
Using session, I have two different values, each for every browser (clicking on "increment" on Firefox, added one just to Firefox's bean).
But my teacher told that a SFSB keeps the "conversational state with a client", so why it doesn't just work without using a HttpSession ?
If I understood correctly , isn't using HttpSession with a SFSB the same of doing it with a SLSB instead?
I hope that my question(s) is clear and that my English is not that poor!
EDIT :
I'm working on a login system.
Everything goes fine and after completing the login it takes me to a profile page that show user's data.
But reloading the page makes my data disappear!
I've tried adding HttpSession while logging but doing in this way makes the data stay even after the logout!
A Stateful Session Bean (SFSB) has to be combined with the HTTP session in a web environment, since it's a pure business bean that itself knows nothing about the web layer.
Traditionally EJBs even mandatory lived inside their own module (the EJB module), that couldn't even access web artifacts if they wanted to. This is an aspect of layered systems. See Packaging EJB in JavaEE 6 WAR vs EAR for more information about that.
The original clients for Stateful Session Beans were among others Swing desktop applications, that communicated with the remote EJB server via a binary protocol. A Swing application would obtain a connection to a remote Stateful Session Bean via a proxy/stub object. Embedded in this proxy is an ID of some kind that the server can associate with a specific SFSB. By holding on to this proxy object, the Swing client can make repeated calls to it and those will go to the same bean instance. This will thus create a session between the client and the server.
In the case of a web application, when a browser makes an initial request to a Java EE web application it gets a JSESSIONID that the server can associate with a specific HTTPSession instance. By holding on to this JSESSIONID, the browser can provide it with each followup request and this will activate the same http session server-side.
So, those concepts are very similar, but they do not automatically map to each other.
The browser only gets the JSESSIONID and has no knowledge about any SFSB ID. Unlike the Swing application, the browser communicates with web pages, not directly with Java beans.
For mapping the client's request to a specific stateful session bean, the EJB container only cares about the ID provided via the SFSB proxy. It can't see if the call happened to originate from code in the web module and can't/shouldn't really access any HTTP contexts.
The web layer being the client code that accesses the SFSB must 'hold on' to a specific proxy reference. Holding on to something in the web layer typically means storing it in the HTTP session.
There is however a bridge technology called CDI that can make this automatic connection. If you annotate your SFSB with CDI's #SessionScoped and obtain a reference to the SFSB via CDI (e.g. using #Inject), you don't have to manually put your SFSB into the http session. However, behind the scenes CDI will do exactly that anyway.
You need to define the bean with #SessionScoped instead of #RequestScoped (if you are looking for HttpSession equivalent solution)
something like
#SessionScoped
public class SessionInfo implements Serializable{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Have a look at following (explained in detail)
http://www.oracle.com/technetwork/articles/java/cdi-javaee-bien-225152.html

ASP.NET MVC Views Dependency Injection without DependencyResolver?

Is it possible to inject dependencies into an MVC ViewPage (must support layout pages) without using DependencyResolver?
I would rather not use DependencyResolver at all (I had major problems when injecting NH sessions into ActionFilters in the past (leaking all over the place)). However, I'm not sure if there is an alternative?
The other complexity I have is that the DependencyResolver needs to be tenant aware (each tenant has its own (StructureMap) container). I'm currently doing this by passing in a lazy instance of my tenant container resolver (seems this is necessary otherwise the resolver is cached):
public SmDependencyResolver(Func<ISiteContainerResolver> containerResolver)
{
this.containerResolver = containerResolver;
}
public object GetService(Type serviceType)
{
var container = containerResolver().Resolve();
If I end up using DependencyResolver should I ditch my StructureMap controller factory since it looks like DependencyResolver handles this too?
Thanks
Ben
Given that the DependencyResolver is used by so many aspects of the ASP.NET MVC framework for dependency injection your life will be easier if you use it - as you say it means you don't need your own versions of things like the controller factory.
That said, the framework is very flexible and it is always open for you to plug in your own version of things - I just prefer to create as little of my own code as possible on the KISS principle.

Validation framework for business app built on Spring 2.5

What could the best strategy for writing validation layer for mid-enterprise level business application built on Spring 2.5
I know that Spring provides facility where we can implement Validator interface and write validation logic in validate method. But this will be restricted to only web requests coming through spring controller.
I would like to develop the validation framework which can be utilized during web-services calls.
In other words, the framework can remain and be called independently without the need of implementing Validator interface and then too it can be automatically integrated into Spring MVC flow.
Hope you get my point.
The Spring Validation framework can be used outside of Spring MVC. What WebServices Stack are you using? If you are using Spring-WS (Spring's Web Services stack) they have special instructions on how to set up the validator here:
http://static.springframework.org/spring-ws/sites/1.5/reference/html/server.html#d0e2313
If you are using some other stack, it is probably easier to implement something for that stack (or find one) that will use Spring's validation framework.
Recall that the Validator interface defines two methods:
boolean supports(Class clazz)
void validate(Object target, Errors errors)
The Object target is your form object, which is the whole object representing the page to be shown to the user. The Errors instance will contain the errors that will be displayed to the user.
So, what you need to do is define an intermediary that can be called with the specifics in your form that you want to validate which are also the same as in your web service. The intermediary can take one of two forms:
(probably the best):
public interface ErrorReturning {
public void getErrors(Errors errors);
}
(this can get ugly really fast if more than two states are added):
public interface ValidationObject {
public Errors getErrors(Errors errors);
public Object getResultOfWebServiceValidation();
}
I would suggest that the first approach be implemented. With your common validation, pass an object that can be used for web service validation directly, but allow it to implement the getErrors() method. This way, in your validator for Spring, inside your validation method you can simply call:
getCommonValidator().validate(partialObject).getErrors(errors);
Your web service would be based around calls to getCommonValidator().validate(partialObject) for a direct object to be used in the web service.
The second approach is like this, though the interface only allows for an object to be returned from the given object for a web service validation object, instead of the object being a usable web service validation object in and of itself.

Resources