0

Hey I trying to educate myself, I need to send a html page as the response along with the js and css.

@EnableAutoConfiguration
@ComponentScan
@RestController
public class Main {

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

    @RequestMapping(value = "/", produces = MediaType.TEXT_HTML_VALUE)
    public String webpage()  throws IOException {
        String html = FileCopyUtils.copyToString(new FileReader("index.html"));
        return html;
    }
}

This is a spring MVC code which returns a index.html page as a view to the user. I want to achieve the same only by using plain servlet. Is there any way to do this when the user hit localhost:8080/. Also I don't want to user to know about the extension or even the file name like localhost:8080/index (or) localhost:8080/index.html. The user should only see the localhost:8080/ in the url.

I have found a approach. I can write the whole html content in a string and send it in text/html format. but as soon as I make another request from the same page it hits "/" mapping so it got stuck in a recursive call.

This is the code that I have made in servlet

@WebServlet("/")
public class Controller extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        PrintWriter out= resp.getWriter();
        resp.setContentType("text/html");
        String str = "";
        str = """**some html content***""";
        out.print(str);
        out.close();
}
            

I have a api call in the front end that looks like this

let response = await fetch(`${url}video/search?searchKeyword=${searchKeyword}`)

this will hit this controller

@WebServlet("/video/search")
public class APIs extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("api hit");
        resp.getWriter().print("Response Received");
    }
}

but as soon I made that api call it also calls the servlet with "/" mapping and stuck in recursive pattern.

Karthick
  • 1
  • 2

0 Answers0