Migrating app to AngularJS? - java

i have existing web application where most of the time pages are submitted traditional way(like document.form.submit or )
I am planning to migrate to angularJS which i am learning. I am not sure how we can submit form in traditional way (without ajax) with angularJS ?
I know it won't be true Single Page App(SPA), but for starting i would like to go this way.
Approach for migrating traditional app to SPA :-
In future , i would like to go for SPA in which i will submitting the form thru ajax way using AngularJS. I have vague understanding
how will i approach this but would like to get experts advice on this.
My Understanding:-
Say i land to welcome page with a link for customer creation. I will make the ajax call from WelcomeController(angularJS Controller) to my servlet/spring controller
which will return html response containing js file. HTML response will be conatining below
1)HTML will be containing ng-view and ng-template which will be used by routeProvide
2)One of the js files will be containing routeProvider Info to map the ng-template with view
Please correct me if this is right approach ?

Use AngularJS for data-binding and form-validation. When you want to submit a form, you can rely on jQuery:
<div ng-controller="ctrl">
<form id="myform" name="myform">
Name: <input type="text" ng-model="person.name" name="person.name" /> <br />
<button ng-click="submit(person)">Submit</button>
</form>
</div>
Script
app.controller('ctrl', function($scope) {
$scope.submit = function(person) {
if ($scope.myform.$valid) {
$('#myform').submit();
}
}
});
For this to work, make sure you give your input fields properly scoped names so that it binds to your MVC models.
This approach does have its limitations. For example, input fields that use ngModel should not have any $formatters/$parsers which limits you to simple formats.

I was exactly looking for Single Page App with AngularJS which describes how you can have full fledged SPA web app using AngularJS(with features like router,controller,service etc) in a clear and succinct way

Related

Stripe Checkout Charge using JSF: Form being submitted twice

The form is being submitted twice:
1. On Page Load
2. When user clicks on Checkout's button
I want to avoid the first submission, it is throwing an error because the token returned is null:
com.stripe.exception.InvalidRequestException: Invalid source object: must be a dictionary or a non-empty string. See API docs at https://stripe.com/docs'; request-id: req_DjRbT4rGULYGnB
Following the documentation I added the following code to my XHTML:
<div>
<form submit="#{studentBean.chargeStudent()}" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_xxxxxx"
data-amount="111"
data-name="myApp"
data-description="Example charge"
data-zip-code="true"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto">
</script>
</form>
</div>
Here is my Managed Bean's function:
#Named
#ViewScoped
public class StudentBean implements Serializable {
#EJB
StripeChargeLogic stripeChargeLogic;
public void chargeStudent(){
Map<String,String> requestParams = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
logger.info("charge:" + requestParams.get("stripeToken"));
stripeChargeLogic.chargeStudent(requestParams.get("stripeToken"));
}
}
Can someone please guide me why the form is being submitted twice and how I can prevent the submission during page load Thank you!
You are not doing jsf here, you have plain html, most likely (but mot clear from you post) in an xhtml/facelets file but not JSF.
In your form action you have an EL that, since it all is in no way related to jsf, is called on page load, sort of like what hapens here
The rest of the behaviour is even more 'undefined' because of this. Take a step back and learn the basics of web technology and jsf and then look at your problem again

Filling out a HTML-form with complex name (dot-notation in input-tag) with Java and Jaunt API

-
hey folks,
i am building a Java-tool, trying to automatically fill out some form input elements in an HTML-Page using Java and Jaunt API.
the HTML-Code is like:
<fieldset class = "fieldsetlong">
<legend>searchprofile</legend>
<label for="reference">reference:</label>
<input maxlength="50" name="reference" id="reference" type="text" />
</fieldset>
<fieldset class = "fieldsetlong">
<legend>searchcriteria</legend>
<label for="surname">surname:</label>
<input name="searchprofile.surname" id="surname" type="text" />
</fieldset>
The Java-Code for filling in the "normal" Input-field reference (it works) looks like:
form.set("reference", "123Test");
Unfortunately, I am not able to fill out the fields that use the dot-notation searchprofile.surname in the name
Here's a sample of what i've tried (without success):
form.set("surname", "TestPerson");
form.set("searchprofile.surname", "TestPerson");
form.set("name=\"searchprofile.surname\"", pers.getSurname());
form.set("id=\"surname\"", pers.getSurname());
For each of these commands I get a NotFoundException and don't know whether I can do this with Jaunt.
It would appreciate any kind of help in this regard.
Thanks in advance
Edit - is there a way to reach the dot-notated input-field searchprofile.surname with JSoup?
HTML allows dots in the name-Attribute, but does Jaunt accept this abc.name?
Not sure about Jaunt, never used it before. However Jsoup seems to be a pretty decent library to be used here. I myself have been using Jsoup for a fairly long time and it has been very successful in scraping web pages, filling input form and submit, and of course, HTML parsing!
I've posted a step by step guide to fill in form input fields and submit to server in the following answer: How to login with Jsoup
Basically it works very similar to your code, a very brief example would be:
Connection.Response response = Jsoup.connect(url)
.data("Name", "Value")
.method(Method.POST).execute();
Today, at work the Jaunt solution with
form.set("searchprofile.surname", "TestPerson");
worked like a charm.
I don't know what the problem was earlier but I am glad that it worked.
The HTML allows to use dots and minus, etc. which I misinterpreted as some kind of nested forms or hierarchies but the dot-notation is just a valid name-attribute in HTML.

JSF and Javascript and HTML - How to create a highly dynamic interface

I'm new to JSF and developing web applications with Java.
I'm basically developing a pretty complex interface, with lots of AJAX content loaded (Pagination, posts, comments, ...).
I'll start with a basic example, a user writes a comment. The form is sent through JSF f:ajax to the server and then I can do a render="sectionId", but the problem is, that I want to make the post not just appear, but slide down and even toggle background color.
How can I obtain this sort of effect using JSF and Javascript?
The designer (who knows only HTML/CSS/Javscript/Jquery) says that usually, he just does a Jquery AJAX call to a page with a string of data and then the page generates a JSON encode that he can then use to do all the magic.
I'm not asking how you do the toggle/color in jquery, it's the communication between the JSF and Javascript. So how can I send to his javascript the newly generated HTML code, so that he can what he wants with it.
Thanks for any help.
JSF is a server-side technology and you'd typically conditionally display content within
a construct such as a panelGroup, so why not include your jquery magic inside a ready
handler inside the conditionally rendered panelGroup like this:
<h:panelGroup id="ajaxRenderTarget">
<ui:repeat value="#{bean.listOfComments}" var="var">
... display required information ...
</ui:repeat>
<h:panelGroup rendered="#{bean.showJqueryEffects}">
<script type="text/javascript">
jQuery(function($) {
... funky effects here ...
});
</script>
</h:panelGroup>
</h:panelGroup>
Where I've used ui:repeat in the above example you could be and probably would be using any data iteration component from jsf or a component library such as a datatable.
Another thing to consider is OmniFaces which has <o:onloadScript> and a host of other tags which are worth knowing about.
One mistake to avoid is trying to load JSF pages using jQuery ajax functions, the server will have no state of the component tree and it won't work.

Spring MVC upload file and send parsed data back

I'm using Spring MVC for my web application. I'm implementing the file upload functionality. Following the tutorial, I was able to send the uploaded file to server through submit action of input type of "file". Then I parsed the uploaded xls file at server side and need to send parsed data (3 lists of custom objects) back to the same form to display. I sent the data back through ModelAttribute.
However, my problem now is that on the client side, I need to use those lists of custom objects in my javascript, but I can only retrieve each field of the custom objects through jstl tag library but I cannot get those custom objects in my javascript where I need them for other logic implementation.
Then I have tried an Ajax file upload plug-in because ajax call can return JSON response which objects can be used in Javascript. But cannot get the plug-in work properly.
I have been stuck on this problem for several days>.< Can anybody help on this? Either a solution on using ModelAttribute in Javascript or a Ajax call solution is ok. Thank you very much!!!
Is there any reason why you can't simply "flatten" your model objects into HTML and then access them from Javascript using the DOM API?
You said you return 3 lists of custom objects. So how about for each list, you build up a (hidden) HTML table, for example if you have a list of Person objects in a ModelAttribute called people:
<table id="people-table">
<c:forEach var="person" items="${people}">
<tr id="${person.id}>
<td class="person-name">${person.name}</td>
<td class="person-age">${person.age}</td>
<td class="person-height">${person.height}</td>
</tr>
</c:forEach>
</table>
Now in your Javascript, you iterate over the rows in people-table, doing whatever you need to do - for example using jQuery:
$("#people-table tr").each(
var personId = $(this).attr("id");
var personName = $(this).find("td.person-name").text();
// etc, etc
// Do something with these as required
);
It's possibly not the most elegant solution but it's easy to debug at least - you can always just inspect the table with Firebug etc to see if the data is correct, and from there you'll know whether to continue debugging the server-side or in the Javascript.

How to create a jsp Form with validation and mail form details to administrator? [duplicate]

This question already has answers here:
How perform validation and display error message in same form in JSP?
(3 answers)
Closed 6 years ago.
I am new to JSP and related technologies. I need to write a JSP form with some required fields (including Captcha), the form will require validation. Upon successful submission of the form, it should be able to email to a stated email address which is grabbed/parsed from a .txt file.
That is basically the flow. But technically how should I do it in JSP/java? Is there any good tutorial referencing to my above form requirement? How should I be able to grab/parse the text file. And lastly,
I remembered that php has a function called mail() to do the emailing, how should I do it in jsp?
Thank you very much.
JSP is just a view technology providing a template to write client side markup/style/scripting languages in, such as HTML/CSS/JS code, alongside with the possibility to control the page flow dynamically with help of taglibs such as JSTL and access to backend data with help of EL. In your speficic case a plain vanilla HTML form would already suffice.
<form action="servletname" method="post">
<input type="text" name="foo"><br>
<input type="text" name="bar"><br>
<input type="submit"><br>
</form>
To control, preprocess and/or postprocess the request and response, the best way is to use a Servlet. Basically just extend HttpServlet and implement the doGet() to preprocess data or the doPost() to postprocess the data. The servlet can be mapped on a certain url-pattern in web.xml. The HTML form action URL should match this url-pattern.
If you want to make use of the very same form to redisplay the submitted page and any error messages, then you can just make use of EL:
<form action="servletname" method="post">
<input type="text" name="foo" value="${param.foo}" ${not empty messages.succes ? 'disabled' : ''}>
<span class="error">${messages.foo}</span><br>
<input type="text" name="bar" value="${param.bar}" ${not empty messages.succes ? 'disabled' : ''}>
<span class="error">${messages.bar}</span><br>
<input type="submit">
<span class="succes">${messages.succes}</span><br>
</form>
Where ${messages} is basically a Map<String, String> which you've put in the request scope in the servlet. For example:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String> messages = new HashMap<String, String>();
request.setAttribute("messages", messages);
String foo = request.getParameter("foo");
String bar = request.getParameter("bar");
if (foo == null || foo.trim().isEmpty()) {
messages.put("foo", "Please enter this field");
}
if (bar == null || bar.trim().isEmpty()) {
messages.put("bar", "Please enter this field");
}
if (messages.isEmpty()) {
YourMailer.send(createTemplate(foo, bar), mailto);
messages.put("succes", "Mail successfully sent!");
}
// At end, forward request to JSP page for display:
request.getRequestDispatcher("pagename.jsp").forward(request, response);
}
More about JSP/Servlet can be found in Java EE 5 tutorial part II chapters 4-9 and in Marty Hall's Coreservlets.com tutorials. To go a step further you can always abstract all the boilerplate stuff (request parameter retrieval, value conversion/validation, event handling, navigation, etcetera) away with help of any MVC framework which is built on top of Servlet API, like Sun JSF, Apache Struts, Spring MVC, etcetera.
With regard to captcha's, you can just use any Java Captcha API to your taste and follow the instructions. Often they have their own servlet/filter which stores a key/toggle/signal in the request or session scope which determines whether the captcha did match or not. You can just access its outcome inside your servlet.
With regard to mailing, you can just use any Java mail API to your taste, however the choice is only limited to the great JavaMail API and the more convenienced one provided by Apache which is built on top of JavaMail API.
That's a lot of questions in one question; here are a couple links which might be helpful (i.e., we've used them in the past):
Kaptcha: http://code.google.com/p/kaptcha/
JavaMail: http://java.sun.com/products/javamail/
Try using skeleton app AppFuse. It offers different frameworks from the basic to advanced ones. Here's an article on captcha integration.

Categories

Resources