Как прочитать XML-файл в Grails? - PullRequest
2 голосов
/ 19 мая 2011

Я очень плохо знаком с Граалсом, и, возможно, это будет самый простой из вопросов, которые я задаю.Я создаю очень простое приложение для самообучения, где я создал страницу входа.При успешном входе в систему следует прочитать xml-файл и отобразить вывод.Может кто-нибудь, пожалуйста, проиллюстрируйте это на примере примера.Также, пожалуйста, скажите, каким должно быть расположение папки для XML-файла? Ниже приведен мой код: 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 display = {
        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')
    }

}

Теперь, когда у меня уже есть index.gsp в качестве первой страницы, которая появляется при входе пользователя в систему, можно ли указать несколько представленийв URLMappings?Также, как предложено в одном из ответов, если мне нужно определить действие с именем "myxml" и указать URL-адрес, такой как "/ controller" / myxml, где это будет?Пожалуйста помоги!

Ответы [ 2 ]

1 голос
/ 19 мая 2011

Здесь я помещаю мои xml-файлы в каталог webapp/xmls/ и анализирую 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
    }
   }
 }
}

Это пример XML-файла (abc.xml):

<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>

Надеюсь, это поможет ..

0 голосов
/ 19 мая 2011

Вот быстрый пример.

Контроллер

def index = {
  def stream = getClass().classLoader.getResourceAsStream("grails-app/conf/my-file.xml")
  return [data: XML.parse(stream)]
}

Просмотр (index.gsp)

<html>
...
<body>
  <p>${data}</p>
</body>
</html>
...