Here is an example to implement CORS and pass parameters in a servlet:
Use the following code snippet for creating a link in JSP:
<a href="servleturl?name=<%=userName%>&country=<%=userCountry%gt;">click</a>
Then, retrieve the parameter values in your Servlet class:
String userName = request.getParameter("name");
String userCountry = request.getParameter("country");
Alternatively, if you are using JSTL, here's how you can create a URL with parameters:
<c:url value="/servleturl" var="url">
<c:param name="name" value="userName" />
<c:param name="country" value="userCountry" />
</c:url>
And finally, create a link using the generated URL:
<a href="<c:out value='${url}'/>">ServletLink</a>
To enable CORS, you can implement a filter with the following method:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
((HttpServletResponse) response).addHeader("Access-Control-Allow-Origin", "*");
((HttpServletResponse) response).addHeader("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST");
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (httpRequest.getMethod().equals("OPTIONS")) {
httpResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
return;
}
chain.doFilter(request, response);
}