user2200278
user2200278

Reputation: 95

Servlet response in different .htm file

  1. How to show response or output generated by servlet using separate .html file designed with CSS?

    For example, output generated by servletresp.java in htmlpage.html.

  2. Can we use CSS in Servlet programming?

Upvotes: 1

Views: 651

Answers (2)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31299

You question is very generic so I'm going to assume you are a beginning Java web programmer.

To your first question, I advise you to use JSP pages (or any other template technology). Yes, it is possible to serve .html files from a Servlet using a RequestDispatcher, but JSP pages are meant to generate such output - it is easy to make a small part of a JSP page dynamic, while serving HTML files from a servlet doesn't give you an option for some dynamic behaviour.

Just rename your file.html page to file.jsp and put in in your web source directory of your war project.

To your second question - HTML sent by a servlet or a JSP page is still normal HTML and you can use CSS as you would in any HTML page.

Code example:

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
    RequestDispatcher dispatcher = request.getRequestDispatcher("/file.html");

    // If you want to include the file in your response, use dispatcher.include - 
    // you can include multiple different files or send more output using 
    // response.getWriter() or response.getOutputStream
    dispatcher.include(request, response);

    // If you just want to send this one file as the response, use dispatcher.forward
    dispatcher.forward(request, response);
}

Upvotes: 2

Anthony Grist
Anthony Grist

Reputation: 38345

If your aim is to have the user's browser (appear to) request a static .html page, but have your servlet code executed instead, there's a few ways you could do that.

Most (All? I'm only familiar with running Struts on WebSphere) servlet containers allow you to specify an arbitrary pattern for URLs that are mapped to actions, so you could simply put in a mapping for htmlpage.html to your servlet action that executes the associated code then runs through a JSP (or similar) to render HTML to be sent as the response.

Alternatively you could simply serve up a static HTML page that uses a JavaScript (so executed client-side) templating engine, then load the data for the page from your servlet (likely as JSON) via an AJAX call when the page loads.

The second part doesn't really make any sense. CSS isn't a programming language, it's simply rules for specifying how things look. It's also meaningless without something to interpret and apply those rules to the content (which is what the browser does). You can include CSS inside HTML, or a separate file, generated in your servlet code, but it's not going to do anything.

Upvotes: 0

Related Questions