Update beans (I18N) for a Spring MVC Webservice - java

I've a webservice written with Spring MVC for a webapp.
The user could change the locale and so the language of his page, so a call to my webservice is done with this information. For information, at startup, I load few beans for my webapp configuration. These beans attributes needs to be internationalize
My question is how can I update the values of my bean directly from a user call ?

There are two things here:
One is overall i18n architecture. At best Beans (controllers, models) should not contain any translatable texts, therefore no i18n work would need to be done to make them localizable. This is ideal situation which doesn't happen to often in practice.
Another is a way to make Controllers localizable. Again, there are two possible approaches: one is to use resource keys instead of strings, messages, etc. and resolve it in your View to real translation, just before displaying it to user, another is to make Controllers read these messages from resources - you said that you know Locale, so it could be done. If you are going with latter solution, you probably need to limit your Scope to request (as different users might want to use different languages and as far as I understand what you wrote users might want to change their language on the fly).

Related

Vaadin Session Management - How does it work?

At work, we develop a web application using Vaadin. I am a pretty advanced programmer in Java. I’m experienced with Vaadin as well. But now I've come to a point where information needs to be stored in a user session. Attributes like Locale, Username and so on.
In the Vaadin Documentation they are talking about two different types of sessions but I dont really get the difference:
VaadinServletService or VaadinPortletService described as low-level customization layer for processing requests.
VaadinSession of a UI with getSession() as lower-level session objects.
What is the difference and which one is to use when I want so store attributes during the whole UI independent user-session?
If in Vaadin 8, you have simple hierarchy of scope, on three levels.
ServletContextRepresents your entire Vaadin web app.
VaadinSessionRepresents each user's work session.
UIRepresents each web browser/tab within a session (Vaadin supports multi-window apps, pretty amazing).
The first is a standard part of every Java Servlet, defined in the spec.
The second is a wrapper around the session, also defined in the Java Servlet spec.
Vaadin is actually one huge Servlet, so it carries these features of context and session.
The UI class is unique to Vaadin. It represents the content of a web browser window/tab. Vaadin supports multi-window apps, tracking all the open windows/tabs as part of the session, a very nice feature of Vaadin.
To store state-wide app, use the standard ServletContext object. It carries a key-value collection known as "attributes". The key is of String type, and the value is of Object type. Call methods setAttribute, getAttribute, and removeAttribute. Use this collection for any objects you may need to access for any of your users, accoss their sessions. You may to learn about ServletContextListener by the way, to hook into your web app launching and exiting.
The VaadinSession class carries the same kind of key-value collection, with similar "attribute" methods. Use this to track items throughout the user’s work session, across them possibly opening/colsing multiple windows/tabs of your app. For example, in the session you would store the user’s Spirit Animal choice, their avatar image, and the fact that person has been authenticated via username/password credentials. See this page in the manual, Setting and reading session attributes.
If you want to store per-window settings, for something like their choice of background color or light/dark mode, store something on UI. Unfortunately, that class does not come with a convenient key-value store that I know of. So you'll need to add your own Map, or some other member variables to your UI subclass.
For more info, see my Answer to a similar Question. I made some nifty diagrams there. That question is about Vaadin 7, but as I vaguely recall, these concepts carry over between 7 and 8.
As for VaadinService and VaadinServletService, I have never understood exactly their role. They seem to represent various aspects of your entire Vaadin web at runtime. But neither carries a convenient key-value collection as like VaadinSession. (If you use Vaadin Flow, versions 10+, see VaadinContext, a class than does represent your entire web app, and does carry a convenient key-value collection of "attributes".)

Spring boot - Thymeleaf vs. JQuery?

I am new to JQuery, and so far I used it in side projects to add visual animations to the user interface. Since I always used Thymeleaf on the UI when writing a Spring Boot application, I was satisfied combining the two of them. The data from the user side goes through the Model via Thymeleaf, which is processed by the server, and then it injects the results in different objects back to the UI (via the Model again).
But now I started to simplify the process by using JQuery ajax queries, which have the benefit of getting rid of page refreshing, and also I don't have to use the model to inject the objects into every single page. (In case of Thymeleaf, even if a user decides not to change something on the page - like a form - an object still needs to be there - just in case - which will store their changes.)
The question is: Is that a good strategy to get rid of the Thymeleaf and using pure HTML+JQuery to do all the request+response work on the userinterface? I was wondering if there is any cons of it, as there are many people using thymeleaf to handle these stuff without JS, and maybe they have a good reason to do that way.
So after all I think I have found an answer for the question, by considering some important aspects just like:
Code Reusability
A big benefit of using a framework like Thymeleaf is that you can easily reuse the code what you have written - in case of TL - by using fragments. Creating the front-end in pure HTML+JQuery means every single page needs to have a separate .html, except if we build a single page application, but in that case using Angular would be much more efficient.
Security
Another aspect which I didn't take into consideration; Thymeleaf is compatible with Spring Security, also it has it's specific syntax which is hidden from the user at runtime. If a server is REST server (as it is in several cases when working with Spring boot) additional security needs to be implemented, what Thymeleaf can help with. (Additional security is mostly needed anyway)
So probably the best solution is to stay with Thymeleaf, using JQuery as a support on the interface (just like caching the data when using ajax, which Thymeleaf is not that good at, and also doing the visual bells and whistles) and let them work together.

Manage multiple models in multiple controllers to keep track on them

I was trying to make a simple application in javafx.
I had 8 views (FXML), so one model for each and same for the controllers.
I had to keep the "context" for each model wherever I was... So I had a function setContext which would take a parameter which is a class that regroup every models.
So in every controllers, I had every models.
But a bit latter, I had to had another page, which would take the result of all those page (questionnaire) and show it, so I could have multiple questionnaire... So I was facing the exact same problem, but I didn't want to do it all over again... Because as soon as I'm creating a new questionnaire, I lose the context of the previous one. I also had to add abstractModel and abstractController for stocking every models. It was ratchet.
So I gave up the idea of one controller for each view.
I ended up with a functionnal application, but with one controller which as over 1000 lines... it's only a questionnaire.
I was wondering if there were any possibilities to do what I attempt to do, with multiple controller, but where I don't need to set the "context"? Like... the pages/views auto-save somehow and won't re-instantiate if I'm not asking for it (like a new questionnaire would reset).
Sush as a static class, like a singleton, but for views and which I'm able to instantiate for every questionnaire. But then again, I keep a track on the old ones.
I'm pretty sure it's possible, but can't find anything about it maybe my formulation of the question is just wrong.
Any ideas? Thanks
Your question is bit abstract and it is hard to give a definitive answer. But you might benefit from introducing a dependency injection framework.
One way to do that would be to use Gluon Ignite: "With this library, developers can use popular dependency injection frameworks in their JavaFX applications, including inside their FXML controllers.". You can choose a dependency injection framework you wish from those supported (for example, Dagger, Guice or Spring). With those systems, you can apply scoping rules to your model classes such as Singleton, for those models for which you only wish to have a single instance for your application. You can also use other scoping rules and producers to create models that have different scopes such as within the context of a wizard or created new every time a form is shown, etc.
Beware that using dependency injection frameworks might make your application a little bit more difficult to understand. Anybody maintaining your application has to additionally learn the dependency injection framework. The framework will create objects and inject references to them into your code automatically and your application might be a bit more difficult to debug due to some seemingly magical generated operations that you don't control. Still, it's a tradeoff and, for medium sized applications, the gain in using dependency injection is probably worth it for a lot of apps. From the description you provided, your application may fall into this class, so you should probably seriously consider this approach.
Note that an alternate to a dependency injection system is a service locator (read about it in the Martin Fowler article on dependency injection that I linked earlier). A sample (extremely basic) version of a service locator would be the vista navigator in this small JavaFX navigation framework, though that doesn't pretend to be a full MVC system.
It's just that I can generate multiple questionnaires, which all have the same models and same views and same controllers. But when I create one, it instantiate everything, but it keeps track on all of them so I can edit them later
You could replace your in-memory structure for keeping track of stuff for editing with a persistent storage, for example a JPA based DB access layer or a NoSQL based DB access layer. One advantage of this could also be that the state of the application would be saved if the application is shut down, then restarted, so the user could just pick up where they left off in their questionnaire.

Single servlet to handle a single page web application design

I have a single page web application designed to look like a desktop application using plain Jsp/Servlet. In the back end I have one servlet with action param being passed for various actions occurs on the single web page. 90% of the requests are ajax. When the functionality grows on the single web page there will be more actions exist under single servlet. Now my questions are
having single servlet to manage a lot of operations a good design? What would be the better design?
What is the performance benefit when having single vs multiple servlet?
Will the servlet code be unmanageable at one point when it grows?
For company policy reasons I can't use the spring mvc..
having single servlet to manage a lot of operations a good design? What would be the better design?
No. A single class having basically all the responsibilities of your backend is not good design. Unless it only serves as a dispatcher to actions, but then you would reinvent the wheel that all the existing MVC frameworks have already invented for years (Spring MVC, etc.). Frankly, I would fight against the "company policy", and use the appropriate tool for the job: Spring MVC, or JAX-RS, or any other modern framework that can be used to easily implement a proper REST backend.
What is the performance benefit when having single vs multiple servlet?
None.
Will the servlet code be unmanageable at one point when it grows?
Yes. You'd better follow the REST principles and assign different URLs to your different actions instead of using a parameter to pass the action. Moreover, all actions should not use the same HTTP method. Searching or reading information should use GET, while creating stuff should use POST and updating stuff should use PUT.
And of course, use one servlet per URL.
you can use jsf
its a single servlet
called FacesServlet
--
jokes aside,
you could use a single servlet, and create multiple classes to handle different scenarios and keep your servlet class under 100 lines of code with good design
but this is essentially writing mvc yourself
REST is the right approach as suggested by JB Nizet. Use JAX-RS for handling the request. In case you don't want to take that route, you can use a single servlet but use the servlet like a controller that send the request to different modules to handle it. Single servlet is fine as long as you don't put all the code in the same class.
In case you use multiple servlets, the design would get better when you plan to move one of the servlets to a different server. But with multiple servlets, the UI (html or java script) needs to handle routing to the right servlet
Code will be unmanageble only if you write everything in one servlet class... If designed correctly it should be manageable.

When do you use a JSP and when a Servlet? [duplicate]

This question already has answers here:
What is the difference between JSF, Servlet and JSP?
(16 answers)
Closed 7 years ago.
I have an application that sends the customer to another site to handle the payments. The other site, outside of the customer, calls a page on our server to let us know what the status is of the payment. The called page checks the parameters that are given by the payment application and checks to see whether the transaction is known to us. It then updates the database to reflect the status. This is all done without any interaction with the customer.
I have personally chosen to implement this functionality as a JSP since it is easier to just drop a file in the file system than to compile and package the file and then to add an entry into a configuration file.
Considering the functionality of the page I would presume that a servlet would be the preferred option. The question(s) are:
Is my presumption correct?
Is there a real reason to use a servlet over a JSP?
What are those reasons?
A JSP is compiled to a servlet the first time it is run. That means that there's no real runtime difference between them.
However, most have a tradition to use servlets for controllers and JSPs for views. Since controllers are just java classes you can get full tool support (code completion etc.) from all IDEs. That gives better quality and faster development times compared to JSPs. Some more advanced IDE's (IntelliJ IDEA springs to mind) have great JSP support, rendering that argument obsolete.
If you're making your own framework or just making it with simple JSPs, then you should feel free to continue to use JSPs. There's no performance difference and if you feel JSPs are easier to write, then by all means continue.
JSPs: To present data to the user. No business logic should be here, and certainly no database access.
Servlets: To handle input from a form or specific URL. Usually people will use a library like Struts/Spring on top of Servlets to clear up the programming. Regardless the servlet should just validate the data that has come in, and then pass it onto a backend business layer implementation (which you can code test cases against). It should then put the resulting values on the request or session, and call a JSP to display them.
Model: A data model that holds your structured data that the website handles. The servlet may take the arguments, put them into the model and then call the business layer. The model can then interface with back-end DAOs (or Hibernate) to access the database.
Any non-trivial project should implement a MVC structure. It is, of course, overkill for trivial functionality. In your case I would implement a servlet that called a DAO to update the status, etc, or whatever is required.
JSPs should be used in the presentation layer, servlets for business logic and back-end (usually database layer) code.
I don't know any reason why you can't use a JSP as you describe (it gets compiled to a servlet by the containter anyway), but you're right, the preferred method is to make it a servlet in the first place.
There are 2 pretty simple rules:
Whenever you want to write Java code (business logic), do it in a Java class (so, Servlet).
Whenever you want to write HTML/CSS/JS code (view/template logic), do it in a JSP.
Related question:
How to avoid Java code in JSP
JSPs are a shortcut to write a servlet. In fact they are translated to servlet java code before compilation. (You can check it under some tomcat subdir wich I don't remember the name).
To choose between servlet an JSP I use a simple rule: if the page contains more html code than java code, go for JSP, otherwise just write a servlet. In general that translates roughly to: use JSPs for content presentation and servlets for control, validation, etc.
Also, Its easier to organize and structure your code inside a servlet, since it uses the plain java class syntax. JSPs tend to be more monolithic, although its possible to create methods inside then.
JSP's are essentially markup that automatically gets compiled to a servlet by the servlet container, so the compile step will happen in both instances. This is why a servlet container that supports JSP must have the full JDK available as opposed to only needing the JRE.
So the primary reason for JSP is to reduce the amount of code required to render a page. If you don't have to render a page, a servlet is better.
I know this isn't the popular answer today, but: When I'm designing an app from scratch, I always use JSPs. When the logic is non-trivial, I create ordinary Java classes to do the grunt work that I call from the JSP. I've never understood the argument that you should use servlets because, as pure Java classes, they are more maintainable. A JSP can easily call a pure Java class, and of course an ordinary Java class is just as maintainable as any servlet. It's easier to format a page in a JSP because you can put all the markup in-line instead of having to write a bunch of println's. But the biggest advantage of JSPs is that you can just drop them in a directory and they are directly accessible: you don't need to mess with setting up relationships between the URL and the class file. Security is easily handled by having every JSP begin with a security check, which can be a single call statement, so there's no need to put security into a dispatch layer.
The only reason I can see to use a servlet is if you need a complex mapping between URLs and the resulting execution class. Like, if you want to examine the URL and then call one of many classes depending on session state or some such. Personally I've never wanted to do this, and apps I've seen that do do it tend to be hard to maintain because before you can even begin to make a change you have to figure out what code is really being executed.
Most java applications nowadays are build on the MVC pattern...
In the controller side (servlet) you implement business logic. The servlet controller usually forward the request to a jsp that will generate the actual html response (the View in MVC).
The goal is to separate concerns... Thousands of books have been written on that subject.
In an MVC architecture, servlets are used as controller and JSPs as view.
But both are technically the same. JSP will be translated into servlet, either in compile time (like in JDeveloper) or when accessed for the first time (like in Tomcat).
So the real difference is in the ease of use. I'm pretty sure that you'll have a hard time rendering HTML page using servlet; but opposite to common sense, you'll actually find it pretty easy to code even a fairly complex logic all inside JSP (with the help of some prepared helper class maybe). PHP guys do this all the time. And so they fall into the pitfall of creating spaghetti codes.
So my solution to your problem: if you found it easier to code in JSP and it wouldn't involve too many code, feel free to code in JSP. Otherwise, use servlet.
Agreed with all the points above about the differences between JSPs and Servlets, but here are a couple additional considerations. You write:
I have an application that sends the
customer to another site to handle the
payments. The other site, outside of
the customer, calls a page on our
server to let us know what the status
is of the payment. The called page
checks the parameters that are given
by the payment application and checks
to see whether the transaction is
known to us. It then updates the
database to reflect the status. This
is all done without any interaction
with the customer.
Your application is consuming the payment service of another application. Your solution is fragile because if the payment service in the other application changes, that breaks your JSP page. Or if you want to change your application's payment policies, then your page will have to change. The short answer is that your application should be consuming the application's payment service via a web service. Neither a servlet nor a JSP page is appropriate place to put your consumption logic.
Second, along those lines, most usages of servlets/JSP pages in the last few years have been put inside the context of a framework like Spring or Struts. I would recommend Spring, as it offers you the full stack of what you need from the server pages to web service gateway logic to DAOs. If you want to understand the nuts and bolts of Spring, I would recommend Spring in Action. If you need to understand better how to tier an enterprise architecture written in a language like Java (or C#), I would recommend Fowler's Patterns of Enterprise Application Architecture.
Yeah, this should be a servlet. A JSP may be easier to develop, but a servlet will be easier to maintain. Just imagine having to fix some random bug in 6 months and trying to remember how it worked.
In java servlet the HTML tags are embeded in java coding.
In JSP the java codings are embeded in HTML tags.
For big application for big problem the servlet is complex to read,understand,debug,etc because of unreadability of embeding more html tags inside the java coding..So we use jsp.In jsp it is easy to understand,debug,etc.
Thanks & Regards,
Sivakumar.j
i think its up to you?
because
JSP is Java inside of HTML
and Servlet is a Java that can do the HTML inside
hmmm... servlet is more sercure than jsp because if you submit to Servlet and forward to another JSP there is no file extension appear and also you cant see what Page it is..
but the advantage of JSP is you can code there easily.

Categories