I am very new to grails and perhaps it would be the most simplest of questions that I am asking. I am creating a very simple application for self-learning where I created a login page. On successful login,the xml file should be read and the output should be displayed. Can anyone please illustrate this with a sample example. Also please tell what should be the folder location for the xml file?Below is my code: UserController.groovy
class UserController {
def index = { }
def login = {
def user = User.findWhere(username:params['username'],
password:params['password'])
session.user = user
if (user) {
redirect(action:display)
}
else {
redirect(url:"http://localhost:8080/simple-login/")
}
}
def disp开发者_运维知识库lay = {
def stream = getClass().classLoader.getResourceAsStream("grails-app/conf/sample.xml")
return [data: XML.parse(stream)]
}
}
myxml.gsp
<html>
<body>
<p>Please find the details below:</p>
<p>${data}</p>
</body>
</html>
URLMappings.groovy
class UrlMappings {
static mappings = {
"/user/login" (controller: "user" ,action: "login")
"/user/display"(controller:"user" ,action:"display")
"/"(view:"/index")
"500"(view:'/error')
}
}
Now that I already have index.gsp as the first page that appears when user login, is it possible to specify more than one view in URLMappings? Also as suggested in one of the replies, if I have to define an action named "myxml" and direct to a url such as "/controller"/myxml where would that be? Please help!
Here I am placing my xml files under webapp/xmls/
directory, and parsing abc.xml
file
def parse ( ) {
// Getting context path here
def webRootDir = sch.servletContext.getRealPath ("/")
// Create a new file instance
def f = new File (webRootDir + "/xmls/" + "abc.xml")
// Parxing XML file here
def items = new XmlParser ( ).parseText( f.text )
// iterating through XML blocks here
items.question.each {
// Creating domain class object to save in DB
def question = new Question ( )
def node = it
question.with {
qtext = node.qtext.text()
answer = node.answer.text()
if (!hasErrors() && save(flush: true)) {
log.info "mcq saved successfully"
} else
errors.allErrors.each {
err->
log.error err.getField() + ": "
log.error err.getRejectedValue() + ": " + err.code
}
}
}
}
This is the sample XML (abc.xml) file:
<qns>
<question id="q1">
<qtext> First letter of alphabet is?</qtext>
<answer>A<answer>
</question>
<question id="q2">
<qtext> Second letter of alphabet is?</qtext>
<answer>A<answer>
</question>
.
.
.
.
</qns>
Hope this will help ..
Here is a quick sample.
Controller
def index = {
def stream = getClass().classLoader.getResourceAsStream("grails-app/conf/my-file.xml")
return [data: XML.parse(stream)]
}
View (index.gsp)
<html>
...
<body>
<p>${data}</p>
</body>
</html>
精彩评论