How to get REST parameters in HTML - java

I have created a REST webservice (and its client on Android) which can create user and make user sign in.But thats fine for Android .Since my URL is not exposed in Android.
My REST root path is : http://localhost:8080/Mysite/rest/site
I have certain REST methods like :
#Path("/create")
#POST
#Produces({MediaType.TEXT_HTML,MediaType.APPLICATION_XML})
#Consumes(MediaType.APPLICATION_FORM_URLENCODED){}
#Path("/{user}/createmessage")
#POST
#Produces({MediaType.TEXT_HTML,MediaType.APPLICATION_XML})
#Consumes(MediaType.APPLICATION_FORM_URLENCODED){}
You can see in second method the parameter {user} in #Path("/{user}/createmessage").
That will be taken care by REST when calling from Android as it will susbstitue the username {user} in HTTP Post request.
Now i need to make the WebClient.And i have the form as :
<form action="http://localhost:8080/MySite/rest/site/{user}/createmessage" method="post">
<label for="title">Message Title : </label>
<input name="title" />
<label for="message">Message : </label>
<input name="message"/>
And thats for certain that this line is having error :
<form action="http://localhost:8080/MySite/rest/site/{user}/createmessage" method="post">
As {user} cannot be transmitted by HTML.
How to get the REST parameters from REST webservice in HTML ?

{user} is a notation to refer to a dynamic path segment used as a parameter. It is used by JAX-RS to denote the parameter name and location in the URI. It is not intended to be passed as is, but to be replaced with the actual parameter for the query.
It would help to see the signature of the REST method to provide some context as to what is expected, but chances are it's expecting some sort of id?
So if you want to create a message for user 123, you'd make your form action URL as below:
<form action="http://localhost:8080/MySite/rest/site/123/createmessage">

Related

Wrong requestMapping send it by a form

I would like to know how can I solve this problem, let me explain: I want to create a search bar and send the user to a jsp view with the results. I created in my controller the next method :
#RequestMapping(value = "/search={productName}", method = RequestMethod.GET)
public ModelAndView getProducteByName(#PathVariable("productName") String productName) {
ModelAndView modelview = new ModelAndView("/productSearch");
List productsByName = productService.getProductByName(productName);
modelview.addObject("productsByName", productsByName );
return modelview;
And I have a form in a jsp file like this:
<!-- Search form -->
<form class="form-inline md-form form-sm mt-0" method="get" >
<i class="fas fa-search" aria-hidden="true"></i>
<input class="form-control form-control-sm ml-3 w-75" type="text" placeholder="Search" name="search"
aria-label="Search">
</form>
The problem is when I put anything to search in the bar search, it works put it puts me a ? in the url, so the controller doesn't understand the requestMapping.
Example: http://localhost:8080/projectbotigabio/search=potato
and it puts me: http://localhost:8080/projectbotigabio/?search=potato
I've tried a lot of things, including trying to putting as a method "post" instead of "get", but it doesn't work... any solution?
Web browsers only support 3 kinds of form submission:
method="get"
Every form value is added to the URL using ?name=value&name=value&...
method="post"
Every form value is added to POST with content type application/x-www-form-urlencoded and content name=value&name=value&...
method="post" enctype="multipart/form-data"
The POST request has content type multipart/form-data, and the content is a multipart with each part being a form value.
Web browsers cannot build the URL you want, so you have to do it yourself, i.e. prevent the web browser from sending the POST request, and send your own request using Ajax. If that's what you want, put on your learning hat and start studying how that works.
I recommend that you stop trying to use a non-standard URL syntax, and use the standard GET processing.
Either way, I suggest you learn more about how HTML forms work, before you try deviating from the standards any further.

How to test jmeter's response and pass parameters?

I am researching jmeter and I have a question.
My first question: in case : (github )
input autocapitalize="off" autocorrect="off" autofocus="autofocus" class="form-control input-block" id="login_field" name="login" tabindex="1" type="text"
input class="form-control form-control input-block" id="password" name="password" tabindex="2" type="password"
In case the website don't have field "name", how can I pass the param to website ? can we use css or xpath to pass the param to website ?
My second question:
How to test the response value from the site ? (from the picture the response data not right, still on login page)
Thanks for reading and supporting me to correct this ...
As per HTML Forms article
The Name Attribute
To be submitted correctly, each input field must have a name attribute.
Actually you should't worry about HTML markup, JMeter acts on protocol level and provides record-and-replay functionality. See Apache JMeter Proxy Step by Step for configuration instructions.
You can use Response Assertion to add a check whether response is still login page or not. For example if the user is logged in - he shouldn't see username input any more. See How to Use JMeter Assertions in Three Easy Steps article for more information on conditionally failing JMeter samplers.

How to process form by <jsp:setBean> and send it to servlet?

Could you help me to come up with solution.
There are JSP-page which sends form parameters to servlet.
Usually I parse parameters by HttpServletRequest.getParameter() which works fine for forms with tiny parameter numbers.
Now I'm developing application which has a lot of JSPs with number of parameters and the standard way of form processing is inconvenient.
I think that possible solution might be by using -action.
I don't understand whether it works for me.
I browsed a lot of materials but find nothing about it.
I mean that there is any information regarding possibility to get form parameters in jsp by ,
automatically create instance of the entity class,
map all the parameters to entity-properties and send the entity-instance to the servlet.
Please take a look at the code:
index.jsp
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="NewFormServlet" enctype="application/x-www-form-urlencoded">
<jsp:useBean id="client-bean" class="model.entity.Client" scope="request"/>
<h3>Please enter client information</h3><br>
Client first name<input type="text" name="first-name"/><br>
<jsp:setProperty name="client-bean" property="firstName" value="${requestScope.first-name}"/>
Client last name<input type="text" name="last-name"/><br>
<jsp:setProperty name="client-bean" property="lastName" value="${requestScope.last-name}"/>
Client address<input type="text" name="address" size="100"/><br>
<jsp:setProperty name="client-bean" property="address" value="${requestScope.address}"/>
Client city<input type="text" name="city"/><br>
<jsp:setProperty name="client-bean" property="city" param="${requestScope.city}"/>
Client postal code<input type="text" name="postal-code"><br>
<jsp:setProperty name="client-bean" property="postalCode" value="${requestScope.postal-code}"/>
<input type="hidden" name="jsp-identifier" value="client-form">
<input type="submit" value="Submit">
</form>
</body>
</html>
What is incorrect in this code? Thank you in advance.
You should first think about what occurs on server and what occurs in browser, as well as what is transmitted via HTTP. A form submission uses many phases :
on server : the JSP is executed using servlet context, session, and request attributes, with still full access at the previous request (parameters, ...) => all that generates a HTML page (with eventually css or javascript linked or included)
on browser : the browser gets and parses the HTML page, optionnaly gets linked resources (images, etc.), and display the form to the user
on browser : the user fills the input fields of the form and clicks the input button
on browser : the browser collates data form input fields, generate an new HTTP request (usually a POST one) and sends it to server
on server : the servlet container pre-processes the request (until that is is only a stream of bytes conforming to HTTP protocol) and calls the appropriate servlet method with a new HttpServletRequest reflecting current HTTP request, and a HttpServletResponse to prepare what will be sent back to browser after processing
All that means that anything you can do to request attributes in the JSP part will be lost at the time of processing of the submitted form by the servlet. You can only rely on session attributes, and on input form fields that will be accessible as request parameters.
So with your current JSP, the Servlet will find nothing in request attributes (it is a different HttpServletRequest) and will only be able to use parameters with names firstName, lastName, address, city, etc.
I can understand it is not the expected answer, but HTTP protocol is like that ...
EDIT per comment :
You can put the attribute in session, and then the servlet will use the same session as the JSP. But read again what I wrote above and think when things happen :
on server, when executing the JSP, you create an empty Client bean that you put in session scope, and use its value to initialize the form fields. Stop for the server part
on client, user fills the input fields - the server knows nothing on that - and submit the form through a new request
on server, the servlet has the values in request parameters, but the session still contains the previous values and so the Client bean has null values
I'm sorry but there's not enough magic for the server to automatically find in its attributes (either request or session) what comes from form submission : it only exists in request parameters, and it is the servlet job to process them and eventually put them in attributes.
Edit:
It appears that jsp:useBean is an old school way to collect up a group of parameter values for easier display on a page.
It does not add an attribute when the request is posted.
Based on that,
I see little value in the jsp:useBean tag,
since you can use el expressions to access attributes that you set in a servlet.
This does not help you get the posted parameter values into a bean in the servlet.
You can write a method on the bean to extract the parameter values from the request (visitor pattern).
For example:
class bean
{
private String value;
public void loadFromHttpServletRequest(final HttpServletRequest request)
{
value = request.getParameter("value");
}
}
Consider using a package like spring-mvc.

Trying to use a #RequestParam field in Spring form [duplicate]

Consider this form:
<form action="http://www.blabla.com?a=1&b=2" method="GET">
<input type="hidden" name="c" value="3" />
</form>
When submitting this GET form, the parameters a and b are disappearing.
Is there a reason for that?
Is there a way of avoiding this behaviour?
Isn't that what hidden parameters are for to start with...?
<form action="http://www.example.com" method="GET">
<input type="hidden" name="a" value="1" />
<input type="hidden" name="b" value="2" />
<input type="hidden" name="c" value="3" />
<input type="submit" />
</form>
I wouldn't count on any browser retaining any existing query string in the action URL.
As the specifications (RFC1866, page 46; HTML 4.x section 17.13.3) state:
If the method is "get" and the action is an HTTP URI, the user agent takes the value of action, appends a `?' to it, then appends the form data set, encoded using the "application/x-www-form-urlencoded" content type.
Maybe one could percent-encode the action-URL to embed the question mark and the parameters, and then cross one's fingers to hope all browsers would leave that URL as it (and validate that the server understands it too). But I'd never rely on that.
By the way: it's not different for non-hidden form fields. For POST the action URL could hold a query string though.
In HTML5, this is per-spec behaviour.
See Association of controls and forms - Form submission algorithm.
Look at "4.10.22.3 Form submission algorithm", step 17. In the case of a GET form to an http/s URI with a query string:
Let destination be a new URL that is equal to the action except that
its <query> component is replaced by query (adding a U+003F QUESTION
MARK character (?) if appropriate).
So, your browser will trash the existing "?..." part of your URI and replace it with a new one based on your form.
In HTML 4.01, the spec produces invalid URIs - most browsers didn't actually do this though...
See Forms - Processing form data, step four - the URI will have a ? appended, even if it already contains one.
What you can do is using a simple foreach on the table containing the GET information. For example in PHP :
foreach ($_GET as $key => $value) {
$key = htmlspecialchars($key);
$value = htmlspecialchars($value);
echo "<input type='hidden' name='$key' value='$value'/>";
}
As the GET values are coming from the user, we should escape them before printing on screen.
You should include the two items (a and b) as hidden input elements as well as C.
I had a very similar problem where for the form action, I had something like:
<form action="http://www.example.com/?q=content/something" method="GET">
<input type="submit" value="Go away..." />
</form>
The button would get the user to the site, but the query info disappeared so the user landed on the home page rather than the desired content page. The solution in my case was to find out how to code the URL without the query that would get the user to the desired page. In this case my target was a Drupal site, so as it turned out /content/something also worked. I also could have used a node number (i.e. /node/123).
If you need workaround, as this form can be placed in 3rd party systems, you can use Apache mod_rewrite like this:
RewriteRule ^dummy.link$ index.php?a=1&b=2 [QSA,L]
then your new form will look like this:
<form ... action="http:/www.blabla.com/dummy.link" method="GET">
<input type="hidden" name="c" value="3" />
</form>
and Apache will append 3rd parameter to query
When the original query has array, for php:
foreach (explode("\n", http_build_query($query, '', "\n")) as $keyValue) {
[$key, $value] = explode('=', $keyValue, 2);
$key = htmlspecialchars(urldecode($key), ENT_COMPAT | ENT_HTML5);
$value = htmlspecialchars(urldecode($value), ENT_COMPAT | ENT_HTML5);
echo '<input type="hidden" name="' . $key . '" value="' . $value . '"' . "/>\n";
}
To answer your first question yes the browser does that and the reason is
that the browser does not care about existing parameters in the action URL
so it removes them completely
and to prevent this from happening use this JavaScript function that I wrote
using jQuery in:
function addQueryStringAsHidden(form){
if (form.attr("action") === undefined){
throw "form does not have action attribute"
}
let url = form.attr("action");
if (url.includes("?") === false) return false;
let index = url.indexOf("?");
let action = url.slice(0, index)
let params = url.slice(index);
url = new URLSearchParams(params);
for (param of url.keys()){
let paramValue = url.get(param);
let attrObject = {"type":"hidden", "name":param, "value":paramValue};
let hidden = $("<input>").attr(attrObject);
form.append(hidden);
}
form.attr("action", action)
}
My observation
when method is GET and form is submitted, hidden input element was sent as query parmater. Old params in action url were wiped out. So basically in this case, form data is replacing query string in action url
When method is POST, and form is submitted, Query parameters in action url were intact (req.query) and input element data was sent as form data (req.body)
So short story long, if you want to pass query params as well as form data, use method attribute as "POST"
This is in response to the above post by Efx:
If the URL already contains the var you want to change, then it is added yet again as a hidden field.
Here is a modification of that code as to prevent duplicating vars in the URL:
foreach ($_GET as $key => $value) {
if ($key != "my_key") {
echo("<input type='hidden' name='$key' value='$value'/>");
}
}
Your construction is illegal. You cannot include parameters in the action value of a form. What happens if you try this is going to depend on quirks of the browser. I wouldn't be surprised if it worked with one browser and not another. Even if it appeared to work, I would not rely on it, because the next version of the browser might change the behavior.
"But lets say I have parameters in query string and in hidden inputs, what can I do?" What you can do is fix the error. Not to be snide, but this is a little like asking, "But lets say my URL uses percent signs instead of slashes, what can I do?" The only possible answer is, you can fix the URL.
I usually write something like this:
foreach($_GET as $key=>$content){
echo "<input type='hidden' name='$key' value='$content'/>";
}
This is working, but don't forget to sanitize your inputs against XSS attacks!
<form ... action="http:/www.blabla.com?a=1&b=2" method ="POST">
<input type="hidden" name="c" value="3" />
</form>
change the request method to' POST' instead of 'GET'.

How do I send data between servlets?

I am pretty new to servlets and web development in general.
So basically I have a servlet that queries a database and returns some values, like a name. What I want is to turn the name into a link that opens a details page for that name (which another servlet would handle). How can I send the name to the other servlet so it can query a database for the relevant details?
Maybe I'm taking the wrong approach?
Edit: I am using Tomcat 5.5
Pass it as request parameter.
Either add it to the query string of the URL of the link to the other servlet which is then available by request.getParameter("name") in the doGet() method.
link
Or add it as a hidden input field in a POST form which submits to the other servlet which is then available by request.getParameter("name") in the doPost() method.
<form action="otherservlet" method="post">
<input type="hidden" name="name" value="${name}" />
<input type="submit" />
</form>
See also:
Servlets info page - contains a Hello World
Not sure if I understand correctly, but you may look at javax.servlet.RequestDispatcher and forward the url to the second servlet.
The url could be created using the name:
http://myhost.mydomain/my.context/servlet2.do?name=John
I would create the URL either in the first servlet or in a client using a configurable template for the URL. This way both servlets are clearly separated - you can even have each one on different machine.

Categories