Java spring #RequestParam JSP - java

current controller code:
#RequestMapping(value = "/city", method = RequestMethod.POST)
public String getWeather(#RequestParam("city") int city_id,
#RequestParam("text") String days, //this gives errrors, when i remove this line, then it is okay
Model model) {
logger.debug("Received request to show cities page");
//int city =
// Attach list of subscriptions to the Model
model.addAttribute("city", service.getCity(city_id));
// This will resolve to /WEB-INF/jsp/subscribers.jsp
return "city";
}
this is my JSP file(view):
<form method="post" action="/spring/krams/show/city">
Vali linn
<select name="city">
<c:forEach items="${cities}" var="city">
<option value="<c:out value="${city.id}" />"><c:out value="${city.city}" /></option>
</c:forEach>
</select><br>
Vali prognoos N päeva kohta(kirjuta 1 hetkese ilma jaoks)
<input type="text name="text">
<input type="submit" value="Test" name="submit" />
</form>
i want to get a value from the textbox named TEXT, but when i press the submit button then i get
HTTP Status 400 - The request sent by the client was syntactically incorrect ().

I am adding this answer so that you can accept it, as it was suggested by Bozho :)
There seems to be a problem in the HTML:
<input type="text name="text">
Change it to
<input type="text" name="text"> and try .
I think syntactically incorrect means the names specified in the #RequestParam annotations don't match with the request param names... possibly because of the above error in HTML.

Related

servlet can't get option value from jsp

I'm doing a java web application using jsp and servlets.
I have a form and I retrieve different values from my db to populate an option. This is my form:
<form class="form" action ="<%=request.getContextPath()%>/aggiungiLibro" method ="post">
<div class="form__group">
<input type="text" placeholder="Titolo" class="form__input" name = "titolo"/>
</div>
<div class="form__group">
<input type="text" placeholder="QuantitĂ  disponibile" class="form__input" name="quantita" />
</div>
<div class="form__group">
<select class="form__input" name="autore">
<c:forEach items="${listaAutori}" var = "autore" >
<option value="${autore.idAutore}"><c:out value="${autore.nome} ${autore.cognome}" /></option>
</c:forEach>
</select>
</div>
<button class="btn btn-light" type="submit">Inserisci nuovo libro</button>
</form>
In the servlet I retrive my data with
String titolo = request.getParameter("titolo");
int quantita = Integer.parseInt(request.getParameter("quantita"));
int autore = Integer.parseInt(request.getParameter("autore"));
I get right values for 'titolo' and 'quantita' but I get the string '${autore.nome}' for 'autore'.
It seems like it doesn't replace the string with the actual value.
The field idAutore is spelt right.
(In the jsp page I see the correct values for ${autore.nome} ${autore.cognome})
Anyone can help me please? What I'm doing wrong?
I solved replacing this:
<option value="${autore.idAutore}">
with this:
<option value="<c:out value='${autore.idAutore}' />">

How to add the result variable of form submission to mapping?

I have this form in a jsp file where I dynamically populate a dropdown from a list. It works fine. This is the home jsp at core address "/" and it sends data to "/spravochnik/list".
<form action="/spravochnik/list" method="post">
<select name="tableName">
<c:forEach var="dropDown" items="${dropDown}">
<c:forEach var="valuesInRows" items="${dropDown.valuesInRows}">
<c:forEach var="valuesInRow" items="${valuesInRows}" varStatus="loop">
<c:if test="${loop.index %2 != 0}">
<option><c:out value="${valuesInRow}"></c:out></option>
</c:if>
</c:forEach>
</c:forEach>
</c:forEach>
</select>
<input type="submit" value="submit" />
</form>
Now I have a controller
#RequestMapping(value = "/spravochnik/list", method = { RequestMethod.POST, RequestMethod.GET })
public String getSpravochniks(Model m, #RequestParam("tableName") String tableName) {
Integer idPrepend = spravochnikService.getIdAtSpravName(tableName);
List<Spravochnik> spravList = spravochnikService.findAll(tableName);
m.addAttribute("spravList", spravList);
m.addAttribute("tableName", tableName);
m.addAttribute("idPrepend", idPrepend);
return "home";
}
It also works fine, and the resulting table (what I got from findAll) is shown with address /spravochnik/list. Question: How can I show it with address depending on what variable "tableName" i sent from the home.jsp? For example, if in the dropdown I select "employees" and pass it with the form under the name "tableName", I want the result to be shown under /spravochnik/list/employees and if I choose "vehicles" it should be "/spravochnik/list/vehicles"?
What I tried
-Adding variable to action
and in controller #RequestMapping(value = "/list/{tableName}" and tableName as #PathVariable. Actual Result: Not Found.
-The same with #RequestParam instead of Path Variable. Actual result: Not Found.

Currency Exchange in Spring Boot

I'm writing code for currency exchanger in spring boot (I'm a begginer) and right now I'm stuck on thymeleaf template. Right now my template looks like this :
<div align="center">
<form th:action = "#{/postCurrency}" method = "POST">
<label for="firstNumber"></label>
<input id = "firstNumber" type="number" name = "fNumber"/>
<br/>
<br/>
<input type="submit" value="Submit">
</form>
</div>
So this means that I have one "box" where user types in number and now I want to have a second "box" where currency will be exchanged and automatically shown in that "box", How do I do that ?
EDIT : My template now looks like this (exchange.html):
<form th:action = "#{/postCurrency}" method = "POST">
<label for="firstNumber"></label>
<input id = "firstNumber" type="number" name = "fNumber"/>
<br/>
<br/>
<input type="submit" value="Submit">
<br/>
<br/>
<input type = "number" th:field="*{resultNumber}" disabled/>
</form>
My controller class :
#PostMapping("/postCurrency")
public String postExchange(#RequestParam Double fNumber , Model model){
Double number = exchangeLogic.exchange(fNumber);
model.addAttribute("resultNumber",number);
return "redirect:/exchange";
}
The problem is that thymleaf can't read the modelattribute , I need to take "resultNumber" and make it visible in form tag
In your controller try this.
#PostMapping("/postCurrency")
public String postExchange(#RequestParam Double fNumber , Model model){
Double number = exchangeLogic.exchange(fNumber);
model.addAttribute("resultNumber",number);
return "exchange";//your html page
}
and in your html page
<input type = "number" th:value="${resultNumber}" disabled/>
let me know if it works for you.

why List<String> is always returning size 1 in this case

I want to send selected options of a select to controller using following
<form action="/save" method="POST" >
<input type="text" name="name"/>
<label>Subjects</label>
<select name="subjects">
<option value="English">English</option>
<option value="Maths">Maths</option>
</select>
<input type="submit" value="Save">
</form>
In controller while form is posted I check the size of subjects list
#RequestMapping(params={"subjects"}, value = "/save-std", method = RequestMethod.POST)
public String saveStd(#ModelAttribute("std")Student std,
#RequestParam("subjects") List<String> subjects) {
System.out.println("List Size is " + subjects.size() );
return "home";
}
it always shows List Size is 1 in the console, why it happens or any better solution to get all selected options?
Please refer to this link. This may help you.
"Request parameters are a Multimap of String to String. You cannot
pass a complex object as request param."

Spring MVC jsp tag place holders for tag value

I am not sure as how to define the value attribute in the Spring MVC form tags. I am querying the database and i would like to return data to the jsp. I am returning an object to the view in the form of a list. I would like to know how to write the attribute value for both an option list and a input box. Under is my code:
jsp
<form:form id="citizenRegistration" name ="citizenRegistration" method="POST" commandName="citizens" action="citizen_registration.htm">
<li>
<label>Select Gender</label><form:select path="genderId" id="genderId" title="Select Your Gender"><form:options items = "${gender.genderList}" selected=???? itemValue="genderId" itemLabel="genderDesc" />
</form:select><form:errors path="genderId" class="errors"/>
</li>
<li><form:label for="weight" path="weight">Enter Weight <i>(lbs)</i></form:label>
<form:input path="weight" id="weight" title="Enter Weight" value= ???/><form:errors path="weight" class="errors"/>
</li>
JavaDao
The function returns:
........................
List<Citizens> listOfCitizens = getJdbcTemplate().query(sql, new CitizensMapper());
return listOfCitizens;
Controller
if (user_request.equals("Query")){
logger.debug("about to preform query");
citizenManager.getListOfCitizens(citizen);
if(citizenManager.getListOfCitizens(citizen).isEmpty()){
model.addAttribute("icon","ui-icon ui-icon-circle-close");
model.addAttribute("results","Notice: Query Caused No Records To Be Retrived!");
}
//how do i return the List<Citizens> listOfCitizens
//or what should be done to send the user the data from the database
return new ModelAndView("citizen_registration");
}
The value comes from the model object (citizens in your case) defined by your form's commandName attribute. Spring uses that and the path attribute to lookup the value of the form objects.
So, there is no need to specifically provide a value for the value attribute, for instance.
EDIT:
Here's a simplified example:
#RequestMapping(value = "/editCitizen", method = RequestMethod.GET)
public String editCitizen(#ModelAttribute("citizen") Citizen citizen, Model model) {
// set attributes of citizen
citizen.genderId = "M";
citizen.weight = 180;
// etc.
// set other model attributes like lists for <form:select>s
model.addAttribute("genderList", <list of genders>);
return "path.to.my.jsp";
}
<form:form id="citizenRegistration" name ="citizenRegistration" method="POST" commandName="citizen" action="citizen_registration.htm">
<form:select path="genderId" items="${genderList}" itemLabel="genderDesc" itemValue="genderId"></form:select>
<form:input path="weight" id="weight" title="Enter Weight"/>
</form:form>

Categories