Unable to load CSS and JS files on JSP servlet mapping

When there is no servlet mapped to a / in the servlet mapping:

<servlet-mapping>
    <servlet-name>ControllerServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

All my css and javascript frameworks load fine. However, upon adding this code snippet to the web.xml file, none of the css and javascript files are loading. How can I ensure that the servlet recognizes them as css/js files instead of methods?

Content of web.xml

<context-param>
        <param-name>jdbcURL</param-name>
        <param-value>jdbc:mysql://localhost:3306/bookstore</param-value>
    </context-param>

    <context-param>
        <param-name>jdbcUsername</param-name>
        <param-value>root</param-value>
    </context-param>

    <context-param>
        <param-name>jdbcPassword</param-name>
        <param-value>12345</param-value>
    </context-param>

    <servlet>
        <servlet-name>ControllerServlet</servlet-name>
        <servlet-class>net.codejava.javaee.bookstore.ControllerServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ControllerServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <error-page>
        <exception-type>java.lang.Exception</exception-type>
        <location>/Error.jsp</location>
    </error-page>
</web-app>

ControllerServlet Class

public class ControllerServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private BookDAO bookDAO;

    public void init() {
        String jdbcURL = getServletContext().getInitParameter("jdbcURL");
        String jdbcUsername = getServletContext().getInitParameter("jdbcUsername");
        String jdbcPassword = getServletContext().getInitParameter("jdbcPassword");

        bookDAO = new BookDAO(jdbcURL, jdbcUsername, jdbcPassword);

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getServletPath();

        try {
            switch (action) {
            case "/new":
                //showNewForm(request, response);
                break;
            case "/insert":
                //insertBook(request, response);
                break;
            case "/delete":
                //deleteBook(request, response);
                break;
            case "/edit":
                //showEditForm(request, response);
                break;
            case "/update":
                //updateBook(request, response);
                break;
            default:
                listBook(request, response);
                break;
            }
        } catch (SQLException ex) {
            throw new ServletException(ex);
        }
    }

    private void listBook(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException, ServletException {
        List<Book> listBook = bookDAO.listAllBooks();
        request.setAttribute("listBook", listBook);
        RequestDispatcher dispatcher = request.getRequestDispatcher("BookList.jsp");
        dispatcher.forward(request, response);
    }
}

JSP Page

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>

        <!-- JS -->     
        <script src='static/js/bootstrap.min.js'></script>
        <script src='static/js/vue.min.js'></script>

        <!-- CSS -->
        <link rel="stylesheet" type="text/css" href="static/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="static/css/common.css">
     </head>
<body>
    <center>
        <h1>Books Management</h1>
        <h2>
            <a href="new">Add New Book</a>
            &nbsp;&nbsp;&nbsp;
            <a href="list">List All Books</a>

        </h2>
    </center>
    <div align="center">
        <table border="1" cellpadding="5">
            <caption><h2>List of Books</h2></caption>
            <tr>
                <th>ID</th>
                <th>Title</th>
                <th>Author</th>
                <th>Price</th>
                <th>Actions</th>
            </tr>
            <c:forEach var="book" items="${listBook}">
                <tr>
                    <td><c:out value="${book.id}" /></td>
                    <td><c:out value="${book.title}" /></td>
                    <td><c:out value="${book.author}" /></td>
                    <td><c:out value="${book.price}" /></td>
                    <td>
                        <a href="edit?id=<c:out value='${book.id}' />">Edit</a>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <a href="delete?id=<c:out value='${book.id}' />">Delete</a>                     
                    </td>
                </tr>
            </c:forEach>
        </table>
    </div>  
</body>
</html>

Answer №1

To include your CSS files, follow the steps below

<LINK REL="StyleSheet" HREF="<%=request.getContextPath()%>/CSS/style.css" TYPE="text/css">

Make sure your folder structure matches the following

https://i.sstatic.net/RqG3Y.png

All your css/js files should be placed inside the WebContent directory

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhance your dynamic content with jQuery/AJAX through customized CSS styling

Below is the jquery (3.1.1)/ajax request that I am using: $.ajax({ type: "POST", url: "pref.php", dataType: "text", data: { groupe_id: groupe_id, action: "getProducts" }, cache: false, error: function(html){ ...

tips for navigating a webpage by directly linking to a specific section using coordinates

My goal is to redirect the page to a specific coordinate when a link is clicked. Here's what I've come up with so far: $("#link").click(function(){ $("body").position("top", "1000":"left","0") }) <script src="https://ajax.googleapis.com ...

Using jQuery, generate a dynamic form to create a multidimensional array

I've set up a form where additional dropdowns can be dynamically added if the user clicks on a specific link. Here's an example of how it looks: <div class="dynamic-sale"> <select name="sizes[]" id="sizes" class="entry-dropdown"&g ...

Having difficulty choosing parent or descendent nodes with Selenium WebDriver in Java?

Currently, I am utilizing xpath in combination with Java and Selenium WebDriver to pinpoint a node within an XML tree on a webpage. Specifically, I'm trying to identify a hyperlink that possesses the class "red-button" and is located as a descendant ( ...

Using Node.js, iterate over every key-value pair within a Redis hash data structure

I am currently navigating my way through the world of redis and node, attempting to iterate over some test hash keys that I have generated. My goal is to display the results on the screen. The expected output should look like this: { "aaData": [['Tim ...

Creating a comprehensive testNG e-mailable report from various html files

I am facing a scenario where I am required to aggregate data from multiple TestNG emailable-html reports and merge them into a single report that resembles the TestNG-emailable report format. I am unsure of how to approach this task. My plan is to create ...

Save information on the application shutting down, not when it goes into the background

In the development of my app, I am seeking a solution that allows the user to run it in the background while still being able to save important data when the app is fully closed. After some research, I have considered implementing SharedPreferences for t ...

Using AngularJS - Invoking a controller method within a directive

I am experimenting with combining jQuery Sparkline charts with Angularjs. To display multiple charts, I have opted to create a function in the controller and invoke it for each chart (directive). JavaScript controller .controller('sparklineCtrl&apo ...

Populate modal form with database information without using Bootstrap

As I work on populating a form with data from an sqlite database, I've come across a stumbling block. My code is available for reference on JSFiddle: https://jsfiddle.net/daikini/e71mvg7n/ One important note: Bootstrap isn't being utilized in t ...

Is Java designed to use Hashing technique internally for handling all objects?

I am a beginner in the world of hashing and I have come across HashMap, HashTable, etc. which use hashing. It seems that we need to specify a key when storing a value with these data structures. It got me thinking - since every object in Java has a hashCo ...

Tips on effortlessly updating the URL of your website

Despite seeing the question asked multiple times, I still find myself struggling to understand how to modify a URL or create a new HTML page that seamlessly integrates into a website without redirecting users. I am curious about achieving the functionalit ...

Using Content-Disposition in ng-file-upload with AngularJS

Context: I am currently working with ng-file-upload to submit two files separately using ngf-selects along with a Javascript object literal. The problem I'm facing is that when the request is sent, all the parts have their content-disposition set to ...

Issues encountered when using .delay() in conjunction with slideUp()

Issue: The box is not delaying before sliding back up on mouse out. Description: Currently, when hovering over a div with the class ".boxset" called "#box", another div "#slidebox" appears. Upon moving the mouse away from these two divs, #slidebox slides ...

Tips for activating the next tab using the <a> or <button> element in Materialize:

<div class="col s12"> <ul class="tabs"> <li class="tab col s4"><a href="#test1" class="active">tab1</a></li> <li class="tab col s4"><a href="#test2">tab2</a></li> <li class="tab c ...

Calculating the duration of promotional banner content with Selenium: A step-by-step guide

What is the best method for determining the time interval of a promotional banner's content when using Selenium Web Driver? ...

Executing JUnit tests in Intellij IDEA with Play Framework 2

I am currently utilizing Play Framework 2.0.4 with Java and IntelliJ IDEA. When trying to run tests from IDEA, I encountered the following error: Class not found: "models.SoftwareTest" The test code is as follows: package models; public class Soft ...

Leverage the power of both ui-sref and $state.go for seamless state transitions in Angular's ui

Currently, I am in the process of constructing a sign-up form that will collect user input and then transition to a logged-in state with a template tailored specifically for this new user. To achieve this, my understanding is that I need to utilize ng-sub ...

Guide to creating a responsive element table using React.js and Tailwind CSS

Looking to create a responsive table that works well on both desktop and mobile screens using Tailwind CSS. The challenge is that this table component is nested within the <Outlet /> in React.js router dom. desktop view mobile view // Layout.jsx retu ...

What is the best way to show static files from the backend in a React application?

Currently, my setup involves a React application connected to an Express-Node.js backend through a proxy. Within the backend, there are some static files in a specific directory. When I make requests and embed the response link in the "src" attribute of an ...

Troubleshooting the error "System library was not found" in Eclipse Neon on Mac OS X when using Java 9

Can Java 9 be used as an Installed JRE in Eclipse on OS X (El Capitan 10.11.6)? I have installed both the Java 9 (EA build 165) JRE and JDK from the JDK Early Access Release page but I am encountering the following error in Eclipse Neon.3 (4.6.3) when I tr ...