首页 > 代码库 > Liferay7 BPM门户开发之29: 核心kernel.util包下面的通用帮助类ParamUtil、GetterUtil使用

Liferay7 BPM门户开发之29: 核心kernel.util包下面的通用帮助类ParamUtil、GetterUtil使用

与其闭门造车,不如直接开动原装、进口、免费的法拉利。 -- 王昕

不多说废话,直接上代码。

 

ParamUtil

ParamUtil、GetterUtil是Liferay最重要的帮助类

  • ParamUtil用途:获取PortletRequest的参数值,并作类型转换和判空处理(内部机制是通过GetterUtil)
  • GetterUtil用途:对输入做类型转换、判空处理、赋予默认值(即期望的获取值为空时侯的初始值)

ParamUtil的使用例子1:

 

public void deleteInterview(        ActionRequest actionRequest, ActionResponse actionResponse)    throws Exception {    long interviewId = ParamUtil.getLong(actionRequest, "interviewId");    InterviewLocalServiceUtil.deleteInterview(interviewId);    sendRedirect(actionRequest, actionResponse);}

 

ParamUtil的使用例子2:

public void updateQuestion(        ActionRequest actionRequest, ActionResponse actionResponse)    throws Exception {    long questionId = ParamUtil.getLong(actionRequest, "questionId");    long questionSetId = ParamUtil.getLong(actionRequest, "questionSetId");    String title = ParamUtil.getString(actionRequest, "title");    String description = ParamUtil.getString(actionRequest, "description");    int type = ParamUtil.getInteger(actionRequest, "type");    ServiceContext serviceContext = ServiceContextFactory.getInstance(        actionRequest);    try {        if (questionId <= 0) {            QuestionLocalServiceUtil.addQuestion(                questionSetId, title, description, type, serviceContext);        }        else {            QuestionLocalServiceUtil.updateQuestion(                questionId, title, description, type, serviceContext);        }    }    catch (Exception e) {        ...    }    sendRedirect(actionRequest, actionResponse);}

 

ParamUtil可以通过get来直接获取PortletRequest参数,如:

public static short get(         PortletRequest portletRequest, String param, short defaultValue) {          return GetterUtil.get(portletRequest.getParameter(param), defaultValue);     }      public static String get(         PortletRequest portletRequest, String param, String defaultValue) {          String returnValue =             GetterUtil.get(portletRequest.getParameter(param), defaultValue);          if (returnValue != null) {             return returnValue.trim();         }          return null;     }

 

也可以通过类似getInteger、getLong 获取单一值和获取数组的getIntegerValues、getLongValues之类的方法(用于checkbox的提交)实际都是一样的。

区别是getIntegerValues、getLongValues的返回值是通过调用GetterUtil

public static int getInteger(HttpServletRequest request, String param) {         return GetterUtil.getInteger(request.getParameter(param));     }      public static int getInteger(         HttpServletRequest request, String param, int defaultValue) {          return get(request, param, defaultValue);     }      public static int[] getIntegerValues(         HttpServletRequest request, String param) {          return getIntegerValues(request, param, new int[0]);     }      public static int[] getIntegerValues(         HttpServletRequest request, String param, int[] defaultValue) {          return GetterUtil.getIntegerValues(             request.getParameterValues(param), defaultValue);     }

 


同时,还可以通过print来打印参数输出,方便程序员使用

public static void print(PortletRequest portletRequest) {         Enumeration<String> enu = portletRequest.getParameterNames();          while (enu.hasMoreElements()) {             String param = enu.nextElement();              String[] values = portletRequest.getParameterValues(param);              for (int i = 0; i < values.length; i++) {                 System.out.println(param + "[" + i + "] = " + values[i]);             }         }     }     

 

另外较高版本增加了ServiceContext的参数

static float getFloat(ServiceContext serviceContext, String param, float defaultValue) static float[] getFloatValues(ServiceContext serviceContext, String param, float[] defaultValue) 

 

GetterUtil


GetterUtil的代码,就不具体解释了
可以访问:
https://docs.liferay.com/portal/5.1/javadocs/portal-kernel/com/liferay/portal/kernel/util/GetterUtil.java.html

GetterUtil的使用例子:发送request属性到jsp

//java:

package com.liferay.docs.exampleserviceconsumerportlet;import java.io.IOException;import javax.portlet.Portlet;import javax.portlet.PortletException;import javax.portlet.RenderRequest;import javax.portlet.RenderResponse;import org.osgi.service.component.annotations.Component;import org.osgi.service.component.annotations.Reference;import com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet;import com.liferay.portal.service.UserLocalService;import com.liferay.bookmarks.service.BookmarksFolderLocalService;@Component(        immediate = true,        property = {                "com.liferay.portlet.display-category=category.sample",                "com.liferay.portlet.instanceable=true",                "javax.portlet.display-name=Example Service Consumer Portlet",                "javax.portlet.init-param.template-path=/",                "javax.portlet.init-param.view-template=/view.jsp",                "javax.portlet.security-role-ref=power-user,user"        },        service = Portlet.class)public class ExampleServiceConsumerPortlet extends MVCPortlet {        @Override    public void doView(RenderRequest request, RenderResponse response)            throws IOException, PortletException {        int userCount = getUserLocalService().getUsersCount();        request.setAttribute("USER_COUNT", userCount);        int bookmarksFolderCount =                getBookmarksFolderLocalService().getBookmarksFoldersCount();        request.setAttribute("BOOKMARKS_FOLDER_COUNT", bookmarksFolderCount);        super.doView(request, response);    }        public BookmarksFolderLocalService getBookmarksFolderLocalService() {        return _bookmarksFolderLocalService;    }    public UserLocalService getUserLocalService() {        return _userLocalService;    }    @Reference    public void setBookmarksFolderLocalService(            BookmarksFolderLocalService bookmarksFolderLocalService) {        _bookmarksFolderLocalService = bookmarksFolderLocalService;    }    @Reference    public void setUserLocalService(UserLocalService userLocalService) {        _userLocalService = userLocalService;    }    private UserLocalService _userLocalService;    private BookmarksFolderLocalService _bookmarksFolderLocalService;}

 

//jsp:

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %><%@ page import="com.liferay.portal.kernel.util.GetterUtil" %><portlet:defineObjects /><%int userCount = GetterUtil.getInteger(renderRequest.getAttribute("USER_COUNT"));int bookmarksFolderCount = GetterUtil.getInteger(renderRequest.getAttribute("BOOKMARKS_FOLDER_COUNT"));%><p>The portal has <%= userCount %> users.</p><p>The portal has <%= bookmarksFolderCount %> bookmarks folders.</p>

 

GetterUtil和ParamUtil的区别是:ParamUtil是解析请求专用类,而GetterUtil是通用的类型转换输出类
使用这两个类ParamUtil、GetterUtil的好处显而易见,如果配合Validator类,像判空、类型转换、验证的大段代码可以大大的省略,非常简洁

Liferay7 BPM门户开发之29: 核心kernel.util包下面的通用帮助类ParamUtil、GetterUtil使用