非Portlet应用如何调用Liferay远程服务及实现文件可视化?
Hey there! Let's tackle your Liferay questions clearly and practically—since I’ve worked through similar scenarios before, I’ll break this down step by step.
You’ve got a few solid options here, but the most straightforward (especially for web-based apps) is using Liferay’s built-in JSON Web Services (JSON WS). Here’s how to make it work:
Step 1: Confirm JSON WS is enabled
By default, Liferay enables JSON WS, but double-check in Control Panel → Configuration → System Settings → Foundation → JSON Web Services. Ensure the "Enabled" toggle is turned on.Step 2: Handle Authentication
Non-portlet apps need to authenticate to access protected services. Two common methods:- Session Cookie (same-domain apps): If your app lives on the same domain as Liferay, once the user logs into Liferay, their browser automatically sends the
JSESSIONIDcookie with requests. This is perfect for your second question’s scenario. - OAuth2 (cross-domain apps): For apps on external domains, set up OAuth2 in Liferay (Control Panel → Security → OAuth2 Administration). Create an app registration to get a client ID/secret, then use authorization codes or client credentials to fetch an access token. Include this token in the
Authorizationheader (Bearer <token>) for every request.
- Session Cookie (same-domain apps): If your app lives on the same domain as Liferay, once the user logs into Liferay, their browser automatically sends the
Step 3: Call the Remote Service
Liferay exposes nearly all its core services via JSON WS. You can browse all available endpoints athttp://your-liferay-host/api/jsonws(replace with your actual Liferay URL). For example, to fetch documents, you might use theDLAppService.getFolderFilesmethod.Example curl request (same domain, authenticated via session):
curl -X GET "http://your-liferay-host/api/jsonws/dlapp/get-folder-files/folder-id/123/start/0/end/20" \ -H "Cookie: JSESSIONID=your-active-session-id"Example JavaScript fetch request (same domain, user already logged in):
fetch('/api/jsonws/dlapp/get-folder-files', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ 'folderId': '123', // Replace with your target folder ID 'start': '0', 'end': '20' }) }) .then(response => response.json()) .then(data => console.log('Fetched files:', data)) .catch(error => console.error('Request failed:', error));
Absolutely feasible—you don’t need to write a single Portlet for this. Here’s the tailored approach:
Leverage the logged-in user’s session
When a user logs into Liferay, their browser stores a valid session cookie. Any JavaScript running on Liferay’s portal pages (like a custom script in the homepage theme or a widget-injected script) will automatically send this cookie with requests to JSON WS endpoints. Liferay validates the session and returns only files the user has permission to view.Find the right JSON WS endpoint
Use the JSON WS browser (/api/jsonws) to locate relevant methods. The most useful ones for file lists are:DLAppService.getFolderFiles: Fetches files in a specific folder (get the folder ID by navigating to the folder in Documents and Media, then copying it from the URL or folder menu).DLAppService.getRepositoryFiles: Fetches files across an entire site’s document library.
Render the file list dynamically
Once you fetch the file data, you can build HTML elements to display the list. Here’s a quick example that injects a list into a div with IDfile-list-container:// Wait for the page to fully load document.addEventListener('DOMContentLoaded', () => { const targetFolderId = '123'; // Replace with your folder ID const container = document.getElementById('file-list-container'); fetch('/api/jsonws/dlapp/get-folder-files', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ 'folderId': targetFolderId, 'start': '0', 'end': '50' // Adjust to fetch more/less files }) }) .then(response => response.json()) .then(files => { if (files.length === 0) { container.innerHTML = '<p>No files found that you have access to.</p>'; return; } // Build a list of file links const fileList = document.createElement('ul'); files.forEach(file => { const listItem = document.createElement('li'); const fileLink = document.createElement('a'); fileLink.href = `/documents/${file.groupId}/${file.folderId}/${file.title}`; fileLink.textContent = `${file.title} (${file.fileSize} bytes)`; listItem.appendChild(fileLink); fileList.appendChild(listItem); }); container.appendChild(fileList); }) .catch(error => { container.innerHTML = `<p>Error loading files: ${error.message}</p>`; console.error('File fetch error:', error); }); });Add the script to your homepage
You can inject this script in a few ways:- Edit your Liferay theme and add the script to the theme’s JS files.
- Use a "Custom HTML" widget (from the Widget Library) on the homepage, then paste the script inside it.
- Use Liferay’s Script Editor (Control Panel → Configuration → Script Editor) to add a global script that runs specifically on the homepage.
A quick sanity check: Test with different user roles to confirm permission enforcement works—Liferay’s JSON WS automatically blocks access to files the user shouldn’t see, so you don’t have to handle that logic yourself.
内容的提问来源于stack exchange,提问作者Roy

