Configuration of an MVC-based web application

As a newcomer to web application development, I am currently working on building a web application using the Model-View-Controller pattern. My setup includes a MySQL database for the Model, JSP pages for the Views, and a DAO for the Controller.

I am looking for guidance on how to retrieve data from the database and dynamically generate a table with that information. Should I resort to using JSP scriptlets or incorporate JavaScript? I have read mixed opinions about the use of scriptlets in JSP and I want to make sure I follow best practices.

Answer №1

Suppose you are looking to create a JSON API with a standalone client-side application, as discussed in the comments. To achieve this, you will need to send an AJAX HTTP request to your server. There are various libraries available for this task, including jQuery.


Retrieving the data

To begin, fetch the data from your web server using jQuery.get:

$.get( "ajax/test.html", function( data ) {
  $( ".result" ).html( data );
  alert( "Load was performed." );
}); 

For more information, refer to the tutorial on jQuery documentation.

Displaying the data in HTML format

There are multiple ways to achieve this using jQuery. I suggest exploring the following answers for guidance:

  • Using jQuery: Create HTML table using jQuery and JSON array
  • Using pure JS: Generate HTML table from 2D JavaScript array

Answer №2

To implement this functionality, one approach is to create a class within your Models that represents a database row and include a method for reading a row. This class can also have a Get method that returns a list of objects, as shown below:

public class MyItem
{
    public string Id { get; set; }
    public string MyProperty { get; set; }

    public List<MyItem> Get()
    {
        List<MyItem> items = new List<MyItem>();

        try
        {
            // Code for retrieving data from the database
        }
        catch (Exception)
        {
            // Logging error
            throw;
        }
        return items;
    }
    
    public void FromRow(DataRow row)
    {
        // Method for populating object properties from a DataRow
    }
}

In your controller, you would call the Get method of the MyItem class to retrieve the desired items based on specified criteria. An example implementation in the controller could look like this:

[Authorize(Roles = "...")]
public IActionResult GetMyItems(string id)
{
    MyItem item = new MyItem() { Id = id };
    var items = item.Get();

    return items;
}

Finally, after fetching the data using the controller, you should be able to access it through the Model property in your view.

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

Text field value dynamically changes on key press update

I am currently working on the following code snippet: {% for item in app.session.get('aBasket') %} <input id="product_quantity_{{ item['product_id'] }}" class="form-control quantity" type="text" value="{{ item['product_quan ...

Converting UTF-16 to UTF-8 in JavaScript: A step-by-step guide

I'm facing a challenge with Base64 encoded data in UTF-16 format. While most libraries only support UTF-8, I need to find a way to decode the data by dropping the null bytes, although I'm not sure how to go about it. Currently, I'm utilizin ...

When trying to save an image using multer's storage, the error message "ENOENT: file or directory not found" is displayed. It is important to note that symbols are not causing

Whenever I try to save an image using multer's storage feature, I encounter the following issue: [Error: ENOENT: no such file or directory, open 'C:\MAMP\htdocs\Chat Backend\public\images\servers\1596819056816AF ...

Performing AJAX requests to dynamically update multiple DIVs

Encountering difficulties with adding additional input fields to a page, each of which contains jquery code for appending more select boxes related to them. The base html setup is as follows: <p id="add_field"> … </p> <div class="show_sub ...

Determine if the webpage is the sole tab open in the current window

How can I determine if the current web page tab is the only one open in the window? Despite searching on Google for about 20 minutes, I couldn't find any relevant information. I would like to achieve this without relying on add-ons or plugins, but if ...

Implementing a confirmation dialog for POST requests in Flask

My first experience with Flask involves adding a confirmation dialog to a form, but only under specific conditions. Unfortunately, I'm unable to achieve this on the client side. While I was successful in implementing it for GET requests, POST requests ...

Is it possible to replace a server-side templating engine with Angular 2's server-side pre-rendering?

As a novice in web development, I have recently been exploring angular 1.x, react.js, and angular 2 (eventually deciding on angular 2). Lately, I've been intrigued by the concept of server-side pre-rendering. In my understanding, this process is ...

Generate a new object from the contents of a div

Having the HTML structure below: <div id="main"> <div id="myDiv1"> <ul> <li>Abc</li> <li>Def</li> </ul> </div> <div id="myDiv2"> <ul> <li>Ghi</l ...

The computed variable in Vuex does not get updated when using the mapState function

I searched through several posts to find out what I am doing incorrectly. It seems like everything is set up correctly. MOTIVE Based on the value of COMPONENT A, I want to change hide/display content using v-show in DEPENDENT COMPONENT. ISSUE In the T ...

Clicking to Load Images - Angular

Implementing a feature to load sets of images on button click instead of loading all at once. Although lazy load plugins are available, I decided to experiment with this approach. Here's the logic: Start with a data array called 'Images' co ...

After utilizing the function, the forward and back arrows are no longer visible

After setting up my slideshow, I encountered an issue where clicking the next or previous buttons caused them to shrink down and turn into small grey boxes. Has anyone experienced this before? This relates to PHP/HTML if ($_SERVER['REQUEST_METHOD&ap ...

Ways to prevent endless loops from occurring?

Here is the code for my component: const Inscriptions = () => { // getting state const { inscriptions, loading } = useSelector( state => state.user ); // flag const instances = Object.keys(inscriptions).length; // dispatch ...

Error Message: Execution Not Recognized and Missing Requirement

After going through numerous threads, I couldn't find a solution to my specific issue. It's quite unclear what I've installed or uninstalled, but I'm hoping that this error message and its details might provide some clarity. Even though ...

Arranging an Array Object in Javascript by Date

Although similar questions have been addressed in other posts, my specific situation appears to be unique due to the data I am receiving from Twitter. Here is the logic I am currently using to sort the JavaScript Array object. However, the issue seems to ...

What is the best way to implement vuelidate when dealing with an array of objects?

In my form questionnaire, I am looping through an array of objects. Each object has five properties, but only one property needs validation. The validation setup in the component looks like this: specificGifts: { $each: { passThrough: { ...

An easy guide to sorting outcomes using JSON

I have JSONResults in my Controller that contains all the data from a table. On the client's HTML detail view page, I am using JavaScript to fetch this data. How do I extract data from JSON where the client name is equal to klID (this is a JSON string ...

Change object values to capital letters

Upon retrieving myObject with JSON.stringify, I am now looking to convert all the values (excluding keys) to uppercase. In TypeScript, what would be the best way to accomplish this? myObj = { "name":"John", "age":30, "cars": [ { "name":"Ford", ...

The second AJAX call is unsuccessful

I have created a dynamic ajax website that retrieves pages from the /pages folder and displays them within an ajax-container div on my index.php. Now, I am looking to implement a second ajax request that will only be triggered on certain pages. For examp ...

The customized sweet alert button is failing to trigger its designated function

I integrated vue-swal to show a pop-up dialog with customized functionality. However, I faced an issue while modifying the swal. In my modified version, there are 3 buttons each with specific actions that should be triggered upon clicking. But for some rea ...

Issue with PrimeNG Calendar not updating date value within modal

While using the PrimeNG Calendar control, I encountered an issue. Even though I am able to select and store dates, when I try to fetch dates from a database and update the Modal, I receive the following error message: <p-calendar [(ngModel)]="bi ...