Spring MVC. Question about visions solution / Design Question
[spring 3.0.5] MVC
I have on class like that:
public class Address {
private String street;
private String city;
public String getStreet() {
return this.street;
}
public void setStreet(String street) {
this.street = street;
}
public String getC开发者_JAVA百科ity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
}
My function is to rely on the possibility of adding an infinite number of addresses on the site (JSP with spring and form tag). Can somebody give a skeleton of such functionality in the controller?
Your question is a little unclear. The answer is twofold:
Displaying a list of addresses
@Controller
public class SomeController {
@RequestMapping("/somepage.jsp ")
public String somePage(HttpServletRequest request, ModelMap model) {
List<Address> addresses = ....
// We can now access the key "addresses" in our jsp
model.put("addresses", addresses);
return "/WEB-INF/jsp/somepage.jsp";
}
}
In your jsp page, you can display the list of addresses using e.g., the core
jstl lib, here noted using the prefix c
.
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
...
<c:forEach items="${addresses}" var="addr">
City: ${addr.city} <br/>
Street: ${addr.street}
</c:forEach>
....
</html>
Submitting addresses
If you're looking to submit an undefined number of addresses, that's a little more tricky. What you could do is create a javasript form template which upon a button press or so creates two additional form fields. Ensure each form field will get a unique name, e.g., :
<input type="text" name="street_1" />
<input type="text" name="city_1" />
<input type="text" name="street_2" />
<input type="text" name="city_2" />
....
Then you can iterate the fields using request.getParameterMap()
, where you construct your address options based on matching names (e.g., street_1 should be associated with city_1 and so forth).
[EDIT] To give you an idea of what the javascript could look like, I give you this from the top of my head (note I haven't tested this code, it's there to give you an idea of what it might look like).
var i = 0; // initialize to how many addresses you initially display
function addAddress() {
var form = document.getElementById('form');
var html = '<input type="text" name="street_' + i + '" />' +
'<input type="text" name="city_' + i + '" />';
form.innerHTML += html;
i++;
}
Then call the javascript when pressing a button:
<input type="button" onClick="addAddress();" value="add address" />
If you decided to use e.g., jQuery this would be even easier. E.g.,
var i = 0:
$("#addbtn").click(function() {
$("#someId").append(
'<input type="text" name="street_' + i + '" />' +
'<input type="text" name="city_' + i + '" />');
i++;
});
精彩评论