I want to get some data from my sql database and write it to a .gsp page. To do that, i did the following:
<%
def temp = dbname.Road.list()
%>
<strong>Name:</strong>${temp.name}
<strong>Local:</strong>${temp.local}
which will give the following output:
Name: Picadil开发者_如何学运维ly
Local: London
My teacher told me that Grails works via-controllers and, although that way is not wrong, i should change it so the information i need from the database is asked and returned in a controller and not directly accessed. I need a hand on this .. Thanks in advanced.
This is absolutely the wrong way to go about it. Grails or not, putting code like that in the view is a huge anti-pattern. The grails way would be to have a Road domain. And have a RoadController.
class Road {
String name
String local
}
class RoadController {
def list = {
[roadList: Road.list()]
}
}
And then you would have a list.gsp located at grails-app/views/road/list.gsp to render the model coming from the controller.
<ul>
<g:each in="${roadList}">
<li>Name: ${it.name}, Locale: ${it.local}</li>
</g:each>
</ul>
So accessing this would be as simple as:
http://localhost:8080/youApp/road/list
This is pretty basic Grails stuff you can find in hundreds of tutorials and books and if you use the scaffolding provided by grails, you don't even have to write the code. Do some googling.
Keep in mind that doing a list() loads the entire contents of that table into memory on the server. If it were large enough your server would crash with an out of memory error in worst case and be slow over time in best.
精彩评论