You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

非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.

1. 如何从非Portlet类型的应用中访问Liferay Remote Services?

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 JSESSIONID cookie 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 Authorization header (Bearer <token>) for every request.
  • Step 3: Call the Remote Service
    Liferay exposes nearly all its core services via JSON WS. You can browse all available endpoints at http://your-liferay-host/api/jsonws (replace with your actual Liferay URL). For example, to fetch documents, you might use the DLAppService.getFolderFiles method.

    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));
    
2. 用户登录Liferay Portal后,需在门户首页通过JavaScript实现其有权限访问的文件列表可视化,该应用无需继承Liferay Portlet类,此需求是否可行?

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 ID file-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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:42:02