Reputation: 1078
I am working in spring mvc, I am doing some jsp with showing multiple dropdowns in a single pages....
I seen an example to show drop down from database by using the following example.
<%@ page import="java.util.*" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:useBean id="state" scope="session" class="src.StateDAO"/>
<html>
<head>
<title></title>
</head>
<body>
<form id="test" method="POST" action="">
<input name="state" type="radio" value="Australia" id="state-aus">Australia
<input name="state" type="radio" value="NewZealand" id="state-new">NewZealand
<input name="state" type="radio" value="India" id="state-oth" >India
<Select name="othStates" size="1" id="oth-states">
<c:forEach items="${state.stateList}" var="st">
<option value="1"><c:out value="${st.name}"/></option>
</c:forEach>
</select>
<br>
<input type="Submit" name="cmdSub" value="SUBMIT">
<input type="Reset" name="cmdReset" value="RESET">
</form>
</body>
</html>
Is this right way to do this to get dropdowns in jsp using Spring mvc?
Upvotes: 1
Views: 5772
Reputation: 22506
I think that a better option is to use the spring tags for jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
...
<form:select path="country">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${countryList}" />
</form:select>
See full example here: http://www.mkyong.com/spring-mvc/spring-mvc-dropdown-box-example/
Edit:
$('#stateSelect').change(function() {
$.ajax({
type:"GET",
url : "/getCitiesForState",
data : { state: $('#stateSelect').val()},
success : function(data) {
$('#citySelect').empty(); //remove all child nodes
for(var i = 0; i < data.length; i++){
var newOption = $('<option value=data[i].value>data[i].text</option>');
$('#citySelect').append(newOption);
}
},
error: function() {
alert('Error occured');
}
});
});
On the server side you need an endpoint that respondes on the url(/getCitiesForState in the example) and returns a list of objects that have value and text properties.
Edit(add controlelr):
@Controller
public class HelloController{
@RequestMapping("/getCitiesForState")
@ResponseBody
public List<City> printHello(@RequestParam long state) {
List<City> cities = //get from the some repository by state
return cities;
}
}
public class City{
private String value;
private String text;
//getters setters
}
Upvotes: 5