Is it possible to design an email using JSP to be sent through Spring 3.0's JavaMailSender mechanism? JavaMailSender probably has little to do with this question, but the idea is to take advantage of JSP's <fmt:message key="phrasetitle"/> internationalization mechanism, its variable/loop JSTL code and allow designers to easily hand me completed html emails.
Additionally, I could make a webpage that imports this JSP so that I can easily provide a link in each email to be able to view that email on the web in case their client doesn't see the html properly.
UPDATE: The 2 answers below suggest using Velocity for email instead of JSP, so it seems like that's the smart choice. However, just some quick scanning of stackoverflow suggests FreeMarker might be better suited for my needs. In particular I want to be able to have a JSP page which mirrors what's sent out in email. I'll have to translate the code from JSP to Velocity or FreeMarker, but the advantage FreeMarker gives me is I can reuse a lot of the JSP code, particularly taglibs. Does this make sense?
JSP is not a templating technology. For that for example Velocity is a better choice.
If you really insist in using JSP, then you have got to execute it locally by java.net.URL.
InputStream input = new URL("http://localhost:8080/context/mailtemplate.jsp").openStream();
There's some Spring documentation about using Velocity which will do what you want. I use it to handle emails in Spring and it works great.
What I typically do is to have an EmailService which which I call from a Controller whose job is to take care of sending emails. Methods within that accept a Command Object, which is accessed in the velocity template and rendered as a String (the email body). You can then use MailSender etc to send the mail.
Although I agree that Velocity or Freemarker may be a better choice, if you really need to render a JSP and capture the output as a String (which you could pass to a JavaMailer), check out my tutorial on Capturing JSP Output
It uses Spring 3, and also allows use of fmt:message, fmt:formatNumber, and spring:message. The idea is basically to use the RequestDispatcher.include method to render the page into a MockHttpServletRequest.
Related
I'm trying to secure my Spring MVC web app against cross-site scripting (XSS) attacks.
At first I thought I could simply set defaultHtmlEscape in my web.xml and be done. But I found that had no effect. As explained here -- Spring or App-Server escape html isn't working JAVA MVC, defaultHtmlEscape has no effect on INPUTS. It only sanitizes OUTPUTS within c:out tags.
So then I figured I'd write a filter to intercept requests, examine the parameters, and sanitize them as needed. But while looking into how to write the filter, I came across this -- XSS Filter to enctype="multipart/form-data" forms. It includes comments suggesting that filtering inputs is a bad idea, and that I should stick to filtering outputs.
Several posts mention HDIV and other third-party security solutions, but I'd rather not introduce a new third-party dependency to my project for something as basic as sanitization.
But filtering outputs seems inconvenient and error-prone. Are all the developers who touch my web app expected to remember to use c:out for EVERY output value on EVERY JSP page? Surely a global setting would be better? What's the best practice here?
Thanks in advance for your advice.
This is a big question. There is no easy or automatic way to do it. Every developer on your team should understand the basic aspects of this. The best practices are going to include input validation and output escaping.
Additionally, if you handle input that is expected to be html markup, you will have additional complications. AntiSAMY is a good place to go for that.
This article is a good place to start:
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
No there is no way in Spring MVC to sanitize user inputs.
However you can prevent XSS by setting defaultHtmlEscape to true in web.xml
Adding this will not sanitize data it will encode it, preventing XSS.
Refer to the link below for syntax
How do I prevent people from doing XSS in Spring MVC?
I am doing a Spring web application with many forms. A common practice when a form is successfully saved is saving a success message in session and then redirecting the user to the same or new link where the success message is displayed.
In Spring web, this can be done like the following:
request.getSession().setAttribute("successMessage", "Form saved successfully");
return "redirect:new_link";
I am hoping to make my application stateless but still follow the practice of redirecting and showing a form-save-success message. I am hoping to have an elegant solution. A simple (but I feel not elegant for a few reasons) solution is to attach the message as a string in the returned url similar to the following and let the front-end page to detect and display the message.
return "redirect:new_link?successMessage=Form-saved-successfully";
I think any idea or solution applies to any web applications, regardless of platforms used or programming languages.
Any input is really appreciated.
Thanks and regards!
Use the Post-Redirect-Get pattern
Use Flash Attributes to show Success/Failure messages on subsequent pages.
Assuming you use Spring 3.1 or up, then you can use flash attributes for that purpose. Define a method attribute of the type RedirectAttributes. The javadoc have a sample on how to use them.
Although this doesn't make your application stateless, it removes the direct couling to the session. (In theory you could implement your own FlashMapManager as the default still stores it in the session).
If you want a stateless solution either you need to put the message (or a message code) in the redirect URL or redirect to a specific 'Your-Form-Was-Saved' page which always shows the same message.
I am working on a web app, where a EXTJS makes an ajax call to a JSP, the JSP in turn calls a java class and then returns the value and updates something in the database.
now the question is, I somehow do not feel this is an effective way, I discovered about servets working and was wondering if should just make a Ajax call to the servlet instead of JSP. Are there any other ways which are better and optimized. Please explain.
Thanks,
SixthString
You're right - a Servlet is better suited for situations like there where all you really need is data from a web end point. The purpose of JSP technology is presentation, there really shouldn't be any business logic in a JSP if you can help it. JSPs are usually employed as the V in MVC (Model-View-Controller) - a design pattern that advocates separating the presentation from the control and business logic. So in theory, if you did everything just right, you would be able to swap out one view for another with minimal work since the view just presents the information.
Do note that JSPs are eventually compiled into Servlets themselves so the issue isn't one of a technical limitation but more of a good design/programming practice.
It depends on what you want returned form your Ajax call. JSP is used for generating formatted HTML. If that's what you're looking to get from the Ajax call, then JSP could be the right choice.
If you're looking for some raw data, then you might as well skip the JSP template and go straight to the servlet. I recommend using JSON in this case, because it's easy to work with in JavaScript.
I was reading about JSF that it's a UI framework and provides some UI components. But how is it better or different from number of components that are available from jQueryUI, AngularJS, React, Vue.js, Svelte, ExtJS, or even plain HTML, CSS and JavaScript.
Why should someone learn JSF?
JSF to plain JSP/Servlet/HTML/CSS/JS is like as jQuery to plain JS: do more with less code. To take PrimeFaces (jQuery + jQuery UI based) as an example, browse through its showcase to see complete code examples. BootsFaces (jQuery + Bootstrap UI based) has also a showcase with complete code examples. If you study those examples closely, then you'll see that you basically need a simple Javabean class as model and a XHTML file as view.
Note that you should not see JSF as replacement of alone HTML/CSS/JS, you should also take the server side part into account (specifically: JSP/Servlet). JSF removes the need of all the boilerplate of gathering HTTP request parameters, converting/validating them, updating the model values, executing the right Java method to do the business stuff and generating the HTML/CSS/JS boilerplate code. With JSF you basically end up with a XHTML page as view definition and a Javabean class as model definition. This greatly speeds up development.
As with every component based web MVC framework, you have in JSF less fine-grained control over the rendered HTML/CSS/JS. Adding custom JS code isn't that easy as you have to take the JSF view state in the server side into account as well (e.g. enabling a disabled button in JS side won't enable the button in JSF side, which is in turn a huge security advantage). If that is however a major showstopper, then rather look for an action based web MVC framework like Spring MVC. You'll only take into account that you have to write all that HTML/CSS/JS code (and prevention against XSS, CSRF and DOM-manipulation!) yourself. Also if you fall back from Facelets to JSP, you'll miss advanced templating capabilities as well.
On the other hand, if you have a big JSP/Servlet/HTML/CSS/JS/jQuery based website and you'd like to refactor the repeated JSP/Servlet/HTML/CSS/JS/jQuery boilerplate code into reusable components, then one of the solutions would be JSF. Custom templates, tagfiles and components can aid in this. In that perspective, JSF stands above JSP/Servlet/HTML/CSS/JS/jQuery (and that's also why it's pretty important to understand those basics before diving into JSF).
You can find a real world kickoff JSF based project here: Java EE Kickoff App. You'll see that it contains next to JSF as good HTML5, CSS3 and jQuery.
See also:
Difference between Request MVC and Component MVC
Difference between JSP, Servlet and JSF
What are the main disadvantages of JSF 2.0?
Is it possible to use JSF+Facelets with HTML 4/5?
When to use <ui:include>, tag files, composite components and/or custom components?
JSF was created to make it so that java shops didn't have to learn stuff like jQuery and build complex JS but instead focus on a purely Java stack. In a world where time is money and lots of places already focusing on Java development, one less language/piece in the stack makes training and maintaining faster and thus cheaper.
I'll add that JavaScript is easy to become a maintenance nightmare on large teams, especially if some of the developers on the project are not highly web savvy.
With Javascript and frameworks such as jQuery you have full flexibility and full control . With ext's etc you lose much control and must adapt to the framework. With JSF you totally lose control and must totally adapt to the framework. You're invoked in lifecycles etc. and finally you have no control when the call to the server can be made and where not. If you are to do something considered 'special', you're in very hard position. And in JSF world even such basic things as multicolumn table sort or fields where you can type only limited set of characters (such as number field) are considered 'special'.
However, the more flexibility you have, the more errors or bad practices you can made. High flexibility works only with highly intelligent programmers, others will turn the project into unmanagable nightmare.
But, with JSF and its limited flexibility, there's always only a few (or even only one) correct way to do something. You are very limited, you can't make shortcuts, you must write more XML etc. - but when adapting to standard, there's better control on the code the unexperienced or low-skilled programmers will produce. As a result, big corporations love JSF because it is 'safer' for them.
When I moved from GWT to JSF, I was shocked, how many things, that was natural to me, was considered highly untypical and how much simple things were so hard to achieve. What's more, even making the smallest changes, such as adding ':' sign after label, which in GWT/jQuery powered app would be changing one function generating label, required changing dozens of files with localized properties, which wasn't even considered by anyone except me strange...
The benefits of using JSF are not only in generating xhtml + css + js. Sometimes JSF imposes a restriction on the markup you can generate, like any component based framework. But JSF is not just for that, its lifecyle helps greately. After validating the input it can update the model and sync your server side beans without any effort. you just say "whatever the user types here, check if it's a number, if yes then store it in the property YY in object XX" and JSF will do all that.
So yes, you can still use JQuery, JS, etc. But JSF provides many benefits when it comes to writing server side code and saves you from a lot of boiler plate.
I strongly disagree that jsf adds anything. It only adds overhead. Doing ui stuff on the server is the most ridiculous thing ive ever heard. And javascript on large teams works great - its called reusing code.
Just wrap the jquery in some jsp tags, thats all you need and youre done, and dont endure the.shackles and scalability issues with.jsf and richfaces.
Having worked with JSF, Spring MVC, Struts, Grails, JQuery, and ExtJS my opinion is that Grails + ExtJS is one powerful combination.
I would pick Grails over JSF any day. I like the completeness of ExtJS as the client side framework and library, but it comes with a steeper learning curve than JQuery.
Here are the biggest differences between jQuery & JSF:
no MVC architecture
no state control (store date in session or conversation, auto-clean up, etc.)
no (default) validation library
no templating library
no advanced navigation/routing
client side
jQuery was never intended to be used as a full stack webframework. It was more intended for replacing low-level JS code so that writing JS becomes easier and more powerfull in less lines of code.
And it should thus mostly be used to add behaviour on HTML elements.
Having used ExtJS framework for a large web application, I know how easy it is to use. The ExtJS (Schena) is best suited for (Oracle 11g) database interactions in MVC architecture. The View was for the visual / user interactions. The controller specified the 'processing' and the triggers that needed to be used form the PLSQL packages (the API for the CRUD, SQL select queries etc.). The Model and the store files were used to 'map' the data items to the Viewer / inputs.
ExtJS is not suitable for non database intensive web interfaces - where Angular JS may be a better fit.
I am trying to find the optimal architecture for an ajax-heavy Django application I'm currently building. I'd like to keep a consistent way of doing forms, validation, fetching data, JSON message format but find it exceedingly hard to find a solution that can be used consistently.
Can someone point me in the right direction or share their view on best practice?
I make everything as normal views which display normally in the browser. That includes all the replies to AJAX requests (sub pages).
When I want to make bits of the site more dynamic I then use jQuery to do the AJAX, or in this case AJAH and just load the contents of one of the divs in the sub page into the requesting page.
This technique works really well - it is very easy to debug the sub pages as they are just normal pages, and jQuery makes your life very easy using these as part of an AJA[XH]ed page.
For all the answers to this, I can't believe no one's mentioned django-piston yet. It's mainly promoted for use in building REST APIs, but it can output JSON (which jQuery, among others, can consume) and works just like views in that you can do anything with a request, making it a great option for implementing AJAX interactions (or AJAJ [JSON], AJAH, etc whatever). It also supports form validation.
I can't think of any standard way to insert ajax into a Django application, but you can have a look to this tutorial.
You will also find more details on django's page about Ajax
Two weeks ago I made a write up how I implement sub-templates to use them in "normal" and "ajax" request (for Django it is the same). Maybe it is helpful for you.
+1 to Nick for pages displaying normally in the browser. That seems to be the best starting point.
The problem with the simplest AJAX approaches, such as Nick and vikingosegundo propose, is that you'll have to rely on the innerHTML property in your Javascript. This is the only way to dump the new HTML sent in the JSON. Some would consider this a Bad Thing.
Unfortunately I'm not aware of a standard way to replicate the display of forms using Javascript that matches the Django rendering. My approach (that I'm still working on) is to subclass the Django Form class so it outputs bits of Javascript along with the HTML from as_p() etc. These then replicate the form my manipulating the DOM.
From experience I know that managing an application where you generate the HTML on the server side and just "insert" it into your pages, becomes a nightmare. It is also impossible to test using the Django test framework. If you're using Selenium or a similar tool, it's ok, but you need to wait for the ajax request to go return so you need tons of sleeps in your test script, which may slow down your test suite.
If the purpose of using the Ajax technique is to create a good user interface, I would recommend going all in, like the GMail interface, and doing everything in the browser with JavaScript. I have written several apps like this using nothing but jQuery, state machines for managing UI state and JSON with ReST on the backend. Django, IMHO, is a perfect match for the backend in this case. There are even third party software for generating a ReST-interface to your models, which I've never used myself, but as far as I know they are great at the simple things, but you of course still need to do your own business logic.
With this approach, you do run into the problem of duplicating code in the JS and in your backend, such as form handling, validation, etc. I have been thinking about solving this with generating structured information about the forms and validation logic which I can use in JS. This could be compiled at deploy-time and be loaded as any other JS file.
Also, avoid XML. The browsers are slow at parsing it, it is a pain to generate and a pain to work with in the browser. Use JSON.
Im currently testing:
jQuery & backbone.js client-side
django-piston (intermediate layer)
Will write later my findings on my blog http://blog.sserrano.com