grails的文件下传,集合迭代,标签
grails的文件上传,集合迭代,标签
grails框架刚用起来,感觉听蹩脚的!处处碰壁,但是用了一段时间,习惯啦,废话少说,步入正题!
grails没用明显DAO层,我们能看到的对对象的增删查改操作,实际上不是groovy语言对象的特有操作,而是在应用grails之后,框架利用AOP功能自动给对象添加的 !所以在你没有启动grails程序时,你直接掉对象的数据库操作是错误的!但是我们需要批量插入数据怎么办,一个一个写吗?不用!
可以自定义一个Controller,启动后操作:
class TestDataController { def create={ try{ createData(); println("创建成功!!!!"); }catch (Exception e){ e.printStackTrace(); } render("测试数据插入——————————————————————————————"); } public static void createData(){ println "****************"; for (int i = 0; i < 50; i++) { User user = new User(); user.name = "user" + i; user.password="password"+i; user.age = i; user.birth = new Date(); user.sex = true; List<Book> books = new ArrayList<Book>(); for (int j = 0; j < 100; j++) { Book tmp = new Book(); tmp.name = "book" + j + ":" + i; tmp.price = j * 100.32; books.add(tmp); if(j == 50) println "-----------"+tmp; } user.books = books; user.save(flush:true); } } }
这是我的TestDataController.groovy文件,就是插入测试数据的(注意数据插入是所有属性默认是不允许为空的)!
但是怎么能通过浏览器调用这个Controller呢?这时就要配置UrlMappings.groovy文件了
class UrlMappings { static mappings = { "/testData" { //这个与Controller中的TestDataController的前半部分对应,切忌这是约定,必须这样写 controller: "testData"; //对应TestDataController中的create操作 action: "create"; } } }
接下来就是访问啦:http://localhost:8080/项目名/testData
select标签和迭代标签的应用:
<g:each in="${list}"> <ul> <li>姓名: ${it.name}</li> <li>性别: <g:formatBoolean boolean="${it.sex}" true="男" false="女"/></li> <li>年龄: ${it.age}</li> <li>生日:<g:formatDate date="${it.birth}" format="yyyy年MM月dd日"/></li> <li>密码: ${it.password}</li> </ul> </g:each> <hr/> <g:select from="${list}" id="userID" name="userID" optionKey="id" optionValue="name" value="2"></g:select>
一看便知${}引用当前上下文中变量。这个与JSTL中的用法相似;
<g:each in="${要迭代的集合}">
${it},代指每次循环的变量
<g:formatBoolean>和<g:formatDate>我就不再说了,很简单格式化文本的,
<g:select>上面输出对应的html文本代码是:
<select name="userID" id="userID" > <option value="1" >test1</option> </select>
from:那个集合
id和name是html代码中的属性
optionKey:每个option的value
optionValue:每个option中要显示的文本值
value:默认哪个optionKey被选中?
文件上传:
class FileUploadController { def upload={ //myFile对应表单中input type=“file”的name值 def f = request.getFile("myFile"); //判断是否等到文件 if(!f.empty){ //获得原始的文件名 String fileName=f.getOriginalFilename(); //获得文件的大小(默认单位是B)和类型 println(new Date().toString()+"--name:"+fileName+";size:"+(f.size/1024)+"kb;type:"+f.contentType); //文件要保存在哪个目录 String filePath="web-app/upload/"; //开始写入,比Java简单多了吧! f.transferTo(new File(filePath+fileName)); //render在这里与response.getWriter().println很相似 render("上传成功!"); }else { render("上传失败!"); } } }
gsp文件内容
<g:uploadForm action="upload" controller="fileUpload" > 文件:<input type="file" name="myFile" id="myFile"/> <g:submitButton name="submit" value="开始上传"/> </g:uploadForm>
对应的HTML代码:
<form action="/grails1/fileUpload/upload" method="post" enctype="multipart/form-data" > 文件:<input type="file" name="myFile" id="myFile"/> <input type="submit" name="submit" value="开始上传" id="submit" /> </form>
这个我就不用解释了,太简单了!