This website uses cookies to ensure you get the best experience. Learn More.
My First Liferay 7 Project
While preparing for our annual Dutch Liferay User group meeting I tried to develop a simple MVC portlet accessing the Liferay 7 API. Somehow this took more time than I had expected - probably because the new blade tooling takes some getting used to.
My purpose was to write a portlet invoking the UserLocalService in the new non-static way instead of using the now obsolete UserLocalServiceUtil.
First I needed to set up the tools jpm and blade - this can be done by following the instructions on the page https://dev.liferay.com/develop/tutorials/-/knowledge_base/7-0/installing-blade-cli
Then we create a new workspace:
blade init -f workspace
This will create a new subdirectory 'workspace' containing all the basics you need to start developing. Now you start the server by issuing the following command - it will download the LR code into the workspace/tomcat directory:
blade server start
This will start LR7 on the usual http:/localhost:8080
Now let's create an MVC portlet and add some code:
blade create -t mvcportlet -p demo.lnlug -c MyMvcPortlet my-mvc-portlet-project
This instructs blade to create a subclass of MVCPortlet called MyMvcPortlet in package demo.lnlug in a project my-mvc-project created under modules.
When you deploy this portlet into Liferay with the following command:
blade deploy
you will see the following message in the LR logs:
20:14:53,570 INFO [Thread-110][BundleStartStopLogger:35] STARTED my.mvc.portlet.project_1.0.0.201605192014 [483]
Now I added the following method to MyMvcPortlet:
@Override public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { int numberOfUsers = getUserLocalService().getUsersCount(); renderRequest.setAttribute("numberOfUsers", numberOfUsers); System.out.println("Number of users = " + numberOfUsers); super.doView(renderRequest, renderResponse); }
supported by the following code in the same class:
@Reference public void setUserLocalService(UserLocalService userLocalService) { this.userLocalService = userLocalService; } public UserLocalService getUserLocalService() { return userLocalService; } private UserLocalService userLocalService;
This annotation @Reference is interesting, it is the OSGI annotation org.osgi.service.component.annotations.Reference used to refer to a Component deployed by some other OSGI bundle. For this to work you need to add one single line to build.gradle:
compile 'com.liferay.portal:com.liferay.portal.kernel:2.0.0'
It took me a while to figure this dependency out. In the end I found it in one of the blade samples projects to be found here: https://github.com/liferay/liferay-blade-samples
Finally we have to display the variable numberOfUsers in our view.jsp:
<%= request.getAttribute("numberOfUsers") %>
Now after a new deployment of our portlet we'll see the number of Users displayed on the page.