Spring Hibernate, updating JSP view while selecting from dropdown menu
my controller:
public String showWeather(Model model) {
model.addAttribute("weather", weatherService.listCities());
return "weather";
}
my weather.jsp
<select class="data">
<c:forEach items="${weather}" var="city">
<option>${city.name}</option>
</c:forEach>
</select>
How can I make that everytime I highlight/select something from the dropdown menu, new info would be displayd next to it from database according to the City?
First of all, must I send all data from database to my JSP with controller at first, or can data be transfered from database to JSP meanwhile I highlight/select items on the list(so when I select city "A", then the query will get all information about city "A" and I can use the info)?
here are my tables:
CITIES(id serial, name varchar(40))
WEATHER(id serial, city_id int, temp int, data date)
So basically I have list of CITIES
in my dropdown menu, and when city is selected, then the WEATHER
with tha开发者_StackOverflow社区t city_id
will be queried from database in theory.
If the live updating is not possible, how should I do it otherways?
Feel free to ask questions or give suggestions.
I think you should use AJAX in this case
use JQUERY on change event whick will send your cityId to SpringMVC controller, as the response your controller should return wheather, and then update your GUI component with this result:
then main difference is that your controller should return anything but the view. You can do it using @ResponseBody
annotation:
for example this controller will return you temperature as String when you request it for city with id=222
/getTemperature/222
@RequestMapping(value="/getTemperature/{id}", method=RequestMethod.GET)
@ResponseBody
public String getTemparature(@PathVariable("id") Integer id){
String weather = someDaoObect.getTemperature(id);
return weather;
}
in this case that code behaves exactly like Servlet where you write your result in HttpServletResponse
.
Hope it will help you.
What are you talking about it is exactly what Ajax is focused on (see Ajax Programming), bring data between the server and client (browser), sending and retrieving data asynchronously. In your case, when the user selects and item the application must go and query to the server what is needed to do it (update information in the db, return something to the browser, etc).
In your case, I don't know if you can include a new library and use it, but there are so many to use within a web project in Java, and are so easy to integrate and use it:
- AjaxTags JavaScript-JSP Library - http://ajaxtags.sourceforge.net/
- AjaxAnywhere - http://ajaxanywhere.sourceforge.net
- jMaki - http://ajax.java.net/
Also you can include one of the beautiful JavaScript libraries (ex: jQuery, Prototype, Ext, Dojo, etc) that provides same functionality to send and receive information asynchronously between the browser and the server.
精彩评论