0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

メモ10

Posted at

有一种更简洁的方法可以处理你的需求,那就是使用纯HTML和JavaScript来实现这个功能。这种方法避开了JSF的复杂性,并且可以更灵活地与后端API交互。下面是一个示例,展示如何使用HTML按钮和JavaScript来实现你描述的功能:

1. HTML页面代码

<!DOCTYPE html>
<html>
<head>
    <title>Open New Window Example</title>
</head>
<body>
    <button id="submitButton">Submit</button>
    
    <script type="text/javascript">
        document.getElementById('submitButton').addEventListener('click', function() {
            fetch('api/call')  // 假设你的API URL是/api/call
                .then(response => response.json())
                .then(data => {
                    if (data.url) {
                        window.open(data.url, '_blank');
                    }
                })
                .catch(error => console.error('Error:', error));
        });
    </script>
</body>
</html>

2. Java后端代码

你需要创建一个独立的API端点来返回URL。这里使用了一个简单的RESTful API示例。

示例1: 使用JAX-RS(如果你的项目中已经有JAX-RS)

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/api")
public class ApiResource {

    @GET
    @Path("/call")
    @Produces(MediaType.APPLICATION_JSON)
    public Response callApi() {
        // 模拟调用API并获取URL
        String url = "https://example.com"; // 假设这是从API返回的URL
        return Response.ok("{\"url\": \"" + url + "\"}").build();
    }
}

示例2: 使用普通Servlet

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/api/call")
public class ApiServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 模拟调用API并获取URL
        String url = "https://example.com"; // 假设这是从API返回的URL
        response.setContentType("application/json");
        response.getWriter().write("{\"url\": \"" + url + "\"}");
    }
}

流程解释

  1. 用户点击按钮时,JavaScript事件监听器被触发。
  2. JavaScript使用fetch API异步调用后端API。
  3. 后端API返回包含URL的JSON响应。
  4. JavaScript从响应中提取URL,并在新窗口中打开该URL。
  5. 这种方法完全避免了JSF的复杂性和潜在的问题,同时确保原页面不会变成空白页。

这种方法简单明了,使用纯HTML和JavaScript实现了你描述的功能,适合需要更灵活和简洁解决方案的情况。如果你有其他问题或需要进一步的帮助,请告诉我。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?