How to print in console in Spring MVC application(Dynamic web project)?

Tags: , , ,



I have a Dynamic Web app in Eclipse which has a normal Controller, Entity and a DAO class.

I am using Hibernate to get the data from the database and then displaying it in JSP page.

But when I try to use System.out.print(); in Controller class to see weather my data is being fetched from the database it is not printing it in the console.

Am I missing something?

Here are the following classes.

Controller.java

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.luv2code.springdemo.dao.CustomerDAO;
import com.luv2code.springdemo.entity.Customer;

@Controller
@RequestMapping("/customer")
public class CustomerController {

    
    
    // need to inject the customer dao
    @Autowired
    private CustomerDAO customerDAO;
    
    @RequestMapping("/list")
    public String listCustomers(Model theModel) {
        
        // get customers from the dao
        List<Customer> theCustomers = customerDAO.getCustomer();
                

       ***//This is the sysout which is not displaying in the consol***
        System.out.println(theCustomers.get(0).getFirstName());
    

        theModel.addAttribute("customers", theCustomers);
        
        return "list-customers";
    }
    
}


DAO class

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.luv2code.springdemo.entity.Customer;

@Repository
public class CustomerDAOImpl implements CustomerDAO {

    // need to inject the session factory
    @Autowired
    private SessionFactory sessionFactory;
            
    @Override
    @Transactional
    public List<Customer> getCustomer() {
        
        // get the current hibernate session
        Session currentSession = sessionFactory.getCurrentSession();
                
        // create a query
        Query<Customer> theQuery = 
                currentSession.createQuery("from Customer", Customer.class);
        
        // execute query and get result list
        List<Customer> customers = theQuery.getResultList();
                
        // return the results       
        return customers;
    }

}


Entity class

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name ="customer")
public class Customer {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private int id;
    
    @Column(name="first_name")
    private String firstName;
    
    @Column(name="last_name")
    private String lastName;
    
    @Column(name="email")
    private String email;

    public Customer() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
    }

    public Customer(String firstName, String lastName, String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }
    
    
    

}

Answer

What you want to do requires a logger. Use the java.util.Logger class to print to the console. A logger instance can be initialized using Logger logger = new Logger(getClass().toString()); Then for output logger.info("Hello, World!");

Edit: To explain more why System.out won’t work. I am not 100% sure but my intuition is that the logging window on your server that you are seeing is not the same output that the System.out PrintStream object points to. According to the documentation on the java.lang.System class found here:

"Typically this stream corresponds to display output or another output destination specified by the host environment or user."

What this says is that the System.out object prints to whatever the destination is it is told to. System.out can be pointed to other destinations by assigning it another PrintStream using the System.setOut(PrintStream). Figuring out how to get an PrintStream object that points to your server logs my require a little digging around.

In any case I should point out that System.out is rarely used in the real world and most real world applications use Loggers for displaying output. Loggers will print meta data about the surrounding context of the output such as the fully qualified name of that class that output is coming from as well as the exact method of that class. This makes debugging and tracing your code much easier than using System.out.

Additionally Loggers have tiers that can categorize your output based on severity. Logging statements that simply trace the execution of your code can be filtered from logging statements that are printing warnings or serious errors. System.out only has an error level and a default level. The java.util.Logger class has a trace level, a debug level, a info level, and a warn level. Each level can be filtered based on configuration and each level provides meta data about the statement to the developer. At a quick glance its obvious whether the statement says something they should be concerned about or whether its just a general update about the execution.

This is starting to get into the weeds a bit but the general take away is that Loggers are much better equipped for a real world application thanSystem.out. They do everything System.out can do, plus more. And btw if your in an application that has a server log that should be a hint that you should be migrating to using loggers anyway. Hope this helps!



Source: stackoverflow