JAX-RS, #FormParam display result in the same page - rest

I have this program that I am coding, the main thing is mostly to get familiar with Jax-rs and rest API. I am sending from a form in JSP page one input and with POST I pass it to my java Response class(that I use annotation #FormParam), it does what calculation I need and then I get the result in another link, what can i do to take the result just below my button on the same page? For my button function I use javascript, and when I push it I don't want to be redirected and take the result like this.
So i use this form and a javascript function in my jsp to pass the value in my POST method in java throw #FormParam
<form name="Form1" method="post">
<p>
Name : <input type="text" name="malename" id="malename" autofocus
value="enter your name..." />
</p>
<input type="submit" name="action" id="malename" value="I'm feeling lucky"
onclick="OnButton1();"> </form>
function OnButton1() {
document.Form1.action = "webapi/perfectmatcher/mate"
document.Form1.target = "_self"; // Open in a new window
document.Form1.submit(); // Submit the page
//return;
}
Here after i have the value i use two other classes to do the calculations and return the result i need. In a few words i pass a value in my form and when i push the button i am redirected in another link(the path of POST) and i display the result. I want to display the result below my button. I hope the code is helpful and i hope i am clear with my explanation
#POST
#Path("/mate")
#Produces(MediaType.TEXT_PLAIN)
public Response postMaleName(#FormParam("malename") String malename) {
String femalename = NumMatcher.numMatcher(Numberizer.numberizer(malename));
// FemaleName female = new FemaleName(femalename);
female.setName(femalename);
System.out.println(female.getName());
return Response.status(200).entity("Perfect Match for " + malename + " is " + femalename).build();
}
P.S.:The object female that i am trying to create its for testing purposes, i was trying somehow to get the information that i store but i cannot find how!!I used even jsp expressions but i get null value of course ...
<%
FemaleName female = new FemaleName("john");
String string = female.getName();
out.print(string);
%>

Related

Flask request not returning any info from select

I'm trying to set up a simple select dropdown form with Flask. Based on the option chosen, I grab different data from my database, and display it back into a div on my html template. But I can't seem to get the Flask request to register any of the select options. When I print request.form or request.args, I always get empty Dicts. It's probably something simple I'm missing but I can't seem to find the problem. I've gotten this to work with several input and button forms, but I can't get it to work right for selects.
Here is a bit of my html template code, with the form and select. I've tried both GET and POST method in the form.
<div class="options" id="options">
<form class="form-horizontal container-fluid" role="form" method="GET" action="exploresn2.html">
<div class="form-group">
<label for="xaxis" class="col-sm-2 control-label">X-axis:</label>
<div class="col-sm-2">
<select name="xaxis" class="form-control" id="xaxis">
<option selected value="mjd" id="mjd">MJD</option>
<option value="seeing" id="seeing">Seeing</option>
<option value="airmass" id="airmass">Airmass</option>
<option value="hourangle" id="hourangle">Hour Angle</option>
</select>
</div>
</div>
</form>
</div>
In Flask, at first, I tried inside my app
import flask
from flask import request, render_template, send_from_directory, current_app
explore_page = flask.Blueprint("explore_page", __name__)
#explore_page.route('/exploresn2.html', methods=['GET','POST'])
def explore():
xaxis = str(request.args.get("xaxis", "any"))
.... [populate new xaxis variable based on request option selected]
exploreDict['xaxis'] = xaxis
return render_template("exploresn2.html", **exploreDict)
or
mjd = valueFromRequest(key='mjd', request=request, default=None)
if mjd:
mjds = [int(exp.platedbExposure.start_time/(24*3600)) for exp in exposures]
xaxis = mjds
exploreDict['xaxis'] = xaxis
to look for and grab a specific values, or in the first case, any value select. The valueFromRequest is function that grabs data from either GET or POST requests.
but this returns nothing, and then I tried just printing the entire request.args (or request.form) and it returns and empty Dict. Everything I try it still returns empty Dicts. So I'm missing some set up somewhere I think but the form looks right to me?
I'm not sure if this is the actual answer to this problem that I was looking for, but here is what I came up with. I couldn't actually get the Flask to accept a GET request into the original explore method defined, so I implemented a new method in Flask to return a JSON object
#explore_page.route('/getdata', methods=['GET','POST'])
def getData(name=None):
name = str(request.args.get("xaxis", "mjd"))
xaxis = 'populate new xaxis data based on value of name'
data = '(x,y) data array filled with values for plotting'
axisrange = range of x,y data for axes for plot
return jsonify(result=data, range=axisrange)
and then I just made a GET request via javascript to that method whenever the select button changes. So in my exploresn2.html template I have (using Flot for plotting)
$("#xaxis").change(function(){
var newname = $("#xaxis :selected").text();
var axes = plot.getAxes();
options = plot.getOptions();
var plotdata = plot.getData();
// make a GET request and return new data
$.getJSON($SCRIPT_ROOT + '/getdata', {'xaxis':$("#xaxis :selected").val()},
function(newdata){
// set new data
for (var i = 0; i < plotdata.length; ++i) {
plotdata[i].data = newdata.result[plotdata[i].label];
}
// set new axes
axes.xaxis.options.panRange = [newdata.range[0]-50,newdata.range[1]+50];
axes.xaxis.options.axisLabel = newname;
axes.xaxis.options.min = newdata.range[0]-1;
axes.xaxis.options.max = newdata.range[1]+1;
axes.yaxis.options.min = newdata.range[2];
axes.yaxis.options.max = newdata.range[3];
// redraw plot
plot.setData(plotdata);
plot.setupGrid();
plot.draw();
});
});

How to serialize html form in dart as a string for submission

In jQuery, there is a function to serialize a form element so for example I can submit it as an ajax request.
Let's say we have a form such as this:
<form id="form">
<select name="single">
<option>Single</option>
<option selected="selected">Single2</option>
</select>
<input type="checkbox" name="check" value="check1" id="ch1">
<input name="otherName" value="textValue" type="text">
</form>
If I do this with the help of jquery
var str = $( "form" ).serialize();
console.log(str);
the result would be
single=Single2&check=check1&otherName=textValue
Is there such functionality in dart's FormElement or I have to code it myself? Thanks.
I came up with my own simple solution that might not work in all cases (but for me it is workikng). The procedure is this:
First we need to extract all input or select element names and values from the form into Dart's Map, so the element name will be the key and value the value (e.g. {'single': 'Single2'}).
Then we will loop through this Map and manually create the resulting string.
The code might look something like this:
FormElement form = querySelector('#my-form'); // To select the form
Map data = {};
// Form elements to extract {name: value} from
final formElementSelectors = "select, input";
form.querySelectorAll(formElementSelectors).forEach((SelectElement el) {
data[el.name] = el.value;
});
var parameters = "";
for (var key in data.keys) {
if (parameters.isNotEmpty) {
parameters += "&";
}
parameters += '$key=${data[key]}';
}
Parameters should now contain all the {name: value} pairs from the specified form.
I haven't seen anything like that yet.
In this example Seth Ladd uses Polymers template to assign the form field values to a class which get's serialized.

Linking two jsp pages with Submit Button Liferay

I have a form where I allow user to select some data and submit the form and based on that selection data will be displayed in another jsp.
I have used the following code in first jsp:
<aui:form name="updateDailyAttendance" action = "<%=request.getContextPath()%> /admin/test.jsp" method="post" >
<input type = "date" name = "myDate"/>
<input type = "submit" name = "Submit"/>
</aui:form>
test.jsp is the second JSP. But the code above isn't working. How should I mention the second jsp name in the "action" above so that the above jsp takes me to second jsp. I am using lIferay
instead of passing a url as 'action', you should provide an actionUrl with the jsp page as param.
<portlet:actionURL var="actionName" name="yourMVCPortletFunctionName">
<portlet:param name="jspPage" value="/admin/test.jsp" />
</portlet:actionURL>
<aui:form name="updateDailyAttendance" action = "<%= actionName %>" method="post" >
<input type = "date" name = "myDate"/>
<input type = "submit" name = "Submit"/>
</aui:form>
then in Your Controller:
public void yourMVCPortletFunctionName(ActionRequest actionRequest, ActionResponse actionResponse){
throws PortletException, IOException
//Do your stuff
//Redirect
String redirectUrl = (String)request.getParameter("jspPage");
actionResponse.setRenderParameter("jspPage", redirectUrl);
}
This way you can have actions that do some standard stuff, like handling that "myDate" param, and have them redirect to other pages each time. So calling them from different points (different jsp page or form), will target ta a new redirect each time

how to pass parameters from jsp to java class using RESTFUL

i hav created a jsp page from which i m taking some values and on submit it should pass the parameters to the java class using rest.
< form id="payment" method="post" action="addtogroup">
< ol style="padding: 0;">
< li>< label for="groupId">Group id:< /label>
< input type="text" id="groupId" name="groupId"/>
< br />
< li>< label for="vendorId">Profile Id :< /label>
< input type="text" id="vendorId" name="vendorId"/>
< li>
< input type="submit" value="Submit"/>
< br />
< /ol>
< /form>
and the java code is:
#RequestMapping(value = "/addtogroup/{groupId}/{vendorId}",method = RequestMethod.POST)
public String addtoGroup(#ModelAttribute("groupId") String groupId,#ModelAttribute("vendorId") String profileId){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
System.out.println("group id is="+groupId);
System.out.println("profileId is="+profileId);
System.out.println("username is="+username);
grpDao.addToGroup(groupId,profileId,username);
return "addtogroup";
}
when i type [http://localhost:8080/biznex/rest/addtogroup/2/13] in the address bar directly the code is executed.
but when i click submit button in the jsp i get page not found error.
plz help me out.
< form id="payment" method="post" action="addtogroup"> This statement means submit the FORM data using POST method to the url "currentpath"/"addtogroup"
However, your RESTFUL Server side component expects the url in the form of /addtogoup/{groupid}/{vendorid} in a GET method
I would suggest you to have a JavaScript method which converts your form fields to the URI path- using jQuery or plain JavaScript
As thewhiterabbit wrote, you have to pass the complete REST url with the groupid and vendorid.
In order to build it you don't need to use JS, it's enough the spring tag library. Here, how it works:
<spring:url value="/addtogoup/${form.groupid}/${form.vendorid}" var="actionURL"/>
<form:form method="POST" action="${actionURL}" modelAttribute="form">

How can I pass FORM on a button click in MVC2.0?

I am calling a controller method SendMe(formCollection myForm){}.
But I don't know how to pass Form that contains some information. I know how to read it, and also, how to call SendMe() on given controller, but I don't know how to pass it. Though, for the reference I am calling SendMe as:
<div id="menucontainer">
<ul id="menu">
<li><%: Html.ActionLink("Send", "SendMe", "Mail")%></li>
</ul>
</div>
and my SendMe method is:
public ActionResult SendMe(FormCollection Form)
{
string From = Form["From"].ToString();
string Pass = Form["Password"].ToString();
string To = Form["To"].ToString();
string Subject = Form["Subject"].ToString();
string Message = Form["Message"].ToString();
MailMessage nmsg = new MailMessage(From, To, Subject, Message);
nmsg.IsBodyHtml = true;
nmsg.Priority = MailPriority.High;
SmtpClient smtpc = new SmtpClient("smtp.gmail.com", 587);
smtpc.Credentials = new System.Net.NetworkCredential(From, Pass);
smtpc.EnableSsl = true;
smtpc.Send(nmsg);
return View();
}
I haven't put anything in Model, though, MailController and SendMe.aspx are in place.
tell me how to get through this. Thanks in advance.
This simple code should work...if all you need is this to submit information from a form...Please clear if i understood it wrong..I would recommend using a viewmodel or something though to have validation for those fields...and in viewmodel case you should inherit the page from the viewmodel...and retrieve from the viewmodel object instead of formcollection...
<% Html.BeginForm("SendMe", "Send", FormMethod.Post); %> //Here 1st parameter is the actionname while second is the Controller name
//Form Fields....
<input id="SendMe" type="submit" value="Send Info" />
<% Html.EndForm(); %>
In order to obtain the FORM variables in your controller, the form needs to be submitted via a Http POST.
<% using (Html.BeginForm()) {%>
.....
<% Html.EndForm(); %>