我正在使用href来调用servlet URL并且它工作正常。我想添加参数并从此请求获得响应。可能吗?我尝试使用AJAX调用但发现了CORS问题(当调用外部Api时)。
还有更好的方法吗?
示例:<a href="servleturl">click</a>
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);
}