JFinal 中的Controller(1)
概述
Controller是JFinal中的核心类之一,该类作为MVC模式中的控制器。基于JFinal的Web应用的控制器需要继承该类。Controller是定义Action方法的地点,是组织Action的一种方式,一个Controller可以包含多个Action。Controller是线程安全的。
Action
在Controller之中定义的public方法称为Action。Action是请求的最小单位。Action方法必须在Controller中定义,且必须是pubic可见性。
public class HelloController extends Controller{
public void index(){
renderText("此方法是一个Action");
}
public String test(){
return "index.html";
}
}
以上代码中定义了两个Action
: HelloController.index()和HelloController.test()
Action
可以有返回值,返回值可以在拦截器中通过invocation.getReturnValue()方法获取到,以便进行render控制。
getPara系列方法
方法调用 | 返回值 |
---|---|
getPara(“title”) | 返回页面表单域名为“title”参数值 |
getParaToInt(“age”) | 返回页面表单域名为“age”的参数值并转为int型 |
getPara(0) | 返回url请求中的urlPara参数的第一个值,如http://localhost/controllerKey/method/v0-v1-v2这个请求返回v0 |
getParaToInt(1) | 返回url请求中的urlPara参数的第二个值并转换成int型 |
getParaToInt(2) | 如http://localhost/controllerKey/method/2-5-N8这个请求将返回-8.注意:约定字母N与n可以表示负号,这对urlParsSeparator为“-”时非常有用。 |
getPara() | 返回url请求中的urlPara参数的整体值,如http://localhost/controllerKey/method/v0-v1-v2 将会返回 “v0-v1-v2” |
写个小例子看下,在jfinal_demo的IndexController加入这个getNumber方法:
public void getNumber(){
String number = "";
number += getPara(0) + "#";
number += getPara(1);
renderText("传递的参数是" + number);
}
启动项目,访问http://localhost:8080/getNumber/1-2
为了测试一下负数参数的获取,我们改一下getNumber代码
public void getNumber(){
String number = "";
number += getParaToInt(0) + "#";
number += getParaToInt(1);
renderText("传递的参数是" + number);
}
启动项目,访问http://localhost:8080/getNumber/n5-n10
这样的话成功获取了负数参数值。