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.
Related
I have a JSP page in my web application and i want to refresh the page with the parameter of option.
<select class="form-control combobox" name="education" >
<option value="" disabled selected hidden>Choose an education</option>
<option>English</option>
<option>French</option>
<option>Dutch</option>
<option>Spanish</option>
</select>
I want to use this parameter for querying my database again. Forexample;
<%
BookDAO bdao = new BookDAO();
for (TblBooks book : bdao.getAllBooks()) {%>
<tr>
<td><%=book.getTittle()%></td>
<td><%=boek.getAuthor()%></td>
<td><%=boek.getCategory()%></td>
<td><%=boek.getEducation()%></td>
<td><input type='checkbox' name ='chk1' /></td>
</tr>
<% }%>
I can get the parameter with request.getParameter("education") but how can i refresh page and query again with this parameter?
In Javascript, You can ask a web page to reload itself (the exact same URL) by:
location.href = location.href;
You can ask a web page to load a different location using the same mechanism:
location.href = 'http://www.google.com'; // or whatever destination url you want
You can get the value of a select control (which needs to have an id attribute):
var ctrl = document.getElementById("idOfSelectControl");
var selectedOption = ctrl.options[ctrl.selectedIndex].value;
So, if you update your JSP to give the control an id:
<select class="form-control combobox" id="education" name="education" >
you should be able to reload the page:
var educationControl = document.getElementById("education");
var selectedOption = educationControl.options[educationControl.selectedIndex].value;
location.href = "http://mysite.example/mypage?education=" + selectedOption;
By the help of Jason i have solved it. I added an onchange event to my select tag
onchange="changeThePage()"
Then i defined a javascript function.
function changeThePage() {
var selectedOption = "book.jsp?education=" + $("#education option:selected").text();
location.href = selectedOption;
}
Then i got the parameter by
String education = request.getParameter("education");
Then i added String education as parameter to my bdao.getAllBooks(education)) method for to query.
'
<script>
function abc(){
var yourSelect = document.getElementById( "ddlViewBy" );
var val = yourSelect.options[ yourSelect.selectedIndex ].value;
//window.location.href=window.location.href;
alert(val);
window.location.replace("index.jsp?name="+val);
}
</script>
<select id="ddlViewBy" onchange="abc()">
<option>select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<%
String name=request.getParameter("name");
if(name!=null){
%>
<table>
<tr>
<td>author<%=name%></td>
<td>book name<%=name%></td>
</tr>
</table>
<%
}
%>
Hi,
try this, this will be helpful,
when you select a value it will call abc, function and then you are assigning that value in scriptlet..and also page is refreshing. in scriptlet you can access that value using request.getParameter("name").
now you can write your code inside scriptlet..hope helpful for someone.. :)
thanks...
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."
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>
I have a JSP with the following EL/html tags:
<c:forEach var="key" items="${resource.stringPropertyNames()}">
<tr>
<td>${key}</td>
<td><input type = "text" name = "${key}" value = "${resource.get(key)}"></td>
</tr>
</c:forEach>
When my jsp is rendered, the first <td> tag shows the evaluated value of ${key}. In the <input> tag however, the ${key} is not evaluated correctly. When I try to retrieve the input as request parameters from my servlet (request.getParameter(StringKey)), I get the literal $key without the braces. When I do request.getParameter("$key"), I get multiple values for the Strings that ${resource.get(key)} evaluate to in the EL.
What is going on?
EDIT
Controller method (using spring) code:
#RequestMapping(value = URI_PATH + "{fileName}", method = RequestMethod.GET)
public String getProperties(#PathVariable String fileName, ModelMap modelMap) {
Properties resource = ..//get properties file
modelMap.addAttribute("resource", resource);
return "configuration" // maps to my jsp;
}
If resource is a Map, which is set using request.setAttribute("resource", resource)
<c:forEach var="entry" items="${resource}">
<tr>
<td>${entry.key}</td>
<td><input type = "text" name = "${entry.key}" value = "${entry.value}"></td>
</tr>
</c:forEach>
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.