Url parameter to servlet doGet() - eclipse

I'm working on my first web application. I am sending email with an url in it:
http://localhost:8080/HotelP/requeteSuccesO.jsp?hotelId=hampton&city=Montreal
When clicking on the link, requeteSuccesO.jsp displays the hotelId and city parameters:
out.println("<b>Hotel:</b> "+request.getParameter("hotelId")+"</br>");
out.println("<b>City:</b> "+request.getParameter("city")+"</br>");
Then the user can accept by clicking on a button:
<form method="get" action="acceptOffer">
<input type="submit" value="Accept" class="sanslabel">
acceptOffer is mapped to a servlet DecisionPage.java, and by clicking on that button it's calling the doGet() method.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("in do get DecisionPage, hotelId is "+request.getParameter("hotelId"));
this.getServletContext().getRequestDispatcher( VUE_PAIEMENT ).forward( request, response );
}
The parameter hotelId received by the doGet function is null, but I am expecting it to be the value found in the url (in our case, "hampton")
Can anyone tell me why I get null and not "hampton" ?

When you make a form and submit that form to some action, it will only create request parameters for the fields you have defined in your form.
So, while you run the application with mentioned URL, it would contain those parameters and will be avilable to your jsp but if you don't include them in your form it won't be available to servlet when you submit the form.
So, you need to include those parameters to some hidden fields if you don't won't to show them to user.
Example:
<form method="get" action="acceptOffer">
<input type="hidden" name="hotelId" value="<%= request.getParameter(\"hotelId\")" %> /> <---- this field will create a new parameter with name as hotelId
<input type="hidden" name="city" value="<%= request.getParameter(\"city\") %>" />
<input type="submit" value="Accept" class="sanslabel">
</form>
So, now as we made a new fields hotelId and city they will be sent to your servlet acceptOffer and then you'll be able to access them with request parameter as below:
request.getParameter("hotelId")

You have to include those paramters in the form itself because the scope of the paramters is request scope. Something like this
<form method="get" action="acceptOffer">
<input type="text" name="hotelId" value=assign the value from request here/>
<input type="submit" value="Accept" class="sanslabel">
</form>

Related

JSP pass parameter to servlet according to button clicked

I have the following JSP which contains a form. The user should be able to update and delete, so I have two buttons for these options:
<form method="GET" action ="${pageContext.request.contextPath}/CurrencyController">
Currency code: <input type="text" name="currencyCode" id="currencyCode" value="${currency.currencyCode}" />
<br/>
<input type="submit" value="Update" >
<input type="submit" value="Delete"/>
</form>
In my servlet CurrencyController I retrieve the action:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action.equalsIgnoreCase("update")){
...
if (action.equalsIgnoreCase("delete")){
...
So how can I pass the value for action in my form? It should be update if the first button is clicked and delete if the second button is clicked
Add action parameter using new input:
<input type="hidden" name="action" id="action" value="" />
Add onClick attribure to each submit button that will change its value. for example:
onClick="document.getElementId('action').value=this.value;return true;"

MVC how can i post a form without using a model

I would like to know how i could sumbit a form in mvc 4 without using a model binding to the view.
can some one please demontrate how? and how can i use that form in the controller?
It is very easy to use a form without any sort of Model binding.
Simple set up your for using either #using(Html.BeginForm()){ ... } or plain html.
<form id="myForm" action="/ControllerName/ActionName" method="Post">
<input type="text" name="foo" value="FOOOO" />
<input type="text" name="bar" value="Baaaar" />
<button type="submit">Submit</button>
</form>
When you post this to the ActionResult, your action result just needs to be set up to accept a string value named foo and one named bar
[HttpPost]
public ActionResult ActionName(string foo, string bar){
// your code here
return View();
}

Rest spring upload file with parameter in form

I am trying to upload a file i can able to upload a file but i need to post one parameter present in the form, now i need to post one parameter and upload file in the form.
I tried Multi part and Form url encoded in the consumes annotation. It is not working i am getting an error.
I used #FormDataParam and #FormParam annotation in the method.
java.lang.NullPointerException
org.glassfish.jersey.media.multipart.internal.FormDataParamValueFactoryProvider$FormDataParamValueFactory.provide(FormDataParamValueFactoryProvider.java:203)
org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:81)
org.glassfish.jersey.server.internal.routing.SubResourceLocatorRouter.getResource(SubResourceLocatorRouter.java:220)
org.glassfish.jersey.server.internal.routing.SubResourceLocatorRouter.apply(SubResourceLocatorRouter.java:133)
org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:128)
Server side:
#POST
#Path("import")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8")
public void uploadScenario(#FormDataParam("importScenario") final InputStream is,
#FormDataParam("complectId") final Long complectId) {
// Realisation
}
Client side:
<form id="importForm" target="my_iframe" action="rest/exportimport/import" method="post" enctype="multipart/form-data">
<input id="uploader" type="file" name="importScenario" size="50"><input type="submit">
<input type="text" style="display:none" name="complectId" value="'+id+'">
</form>

Angular JS: sending form field data in a PUT request (like POST does)

I'm trying to write a client that does all four REST verbs (GET/POST/PUT/DELETE) and have gotten all but the PUT done. The REST/CRUD API I'm working from wants to update an entry by calling PUT /realmen/ID-string and including the key-value pairs as JSON. For a POST this seems to work "automatically", but not for a PUT.
My HTML looks like:
<div id="list">
<form novalidate class="edit-form">
<p>Title <input ng-model="realmen.title" type="text" value="{{realmen.title}}" /></p>
<p>Real Men <input ng-model="realmen.realmen" type="text" value="{{realmen.realmen}}" /> </p>
<p>Real Role-Players <input ng-model="realmen.realroleplayers" type="text" value="realmen.realroleplayers}}" /></p>
<p>Loonies <input ng-model="realmen.loonies" type="text" value="{{realmen.loonies}}" /></p>
<p>Munchkins <input ng-model="realmen.munchkins" type="text" value="{{realmen.munchkins}}" /></p>
<input ng-model="realmen.entryId" type="hidden" value="{{entryId}}"/>
<button ng-click="change()">UPDATE ({{entryId}})"</button></p>
</form>
</div>
My controller looks like:
$scope.realmen = RealMen.get({entryId: $routeParams.entryId}, function() {
$scope.master = angular.copy($scope.realmen); // For resetting the form
});
$scope.change = function() {
console.log($scope.realmen);
RealMen.update({entryId: $scope.entryId}, function() {
$location.path('/');
});
}
And finally, my services look like:
angular.module('realmenServices', ['ngResource']).
factory('RealMen', function($resource){
var RealMen = $resource(
'http://localhost\\:3000/realmen/:entryId',
{},
{
query: {method:'GET', params:{entryId:''}, isArray:true},
post: {method:'POST'},
update: {method: 'PUT', params:{entryId:'#entryId'}},
remove: {method:'DELETE'}
});
return RealMen;
});
The PUT is getting called with the correct id value in the URL, but the Request Payload only contains the entryId, so the backend API gets no expected keys and values and essentially blanks out the record in the database.
The console.log($scope.realmen) does show the form fields, along with a lot of extra data. I tried calling RealMen.update($scope.realmen, ...) (similarly to calling .save()), but all those extra fields are tacked on as query string parameters to the URL in a spectacularly ugly fashion.
Because your $scope.realmen is a resource instance, instead of using RealMen.update, you can just call $scope.realmen.$update() (note that there is a "$"). The instance action method will take care of sending the data for you.

send html form via post to webservice

I'm very very new on HTML5 development and this question could be very silly but I've found an answer for it (or I've searched very well).
I want to send a form to a web service via post (I don't want to show all fields in URL).
I have two question:
How must I named forms fields? If I trying to send an userName I think I have to put this test as ID to the field which will held that value.
And this is because I'm so curious. Which is the post message content which is sent to web service?
This is an example that I've found searching Internet:
<FORM action="http://somesite.com/prog/adduser" method="post">
<P>
<LABEL for="firstname">First name: </LABEL>
<INPUT type="text" id="firstname"><BR>
<LABEL for="lastname">Last name: </LABEL>
<INPUT type="text" id="lastname"><BR>
<LABEL for="email">email: </LABEL>
<INPUT type="text" id="email"><BR>
<INPUT type="radio" name="sex" value="Male"> Male<BR>
<INPUT type="radio" name="sex" value="Female"> Female<BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</P>
</FORM
I think I will need those ids to get those values while processing them on web service, isn't it?
It depends, you could do a post to a page with a redirect (in .NET you would handle it this way):
<form action="http://myurl/postpage.ashx" method="post">
<input name="forename" />
<input name="surname" />
<input type="submit" value="Submit" />
</form>
And then pick this up in the server side script at postpage.ashx using:
string forename = Request["forename"];
string surname = Request["surname"];
You could also use jQuery to make an ajax call to the same page using the following:
var forename = $("input[name=\"forename\"]").val();
var surname = $("input[name=\"surname\"]").val();
$.ajax({
url: "http://myurl/postpage.ashx",
type: "POST",
async: true, // set to false if you don't mind the page pausing while waiting for response
cache: false,
dataType: "json",
data: "{ 'forename': '" + forename + "', 'surname': '" + surname + "' }",
contentType: "application/json; charset=utf-8",
success: function(data) {
// handle your successful response here
},
error: function(xhr, ajaxOptions, thrownError) {
// handle your fail response here
}
});
You would handle the post in the server side code the same way. The key thing to note here is that whatever you enter as the name attribute of your input element is what will get POSTed as a key/value pair to your receiving URL.
every web service should give you something like WSDL which normally contains specification of available fields and methods you can use. if the webservice you are connecting to have url webservice.com than try webservice.com/wsdl to get the WSDL.
Check this topic: click
Attribute "name" is the one that needs to be unique in order to pass that parameter to a Servlet (or wherever). The post method then encrypts the message and sends it to the Servlet.
<form method="post" action = "LoginServlet">
Name: <input type="text" name="userName">
Password: <input type="password" name="password">
<input type="submit" name = "Login" class="button">
</form>
In order to access that data you will do something like this in the Servlet:
String userName = request.getParameter("userName");