Wrong requestMapping send it by a form - java

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.

Related

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.

How does the Spring forms .jsp tag library work?

So I have a .jsp page which has a form on it, like this (naturally this is a massive simplification):
<form:form commandName="myCommand" method="post">
<form:select path="values" class="select-tall" multiple="multiple" id="mySelect">
<option>first</option>
<option>second</option>
<option>third</option>
</form:select>
<button type="submit" class="button">Save</button>
</form:form>
When the submit button is pressed, the form is submitted(somehow) and the path= attributes are used to bind the data inside the form elements to the properties of an instance of a plain old java object. I understand how this POJO is specified, and I understand how the POST request is routed to the correct controller, but I don't understand where or how the form values are mapped to the given POJO.
What I don't understand is:
How does the spring tag library modify the form such that this binding takes place?
How would one go about doing this in a manual or ad-hoc fashion(using a Javascript onSubmit() method, say)?
Essentially my question is: How does the spring-form.tld tag library work?
Any resources, or even a high-level explanation in your own words, would be extremely helpful.
I've implemented a work-around solution in the mean time (dynamically adding items to a hidden form element), but I feel like this is hack-y and the wrong solution.

Spring 3, pass data from jsp to controller

I am using Spring 3. In my jsp I have a form
<form action='componentAction.html' method='POST'>
<input type='hidden' id='action_' name='componentAction' value=""/>
</form>
The value of the form's action changes to either start, stop or pause.
I also have 3 buttons: start, stop and pause. Upon pressing one of these buttons the value of the form changes.
<input type="button" value="Start" onclick="changeFormValueAndSubmit('start')">
<input type="button" value="Stop" onclick="changeFormValueAndSubmit('stop')">
<input type="button" value="Pause" onclick="changeFormValueAndSubmit('pause')">
I would like to be able to send the value of the form to my controller via ajax call after the press happens.
Can someone please show me the right way of doing it? Alsos hould I use POST or GET?
I have tried following tutorials such as
http://www.raistudies.com/spring/spring-mvc/ajax-spring-mvc-3-annonations-jquery/
http://hmkcode.com/spring-mvc-json-json-to-java/
http://java.dzone.com/articles/using-spring-mvc%E2%80%99s
But I have failed miserably.
Thanks to anyone for their hlep in advance!
Using JQuery you can use the following in your changeFormValueAndSubmit() function
function changeFormValueAndSubmit(buttonName) {
var formData = $('form').serialize();
jQuery.post('/path', formData, function(d) {
// handle response
});
...
}
Note: that in this example, jquery will send all the data fields in your form.
Make your you include the jquery framework in your JSP and also have a controller method in spring to handle the POST.
POST is preferable over GET.
On server side using Spring 3 annotations, something like
#Controller
public class ExampleController {
#ResponseBody
#RequestMapping(value = "/path", method=RequestMethod.POST)
public String post(#RequestParam String componentAction) {
// do work
...
return "OK"; // depends on what you need to send back...
}
}
You must enable MVC annotations. See http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html#mvc-annotation-driven
POST or GET will determine if the form data is sent encoded in the URL (GET) or in embedded in the http requests message body (POST). Since it is an ajax call, the URL will not be shown directly to the user, but either way, the user can see the contents of the request under the browser's developer tools.
The simplest way to get spring to direct traffic to your jsp is like such:
<servlet-mapping>
<servlet-name>MyJSPServlet</servlet-name>
<url-pattern>/urlFromOutside</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>MyJSPServlet</servlet-name>
<jsp-file>/pathToJspFile/MyJspFile.jsp</jsp-file>
</servlet>
To get the form data, in your jsp file, you have access to the request object and can get the parameters like so:
<%= request.getParameter("componentAction") %>

How to get REST parameters in HTML

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">

How can I call setParameter in a request object?

This is probably due to my misunderstanding and incomplete information of JSP and JSTL. I have a web page where I have input elements such as
<input name="elementID" value="${param.elementID}"/>
When I am trying to save the form, I check for that elementID and other elements to conform to certain constraints "numeric, less than XXX". I show an error message if they don't. All the parameters are saved and user does not need to type it again after fixing the error.
After saved, when I am redirecting to the same page for the object to be edited, I am looking a way to set the parameter like request.setParameter("elementID",..) Is there a way to do this ? However the only thing I can find is request.setAttribute.
HTTP responses does not support passing parameters.
JSP/Servelets allows you to either use request.setAttribute or session.setAttribute for that purpose. Both methods are available when processing the page you're redirecting to, So basically, you got it right...
Also, from what you describe, you may want to check client-side validation: don't submit the form until you're validating it using client-side scripting (javascript)
After the servlet processes the form, (ie. saves the user input in the database), have the servlet forward (not redirect, because that would lose the request params) the request to the same jsp which contains the form. So there is no need to set the params since the servlet is just passing back the same request object.
The jsp which contains the form should have inputs similar to this:
<form>
...
<input type="text" value="${elementid}"/>
...
</form>
The syntax ${varname} is EL. So if the elementid already has a value, it that textfield will contain that value. Alternatively if you have not used EL and/or JSTL, you use scriptlets (but that is highly unadvisable, EL and/or JSTL should be the way):
<form>
...
<input type="text" value="<%= request.getParameter("elementid") %>"/>
...
</form>
I had to include <%# page isELIgnored="false"%> to my jsp to allow code like ${elementid} to work

Categories