Back to: Java (Clone)
Spring MVC HelloWorld Example With Maven, Bootstrap and Logging(Log4j):
In this tutorial we are going to see a project based on Spring MVC, Maven, Bootstrap and Log4j. This example is actually for showing use of Logging(using Log4j) in Spring MVC based application. If want to know why logging is important then visit importance of logging. For knowing what is Log4j visit what is Log4j . For understanding on why and where to use Log4j visit use of Log4j.
Used Technologies:
1. Spring Framework
2. Jsp, HTML, CSS, Bootstrap
3. Built Tool: Maven
4. Server: tomcat
5. Logging: Log4j
Final Project Structure:
For adding Log4j to our application, requires a configuration file. It could be a .xml file a .properties. Both of them serve the same. Here we will see a log4j.properties file.
# Root logger option and logging level log4j.rootLogger=DEBUG, stdout, ERROR, INFO, file # Redirect log messages to console log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n # Redirect log messages to a log file log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=D:/practice/app.log log4j.appender.file.MaxFileSize=5MB log4j.appender.file.MaxBackupIndex=10 log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Here logging level means what kind of log it is? Is it a warning, error or stack trace. Logging levels are:
- DEBUG
- ERROR
- FATAL
- INFO
- OFF
- TRACE
- WARN
In this example we will see different levels of logging.
“Redirect log messages to console” for showing the logs in output console.
“Redirect log messages to a log file” for saving the logs in a file. I’m saving it in my “D” directory and the log file name is “app.log”
log4j.appender.file.File=D:/practice/app.log
Let’s see the complete example:
Jsp pages:
Index.jsp
<% response.sendRedirect("dashboard.do");%>
customer.jsp
<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sales Management</title>
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">NoteArena Property</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="<c:url value="/dashboard.do" />">Dashboard</a></li>
<li><a href="<c:url value="/addCustomer.do" />">Add Customer</a></li>
</ul>
</div>
</nav>
<div style="width: 600px; margin: auto;">
<h3 align="center">
<b>Dashboard: Sales Management System</b>
</h3>
<form:form class="form-horizontal" role="form" action="dashboard.do" modelAttribute="customerObject">
<div class="form-group">
<h2>Welcome to Sales management system</h2>
</div>
</form:form>
</div>
</body>
</html>
addCustomer.jsp:
For taking input(customer information) from html form and adding customer. This file uses Spring MVC pattern, HTML tags and Bootstrap.
<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sales Management System</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">NoteArena Property</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="<c:url value="/dashboard.do" />">Dashboard</a></li>
<li><a href="<c:url value="/addCustomer.do" />">Add Customer</a></li>
</ul>
</div>
</nav>
<div style="width: 600px; margin: auto;">
<h3 align="center"><b>Add a new customer</b></h3>
<form:form class="form-horizontal" role="form" action="showCustomer.do" modelAttribute="customerObject">
<div class="form-group">
<label class="control-label col-sm-2" for="name">Customer Name:</label>
<div class="col-sm-10">
<form:input path="name" value="" type="text" class="form-control" placeholder="Customer Name"/>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label col-sm-4" for="age">Age :</label>
<div class="col-sm-8">
<form:input path="age" type="text" class="form-control" placeholder="Age"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="education">Education:</label>
<div class="col-sm-8">
<form:input path="education" type="text" class="form-control" placeholder="Education"/>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label col-sm-4" for="address">Address:</label>
<div class="col-sm-8">
<form:textarea path="address" type="text" rows="5" cols="30" class="form-control" value="" placeholder="Address"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="designation">Designation:</label>
<div class="col-sm-8">
<form:input type="text" class="form-control" path="designation" value="" placeholder="Designation" />
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form:form>
</div>
</body>
</html>
showCustomer.jsp
Shows the added customers.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Customer Name: ${customerObject.name}</h1>
<h1>Customer Age: ${customerObject.age}</h1>
<h1>Customer Education: ${customerObject.education}</h1>
<h1>Address: ${customerObject.address}</h1>
<h1>Designation : ${customerObject.designation}</h1>
</body>
</html>
Java Classes:
Model Class:
Model class bind and encapsulate our data. It actually holds our data so that we can use it further.
CustomerObjectForm.java
package com.notearena.model; public class CustomerObjectForm { private String name; private int age; private String education; private String address; private String designation; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEducation() { return education; } public void setEducation(String education) { this.education = education; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } @Override public String toString() { return "CustomerObjectForm [name=" + name + ", age=" + age + ", education=" + education + ", address=" + address + ", designation=" + designation + "]"; } }
Controller class
Controller takes our action, it navigate our action to the page we want to go.
CustomerController.java
package com.notearena.controller; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import com.notearena.model.CustomerObjectForm; @Controller public class CustomerController { private static final Logger logger = Logger.getLogger(CustomerController.class); @RequestMapping(value = "dashboard") public String getDashboard(@ModelAttribute("customerObject") CustomerObjectForm customerObject, Model model) { //System.out.println("Check dashboard"); logger.debug("Checking dashboard"); return "customer"; } @RequestMapping(value = "addCustomer") public String addCustomer(@ModelAttribute("customerObject") CustomerObjectForm customerObject, Model model) { //System.out.println("Check add customer"); logger.debug("Checking addCustomer"); model.addAttribute("customerObject", customerObject); return "addCustomer"; } @RequestMapping(value = "showCustomer") public String showCustomer(@ModelAttribute("customerObject") CustomerObjectForm customerObject, Model model) { //System.out.println("Check show customer"); logger.debug("Checking show customer"); //System.out.println("Name:"+customerObject.getName()); logger.info("Name:"+customerObject.getName()); model.addAttribute("customerObject", customerObject); return "showCustomer"; } }
View Resolver
It’s a xml file which resolve our views. It defines which is our package for controller. It also defines from which folder spring will find the view pages(jsp pages) and what are their extensions.
customer-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <context:component-scan base-package="com.notearena.controller" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/views/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
Deployment descriptor:
Web.xml
Web.xml defines servlet mapping .
And also we can modify our jsp files extension with any extension like <url-pattern>*.do</url-pattern> , example:
yourpagename.jsp yourpagename.do
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>Sales Management</display-name> <servlet> <servlet-name>customer</servlet-name> <!-- servlet name can be anything --> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- Known as front controller in spring --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>customer</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
pom.xml
This file because we are using maven. Why we are using maven , we will see in maven tutorial series. pom.xml contains reference of all the dependencies (jar file) we are using in this project.
For Adding Log4j, we added dependency :
<!-- Log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency>
Complete Pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.notearena</groupId> <artifactId>SalesManagement</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SalesManagement Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <org.springframework.version>4.2.6.RELEASE</org.springframework.version> <jstl.version>1.2</jstl.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <!-- Log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> </dependencies> <build> <finalName>SalesManagement</finalName> </build> </project>
Run the application:
For running these application you have to deploy this app to an application server (tomcat, jboss, glassfish etc). If you are running this application from eclipse then you have to a application server like this. Now you need to just right click on the project folder and choose Run as> Run on Server
Now if you select Run on Server then it will execute index.jsp file. index.jsp file contains :
<% response.sendRedirect("dashboard.do");%>
Therefore , it will call controller class( CustomerController.java ) and find for “@RequestMapping(value = “dashboard”)” in this class. Again this returns customer.jsp page.
@RequestMapping(value = "dashboard") public String getDashboard(@ModelAttribute("customerObject") CustomerObjectForm customerObject, Model model) { //System.out.println("Check dashboard"); logger.debug("Check dashboard from logger"); return "customer"; // returns customer.jsp page }
So, customer.do (customer.jsp)file will be shown on browser.
You will find output like below:
Dashboad(customer.jsp):
Add Customer:
Show Result(showCustomer.jsp):
In console we will see the logs like:
And check your directory you have provided to save your log file. In my case it was:
D:/practice/app.log
Download the example: Spring MVC with Log4J