Java Spring + ReactJs - java

There is this typical traditional JAVA Spring + JSP application that I am working on. It's a full fledged working application with more than 50 pages. The client feels its slower and wants to make it faster by using ReactJs for new pages. From performance point I understand his concerns. Now I am not a JAVA expert and I am new to ReactJS but i have worked on AngularJs(SPA) applications extensively before.
Right now the way the application works is when we call a url say http://example.com/mycontroller/myaction.do, the app maps the url to certain controller and action in a JAVA controller.
#RequestMapping(value = "/mycontroller/myaction.do", method = RequestMethod.GET)
public ModelAndView myfunction(HttpServletRequest request, HttpServletResponse response) throws IOException {
ModelAndView mav = new ModelAndView("myJSPPage");
mav.addObject("pageDetails", myPageDetails);
return mav;
}
Once the action gets executed the html page is rendered in the browser along with server data and jQuery takes care of the UI part.
Now speaking of ReactJs,
React is just a UI, Lots of people use React as the V in MVC.
Which comes to my questions:
Can i use React in Java JSP Pages and access Java variables in React ?
If not what are other options/ways to use React with these kind of applications.
If its not possible to use React in current application, do i need to write the whole application from scratch using React. What are the challenges i might face?

Yes. Its possible to pass the Java objects and lists to your javascript application using Nashorn which comes bundled with java 8.
Second option is to do the rendering on client and fetch the required data using ajax/websockets.

I believe sticking to using JSP’s along with React won’t benefit you much in terms of performance. Because the main benefit of using SPA’s is that you don’t need to re-render the whole web page when some data changes or when actions are dispatched.
If performance is your main concern then I encourage you to implement a React application (the V) and make Spring your controller (the C) and make them communicate JSON objects (the M (data)).

Related

Understanding the flow of spring framework & MVC

I am having some trouble understanding this. Can someone help me better understand this?
MVC
Model --> Java- Spring Framework
View ---> templating language(JSP velocity) & Javascript
DB --> SQL
Q-1)
Now, When I open a particular page, I can't visualize the flow. I've read about DAO, controller , service etc and I understand them individually but I am really confused when I club all together what's the order of execution? Whats the flow exactly ? Is it that first the view is loaded then it sends JS request to fetch the necessary data from backend and then the controller and service are invoked and the DAO queries the db? Then how does the API come into picture? DAO deals with the API?
Q-2)
Why do we need xyz.properties? I have removed a module from my page. If I remove a particular js file(related to that module) from the scripts.properties, then ideally that js should not get executed at all right? Then still why would I see the api call to fetch the data related to that module? I don't see the module but I sure see the api call. Why is that?
DB doesn't enter in MVC model. And you're forgetting a principal element in your analysis: the Controller. The flow goes like this:
Client performs a request to an URL
The application server gets the URL and passes the handling to the web application.
The web application using Spring MVC will handle the URL processing to the Controller: DispatchServlet, which is a Servlet.
The DispatchServlet will try handle the URL. If there's an URL mapping, then it will pass it to the class (mapped in the spring.xml config or decorated with #Controller annotation).
This controller (which in fact is part of the model) will handle the request. It will call services, daos, etc (Model) and return the necessary data to complete the response to the DispatchServlet.
The DispatchServlet will finish the request handling and, in the end, will generate the results e.g. a text/json response, or it will forward to a JSP file (View).
For question two, I never have used such scripts.properties file, so I don't know what you're talking about. Usage of a properties file is to store application properties that should not change until an application redeploy. They have 3 main advantages:
They can be easily manipulated by human users. It's no rocket science to add, edit or remove values.
Since it is a plain text, it's easier to version using a version control system like SVN, Git or another of your preference.
It provides a faster access since it is usually in the same disk as the application, so there's no much time penalty when accessing to its contents compared to a database configuration. But since it is in disk, it still has a disadvantage against RAM access only.
In simple layman's term, MVC explained in pictorial form
(inputing data) (data related part) (display rendering)
-request mapping -classes -JSP (Script,CSS,HTML)
-request param -interface -velocity
Controller ------------->Model--------------->View
||
\/
(data processing logic) (access to Databse)
-optimization -JDBC
-business logic -SQL
Service--------------------->DAO

AJAX with Spring MVC

What AJAX libraries work well with Spring MVC?
I'm new to developing with Spring and Spring MVC. From the documentation at http://www.springsource.org I'm not yet understanding what AJAX framework Spring MVC has built-in or what third party APIs and tooling might be suggested as working well with developing a Spring MVC application.
All recommendations are appreciated.
I did search through previous SO discussions on this subject, but I didn't get any clear direction.
Spring is super easy to use with Ajax. If Jackson is on the classpath Spring can use it for returning JSON to the caller. Something like this:
#RequestMapping( "/my/path" )
public #ResponseBody MyObject doSomething( #RequestParam Long myVal ) {
MyObject result = new MyObject( myVal );
// do something interesting
return result;
}
Then you can use jQuery (or your other favorite javascript library) to make a request to http://myserver/my/path and handle the resulting JSON object.
Google's GSON is also easy to use. As in:
#RequestMapping( "/my/path" )
public ResponseEntity<String> MyObject doSomething( #RequestParam Long myVal ) {
MyObject result = new MyObject( myVal );
// do something interesting
HttpHeaders headers = new HttpHeaders();
headers.set( "Content-Type", "application/json" );
String json = gson.toJson( result );
return new ResponseEntity<String>( json, headers, HttpStatus.CREATED );
}
Please go through the following link. It clearly explains how it needs to be done.
http://blog.springsource.org/2010/01/25/ajax-simplifications-in-spring-3-0/
Here is another approach to let Spring MVC to work with ZK UI components - Rich Web Application with Spring MVC CRUD Demo
In that article, it used Spring MVC controller to communicate with ZK UI components. (all in Java code)
Spring JS has support of Dojo JavaScript framework.
Spring Js
Spring doesn't deal with Javascript frameworks, per se. I don't know if Springsource does any advocacy for any particular Javascript framework or whether they are agnostic. Ajax is really just a technique enabled by browser technology in combination with the Javascript language and what matters is the ability to pass some kind of serialized data between client and server. It isn't that difficult to cook up your own basic AJAX framework and you could even design your own data encoding and not use JSON or XML. It is wise to adopt an existing framework and standards because you don't want to maintain a lot of ancillary code or worry about it, and instead focus on the problem you are trying to solve. So that is why there are many Javascript frameworks out there that can do asynchronous requests and some have some really nice features and capabilities that make your life easier, for example jQuery provides excellent DOM manipulation and browser-neutral functionality. I think that using Spring MVC in conjunction with the Jackson JSON library on the server side, and jQuery on the client side, is the basis for a very decent end-to-end solution. I have had a lot of success with jQuery and jQuery-UI, but other Javascript frameworks can work just as well. For complex applications, you basically end up needing what amounts to a second MVC on the client side because you need that breakdown between UI widgets and the data that has to move between client and server.

passing response object from java to javafx.( Desktop application )

Im am planning on creating a desktop application with JavaFX. I would like to use JavaFX only for the UI, and all backend work should be done by java(with spring).Im not sure how to develop the frontend to call the service layer, and also receive the response and display the response on the next page.
Basically I need to know the following(just an example of want i want to accomplish).
1) to call the controller class I would do something like below in 'Login.fx'?
function btnLoginAction(): Void {
var loginController = LoginController {};
loginController.authenticateUser(txtboxUsername.text.trim(), pwdboxPassword.text.trim());
}
2) LoginController would be my java class and would call the service layer. after authentication, i would want to call another page('Welcome.fx') and pass the firstname of the logged-in user as a parameter. How do I accomplish this?
Im new to javafx(java gui development as a whole), hence let me know if there is a better approach to go about this, and some links to help me better understand.
NOTE: I am using javafx 1.3.
You can use java classes from javafx, e.g. the way you suggested is correct.
To achieve that you can just add a parameter to Welcome class and set it during creation/accessing with value received from LoginController instance.
P.S.: but I really suggest you to move to JavaFX 2.0. JavaFX 1.3 script language is not supported unfortunately, so no new functionality would be accessible.

How do I implement a front controller in Java?

I'm writing a very simple web framework using Java servlets for learning purposes. I've done this before in PHP, and it worked by consulting the request URI, then instantiating the appropriate class and method.
This worked fine in PHP, as one can do something like $c = new $x; $x->$y;. I'm unsure however of how to translate this to Java, or even if this is an appropriate way to go about it.
So far, I've tried:
Router router = new Router(request.getPathInfo());
String className = router.route(); //returns com.example.controller.Foo
Class c = Class.forName(className);
Object x = c.newInstance();
Foo y = (Foo) x;
y.doSomething();
This seems fine for a couple of routes, but doesn't seem like it would scale well, nor would it allow for sourcing routes from a configuration file.
How should I make it work?
Get hold of actions in a Map<String, Action> where the String key represents less or more a combination of request method and request pathinfo. I've posted similar answer before here: Java Front Controller
You can fill such a map either statically (hardcoding all actions) or dynamically (convention over configuration, looking up classes in a certain package, or scanning the entire classpath for classes with a certain annotation or implementing a certain interface).
And just stick to Servlet. The Filter isn't there for. At highest use it to forward the request to the controller Servlet. In the Servlet, just implement HttpServlet#service().
I would use a Servlet Filter as Front Controller. The router would connect paths with request dispatchers. In the doFilter method you would convert ServletRequest to HttpServletRequest, extract the request path and match it against the registered mappings. The result of this mapping is a request dispatcher you would dispatch the request with.
In pseudo code:
doFilter(ServletRequest request, ServletResponse response) {
httpServletRequest = (HttpServletRequest) request;
path = httpServletRequest.getRequestURI();
dispatcher = router.getTarget(path);
dispatcher.dispatch(request, response);
}
Depending on your need the default routing mechanism of the Servlet API could be sufficient.
Not quite sure what you're after but you might want to take a look at Java servlets. Granted many web frameworks are abstracted above plain servlets, but it's a jolly good place to start learning about Java web apps if you ask me (which indirectly you did ;) )
Download the Java servlet specification here: Java Servlet Spec - it's quite interesting.
How should you make it work? However you want it to. If you're just doing it for learning purposes, whatever you do will be fine.
I would suggest having all your actions implement the same interface though (maybe extend Servlet) so that you don't have to compile in all different classes.
Then you can essentially do what you're doing, except that your cast to Foo becomes a cast to Servlet and then you don't have to have a special case for all your different classes.
You can then also load up the routes from configuration (maybe an XML file).
Essentially what you're doing is implemented by the Struts 1 framework so it might be worthwhile reading up on that (it's open-source so you can also look at the source if you want).

Simple Java stand-alone server container/framework?

For the last couple of years I've had my head in Python, where there are numerous choices for simple, minimal frameworks that allow me to stand up a website or service easily (eg. web.py). I'm looking for something similar in Java.
What is the simplest, least-moving-parts way of standing up simple services using Java these days? I'm looking for something as simple as:
the ability to receive HTTP requests
the ability to dispatch those requests to handlers (preferably a regular expression based url to handler mapping facility)
the ability to set HTTP headers and generally fully control the request/response
Bonus points if the framework plays well with Jython.
[Update] Thanks for the responses, some of these look quite interesting. I'm not seeing the url dispatch capability in these, however. I'm looking for something similar to Django's url.py system, which looks like:
urlpatterns = patterns('',
(r'^articles/2003/$', 'news.views.special_case_2003'),
(r'^articles/(\d{4})/$', 'news.views.year_archive'),
(r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
(r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
)
Where you specify a url regular expression along with the handler that handles it.
I liked to worth the Simple HTTP Server from the Simple Framework. It offers a nice Tutorial about how to start as well.
there are several alternatives:
servlets
restlet: lightweight REST framework
jax-rs: using jersey or the restlet module implementing the jax-rs specs
grizzly: NIO based server (with HTTP support + handlers)
apache mina: event-driven, async server (with HTTP support)
all these frameworks come with a built-in server.
EDIT
jax-rs has a similar approach using url templates:
#Path("/users/{username}")
public class UserResource {
#GET
#Produces("text/xml")
public String getUser(#PathParam("username") String userName) {
}
}
then put your handlers in an Application object:
public class MyApplicaton extends Application {
public Set<Class> getClasses() {
Set<Class> s = new HashSet<Class>();
s.add(UserResource.class);
return s;
}
}
another example with JAX-RS:
#GET
#Produces("application/json")
#Path("/network/{id: [0-9]+}/{nid}")
public User getUserByNID(#PathParam("id") int id, #PathParam("nid") String nid) {
}
EDIT 2
Restlet supports a centralized configurations like Django, in your Application object:
// Attach the handlers to the root router
router.attach("/users/{user}", account);
router.attach("/users/{user}/orders", orders);
router.attach("/users/{user}/orders/{order}", order);
Servlets might be the way to go. To do very simple things you only need to override one method of one class. More complicated stuff is of course possible, but you can go a long way with a little work.
Investigate Tomcat or Jetty - both are open source and well supported.
public class HelloWorldServlet extends HttpServlet {
public void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
response.setContentType( "text/plain" );
PrintWriter out = response.getWriter();
out.print( "hello world!" );
}
}
Note: This is more general discussion than answer.
I'm having similar issues coming from Python for 10+ years and diving, as it were, back into Java. I think one thing I'm learning is that the "simplicity" factor of Python is very different from that of Java. Where Python abounds with high-level framework-- things like web.py, Java seems much more lower level. Over the past few months, I've gone from saying "What's the Java way to do this easy in Python thing" to "How does one build up this thing in Java." Subtle, but seems to bring my thoughts around from a Python-centric view to a more Java-centric one.
Having done that, I've realized that standing up a website or service is not simple for a Java outsider, that's because there's a large amount of info I have to (re)grok. It's not as simple as python. You still need a webserver, you need to build a "container" to drop your Java code into, and then you need the Java code (am I wrong on this, everyone? Is there a simpler way?).
For me, working with Scala and Lift has helped- and not even those, but this one thread by David Pollack. This was what I needed to build a Jetty server. Take that, follow the directions (somewhat vague, but might be good enough for you) and then you have a servlet container ready to accept incoming traffic on a port (or 3 ports, in his case). Then you can write some Java code using HTTPServlet or something to go the rest of the way.
Again, this is just what I did to get past that barrier, but I'm still not a Java guru. Good luck.
I've hard about: Apache Mina
But quite frankly I don't even know if it is what you need.
:-/
:)
Jetty is a pretty nice embedded http server - even if it isn't possible to do the mapping like you describe, it should be pretty easy to implement what you are going for.

Categories

Resources