`
klcwt
  • 浏览: 195903 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

The Web Layer

阅读更多
The Web Layer
一个控制器要"处理请求(handles request)","创建或准备响应(response)","判断请求的范围"。
从另外一个方面讲,每个响应都会创建一个新的控制器。一个控制器能够产生响应(response)或者代理生成一个页面(view)。
创建一个控制器很简单。他的名称以Controller 结尾,还有把他放在grails/controller的目录下。


理解Controllers和Actions
创建Controller
在项目的根目录使用create-controller [name]命令创建。
grails create-controller book
class BookController { … }


创建一个actions
一个控制器的属性每一个都是代码块。每个属性的名称映射一个uri。
class BookController {
    def list = {        // do controller logic
        // create model        return model
    }
}
URI是/root/book/list

默认的Action
有几个规则:
当action中没有定义明确的uri,你定义一个index属性,所有的请求将由它处理。
要么你就明确定义defaultAction 属性
def defaultAction = "list"

控制器和范围(scopes)
*servletContext javax.servlet.ServletContext
*session  HttpSession
*request HttpServletRequest
*params  从CGI引入的一个参数
*flash

访问这些变量
  def find = {
    def findBy = params["findBy"]
    def appContext = request["foo"]
def loggedUser = session["logged_user"]    }
class BookController {
    def find = {
        def findBy = params.findBy
        def appContext = request.foo
        def loggedUser = session.logged_user    }
}

使用Flash scope
flash是一个临时的存储变量,仅仅在两个request之间传递。

Models和视图
模型本质就是一个map,在返回时候,给view层使用。
有以下几种方式放回一个map的实例
def show = {
[ book : Book.get( params.id ) ]
}

class BookController {
    List books
    List authors
    def list = {
           books = Book.list()
           authors = Author.list()
    }
}
上面这些代码是线程不安全的。
使用Spring ModeAndView
import org.springframework.web.servlet.ModelAndViewdef index = {
    def favoriteBooks = … // get some books just for the index page, perhaps your favorites    // forward to the list view to show them
    return new ModelAndView("/book/list", [ bookList : favoriteBooks ])
}

选择视图:
class BookController {
def show = {
[ book : Book.get( params.id ) ]
}
}
上面的代码并没有明确指定返回的视图,Grails怎么知道的了?是因为grails使用了约定。
grails将会自动查找grails-app/views/book/show.gsp(而实际上它会先查找jsp,因为grails 能够使用jsp)

如果你喜欢指定返回的页面和模型(render):
def show = {
  def map = [ book : Book.get( params.id ) ]
    render(view:"display", model:map)
}
定位在grails-app/views/book/display.gsp
这里默认的会查找book/display.gsp
如果想让它返回其他页面,看下面代码
def show = {
  def map = [ book : Book.get( params.id ) ]
    render(view:"/shared/display", model:map)
}
定位在grails-app/views/shared/display.gsp
返回一个简单的response
render "Hello World!"
// write some markup
render {
   for(b in books) {
      div(id:b.id, b.title)
   }
}
// render a specific view
render(view:'show')
// render a template for each item in a collection
render(template:'book_template', collection:Book.list())
// render some text with encoding and content type
render(text:"<xml>some xml</xml>",contentType:"text/xml",encoding:"UTF-8")


Redirects 和 chaining
class OverviewController {
                     def login = {}                     def find = {
                         if(!session.user)
                            redirect(action:login)
                         …
                     }
                 }

redirect使用的是HttpServeltResponse
在同一个控制类中:
redirect(action:login)
在不同的action中
redirect(controller:'home',action:'index')
URI
   redirect(uri:"/login.html")
url
redirect(url:"http://grails.org")












分享到:
评论

相关推荐

    Cloud Native Python_Packt Publishing(2017).pdf

    Then you'll learn how to build microservices in Python using REST API's in an event-driven approach and you will build the web layer. Next, you'll learn about interacting with data services and ...

    计算机网络英文课件:Chapter6 The Transport Layer.ppt

    Chapter 6 of the "The Transport Layer" presentation delves into the core concepts and functionalities of the transport layer in computer networking. This layer is crucial as it serves as a bridge ...

    Spring.Essentials.178398

    2. Building the Web Layer with Spring Web MVC 3. Accessing Data with Spring 4. Understanding WebSocket 5. Securing Your Applications 6. Building a Single-Page Spring Application 7. Integrating with ...

    XDoclet in Action

    This chapter covers the use of XDoclet in web development, specifically focusing on the web layer. It includes: - **Web Development Overview**: An introduction to web development in Java and common ...

    Spring in Action

    - 第8章《Building the web layer》介绍了如何使用Spring MVC来构建Web层;第9章《View layer alternatives》则探讨了不同的视图技术与Spring框架的集成方式。 - **安全(Security):** - 安全是任何应用程序的...

    layer.mobile-v2.0

    "layer.mobile-v2.0" 是一个针对移动设备优化的前端弹层组件的版本更新,主要服务于手机和平板等移动平台。在这一版本中,layer 秉承了其易用、高效的特点,提供了丰富的功能和良好的用户体验。接下来,我们将详细...

    High Performance Mobile Web

    Learn tools and techniques for working with responsive web design, images, the network layer, and many other ingredients—plus the metrics to check your progress. Ideal for web developers and web ...

    Two Scoops of Django 1.11: Best Practices for the Django Web Framework.pdf

    Chapter 7: Queries and the Database Layer Chapter 8: Function- and Class-Based Views Chapter 9: Best Practices for Function-Based Views Chapter 10: Best Practices for Class-Based Views Chapter 11: ...

    2016年上午基础知识.pdf

    The development of the Semantic Web proceeds in steps, each step building a layer on top of another. The pragmatic justification for this approach is that it is easier to achieve ( 71 ) on small ...

    计算机网络英文课件:Chapter7 the application layer.ppt

    【计算机网络英文课件:Chapter7 the application layer.ppt】主要涵盖了网络应用层的重要协议和服务,包括域名系统(DNS)、电子邮件(E-Mail)、文件传输协议(FTP)、万维网(World Wide Web)以及多媒体服务。...

    SSL and TLS Essentials - Securing the Web.pdf

    本书《SSL and TLS Essentials - Securing the Web》由Stephen Thomas撰写,旨在深入解析这两个协议的工作原理、实施方法以及如何在实际的Web环境中应用它们。 SSL和TLS协议的核心目标是提供加密通信,防止数据被...

    计算机网络第六版答案

    23. The five layers in the Internet protocol stack are – from top to bottom – the application layer, the transport layer, the network layer, the link layer, and the physical layer. The principal ...

    Flask Web Development.pdf 最新 原版

    - **Templates:** Templates allow developers to separate the presentation layer from the logic layer, making it easier to generate dynamic HTML pages. Flask uses Jinja2 as its templating engine. ...

    layer模板引擎的使用

    综上所述,layer模板引擎为Web开发者提供了一种强大且灵活的方式,使他们能够在JavaScript中构建动态的HTML内容。通过理解和掌握上述知识点,你将能够更好地利用layer模板引擎提升项目开发效率,实现更加优雅的页面...

    高清Building Web Applications with Visual Studio 2017及源码

    After building the data application layer using Entity Framework Core and a RESTful service using ASP.NET Core, you will then build the client side web application three ways: first, using ASP.NET ...

    Designing with Progressive Enhancement: Building the Web that Works for Everyone

    Progressive enhancement is an approach to web development that aims to deliver the best possible experience to the widest possible audience, and simplifies coding and testing as well. Whether users ...

Global site tag (gtag.js) - Google Analytics