Thursday, April 15, 2021

CORS header 'Access-Control-Allow-Origin' missing and Java Servlet

 As it is answered here, HttpServlet.doOptions() method has to be overridden the following way:

import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
@WebServlet(
    name = "MyServlet",
    urlPatterns = {"/myservlet"}
)
public class MyServlet extends HttpServlet {
	
    @Override
    protected void doOptions
        
(
            
HttpServletRequest req,
            HttpServletResponse resp
        )         throws IOException {         resp.setHeader("Access-Control-Allow-Origin", "*");      resp.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");      resp.setHeader("Access-Control-Allow-Headers", "*");     }     @Override     protected void doPost
        (
            HttpServletRequest req,
            HttpServletResponse resp
        )         throws IOException {         resp.setHeader("Access-Control-Allow-Origin", "*");         resp.setContentType("text/plain");         resp.setCharacterEncoding("UTF-8");         resp.getOutputStream().println("OK");     }     @Override     protected void doGet
        (
            HttpServletRequest req,
            HttpServletResponse resp
        )         throws IOException {         doPost(req, resp);     } }

No comments:

Post a Comment