使用哪种机制来触发使用href从jsp到servlet的调用

问题描述 投票:0回答:1

我正在使用href来调用servlet URL并且它工作正常。我想添加参数并从此请求获得响应。可能吗?我尝试使用AJAX调用但发现了CORS问题(当调用外部Api时)。

还有更好的方法吗?

示例:<a href="servleturl">click</a>

javascript java ajax jsp servlets
1个回答
0
投票
    Try like this:

    <a href="servleturl?name=<%=userName%>&country=<%=userCountry%>">click</a>

    In Servlet:

    String userName= request.getParameter("name");
    String userCountry= request.getParameter("country");

OR If you are using JSTL:

<c:url value="/servleturl" var="url">
  <c:param name="name" value="userName" />
  <c:param name="country" value="userCountry" />
</c:url>

<a href="<c:out value='${url}'/>">ServletLink</a>


For enabling CORS create a filter having overrided method like this:
// content of Request Filter
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {

            HttpServletRequest request = (HttpServletRequest) request;    

            ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Origin", "*");
            ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST");

            HttpServletResponse resp = (HttpServletResponse) response;

            if (request.getMethod().equals("OPTIONS")) {
                resp.setStatus(HttpServletResponse.SC_ACCEPTED);
                return;
            }    

            chain.doFilter(request, response);
        }
© www.soinside.com 2019 - 2024. All rights reserved.