Groovy笔记(12)_Groovlet

来源:互联网 发布:软件著作权 技术入股 编辑:程序博客网 时间:2024/05/18 01:01

Groovlet介绍

 

 

1、Groovlet是以Servlet API为基础建立起来的框架

2、Groovlet与GSP框架提供一种优雅而简单的平台,将它用于构建复杂程度不高的Web应用程序。

3、Groovlet不需要继承HttpSevlet,甚至连类都可以不需要写

4、Groovlet不需要实现doGet(),doPost()等发放

5、Groovlet实际上时直接使用Servlet API替代品

 

 

第一个Groovlet

 

 

1、文件名及路径:GSPToysStore/WebRoot/groovy/hello.groovy

 

     printl """

        <html>

        <head><title>Hello Groovlet!!</title></head>

        <body>

              <h2>Hello Groovy!! </h2>

        </body>

        </html>

    """

2、访问Groovlet的html页面

   <html>

   <head>

   <meta http-equiv="Content-Type" content="text/html;charset=uft-8">

   <title>Say Hello!</title>

   </head>

   <body>

        <a href = "groovy/hello.groovy">Say Hello!</a>

   </body>

   </html>

 

 

 

环境准备(MyEclipse)

 

 

1、加入.gsp的Content Type方法:

   Window -->Preferences --> General -->Content Types --> Text -->JSP -->Add

2、设置默认gsp文件打开的编辑器的方法:

   Window -->Preferences -->General -->Editors -->FileAssociations --> Add --> *.gsp -->选择编辑器-->Default

3、把asm-2.1.jar , groovy-1.0-jsr-04.jar, antlr-2.7.5.jar, MySQL驱动等jar包拷贝到项目lib目录,加入构建路径。

4、*.groovy(Groolet)与jsp/gsp放在一起

5、修改web.xml

 

 

Groovlet 可以使用的隐含对象

 

 

隐含对象             绑定到

 

request            ServletRequest

response          ServletResponse

context             ServletContext

application       ServletContext

session            request.getSession(true)

out                   response.getWriter()

sout                 response.getOutputStream() // 输出流对象

html                 new MarkupBuilder(out)  // 就是生成器

 

 

 

用print生成html页面

 

 

1、def name = request.getParameter("toyName")

     def price = request.getParameter("unitPrice")

     // 数据库操作

     print """

           <html>

           <head><title>Success add toy!</title></head>

           <body>

               <h1>Success add toy!</h1>

               Toy Name: ${name}<br/>

               Unit Price: ${price}<br/>

               <a href = "/GSPToysStore/index.gsp">Home</a>

            </body>

           </html>

     """

 

 

 

使用构造器生成HTML内容

 

 

1、html是隐含对象

2、sql.eachRow是Sql类的方法,需要闭包作为参数

3、

html.html(){

  head(){title("All Toys List!")}

  body(){

    h1("All Toys List!")

    table(border:"1"){

       sql.eachRow("select * from toys"){ toy->

             html.tr(){

                     td("${toy.toyName}")

                     td("${toy.unitPrice}")

             }                                                   

        }

    }

  }

}

 

 

GSP介绍

 

1、GSP功能比JSP还要多

2、GSP框架是模板引擎,GSP实质上是一个模板

3、GSP集中MVC中的View部分

4、Groovlet集中于控制与业务逻辑

5、当所需功能简单并且需要尽快完成时,Groovlet和GSP是进行服务器端开发的首选。

 

 

第一个GSP页面hello.gsp

 

<%@page pageEncoding="utf-8"%>

<html>

 <head>

  <title>Hello GSP! </title>

 </head>

 <body>

  <% println "Hello${request.getParameter("userName")}"%>

 </body>

</html>

 

访问: http://localhost:9090/GSPToysStore/hello.gsp?userName=clat

 

 

可以学习Grails,Grails可以敏捷开发Web程序。