Today I will explain how to create project in Eclipse Oxygen IDE using Spring Boot & Maven.
Your Final Project will look somewhat like this:
Login Page:
Account Summary Page:
So to start with let us understand what all softwares we need to install:
1. Eclipse Oxygen IDE
2. JDK 1.8 (install & set the JAVA_HOME & PATH variables)
3. Install MySQL server
To download maven archetypes:
1. In Eclipse go to Help > Install New Software
2. Click on Manage > Select Maven
3. Untick - Do not automatic update..
4. Tick - Download Artifact, Download Repository Index, Update Maven Project on Startup, Automatic update maven project.
5. Apply & Close. Restart Eclipse . It will start downloading all maven dependancies. Once Finished Downloading Reset the Maven Option as per below Image:
Creating new Maven Project:
1. In Eclipse go to File > New > Other..
2. Click on Maven > Maven Project.Click Next.
3. Untick Use default workspace location. Click on Browse.. Go to Location of your choice, where you want all Maven Projects to be. Click Next.
4. For Catalogs: Select All Catalogs. In Filter textbox write "org.apache.maven.archetypes". Press Enter. You will get list of archetypes. Select the one whose Artifact Id is "maven-archetype-webapp" Version 1.0. Click Next.
5. Enter Group Id, Artifact Id. Select Version as 0.0.1-SNAPSHOT. Click Finish.
Required for Debugging:
m2e - Maven Integration for Eclipse (includes Incubating components) add-in for edit source path , when we are unable to see source code while debugging maven project.
POM .xml
Copy following contents in the POM.xml file of your project. Save this POM.xml file.
4.0.0 com.smartjava.tutorial MyLoginApp war 0.0.1-SNAPSHOT MyLoginApp Maven Webapp http://maven.apache.org 1.8 UTF-8 UTF-8 codelds https://code.lds.org/nexus/content/groups/main-repo org.springframework spring-core 4.2.5.RELEASE org.springframework spring-web 4.2.5.RELEASE org.springframework spring-webmvc 4.2.5.RELEASE org.springframework spring-jdbc 4.2.5.RELEASE org.springframework.security spring-security-web 4.0.4.RELEASE org.springframework.security spring-security-config 4.0.4.RELEASE javax.servlet jstl 1.2 javax.servlet javax.servlet-api 3.1.0 provided javax.servlet.jsp jsp-api 2.2 provided mysql mysql-connector-java 5.1.34 com.oracle ojdbc6 11.2.0.3 net.sourceforge.jtds jtds 1.3.1 junit junit 3.8.1 test javax.validation validation-api 1.1.0.Final org.hibernate hibernate-validator 5.0.1.Final MyLoginApp maven-resources-plugin 2.6 copy-resources process-resources copy-resources target/m2e-wtp/web-resources/resources src/main/webapp/resources true copy-views process-resources copy-resources target/m2e-wtp/web-resources/WEB-INF/pages src/main/webapp/WEB-INF/pages true org.apache.tomcat.maven tomcat7-maven-plugin 2.2 /MyLoginApp 9995 org.apache.maven.plugins maven-war-plugin 2.0.2 true src/main/webapp **/*.css src/main/resources true
Content in Web.xml
Archetype Created Web Application
ds.database-driver=com.mysql.jdbc.Driver
ds.url=jdbc:mysql://localhost:3306/userinfo
ds.username=admin
ds.password=rootsql
MyDBAuthenticationService
package com.smartjava.tutorial.authentication;
import java.util.ArrayList;
import java.util.List;
import com.smartjava.tutorial.dao.UserInfoDAO;
import com.smartjava.tutorial.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class MyDBAuthenticationService implements UserDetailsService {
@Autowired
private UserInfoDAO userInfoDAO;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserInfo userInfo = userInfoDAO.findUserInfo(username);
System.out.println("UserInfo= " + userInfo);
if (userInfo == null) {
throw new UsernameNotFoundException("User " + username + " was not found in the database");
}
// [USER,ADMIN,..]
List roles= userInfoDAO.getUserRoles(username);
List grantList= new ArrayList();
if(roles!= null) {
for(String role: roles) {
// ROLE_USER, ROLE_ADMIN,..
GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + role);
grantList.add(authority);
}
}
UserDetails userDetails = (UserDetails) new User(userInfo.getUserName(),userInfo.getPassword(),grantList);
return userDetails;
}
}
ApplicationContextConfig
package com.smartjava.tutorial.config;
import javax.sql.DataSource;
import com.smartjava.tutorial.dao.UserInfoDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@ComponentScan("com.smartjava.tutorial.*")
@EnableTransactionManagement
// Load to Environment.
@PropertySource("classpath:datasource-cfg.properties")
public class ApplicationContextConfig {
// The Environment class serves as the property holder
// and stores all the properties loaded by the @PropertySource
@Autowired
private Environment env;
@Autowired
private UserInfoDAO userInfoDAO;
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource rb = new ResourceBundleMessageSource();
// Load property in message/validator.properties
rb.setBasenames(new String[] { "messages/validator" });
return rb;
}
@Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Bean(name = "dataSource")
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
// See: datasouce-cfg.properties
dataSource.setDriverClassName(env.getProperty("ds.database-driver"));
dataSource.setUrl(env.getProperty("ds.url"));
dataSource.setUsername(env.getProperty("ds.username"));
dataSource.setPassword(env.getProperty("ds.password"));
System.out.println("## getDataSource: " + dataSource);
return dataSource;
}
// Transaction Manager
@Autowired
@Bean(name = "transactionManager")
public DataSourceTransactionManager getTransactionManager(DataSource dataSource) {
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
return transactionManager;
}
}
SpringWebAppInitializer
package com.smartjava.tutorial.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class SpringWebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(ApplicationContextConfig.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("SpringDispatcher",
new DispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
WebMvcConfig
package com.smartjava.tutorial.config;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
private static final Charset UTF8 = Charset.forName("UTF-8");
// Config UTF-8 Encoding.
@Override
public void configureMessageConverters(List> converters) {
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", UTF8)));
converters.add(stringConverter);
// Add other converters ...
}
// Static Resource Config
// equivalents for tags
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(31556926);
registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(31556926);
registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
}
// Equivalent for tag
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
WebSecurityConfig
package com.smartjava.tutorial.config;
import com.smartjava.tutorial.authentication.MyDBAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
// @EnableWebSecurity = @EnableWebMVCSecurity + Extra features
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
MyDBAuthenticationService myDBAauthenticationService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// Users in memory.
auth.inMemoryAuthentication().withUser("admin").password("rootsql").roles("USER, ADMIN");
// For User in database.
auth.userDetailsService(myDBAauthenticationService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
// The pages does not require login
http.authorizeRequests().antMatchers("/", "/welcome", "/login", "/logout").permitAll();
// /userInfo page requires login as USER or ADMIN.
// If no login, it will redirect to /login page.
http.authorizeRequests().antMatchers("/userInfo").access("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')");
// For ADMIN only.
http.authorizeRequests().antMatchers("/admin").access("hasRole('ROLE_ADMIN')");
// When the user has logged in as XX.
// But access a page that requires role YY,
// AccessDeniedException will throw.
http.authorizeRequests().and().exceptionHandling().accessDeniedPage("/403");
// Config for Login Form
http.authorizeRequests().and().formLogin()//
// Submit URL of login page.
.loginProcessingUrl("/j_spring_security_check") // Submit URL
.loginPage("/login")//
.defaultSuccessUrl("/userInfo")//
.failureUrl("/login?error=true")//
.usernameParameter("username")//
.passwordParameter("password")
// Config for Logout Page
.and().logout().logoutUrl("/logout").logoutSuccessUrl("/logoutSuccessful");
}
}
MainController
package com.smartjava.tutorial.controller;
import java.io.IOException;
import java.security.Principal;
import java.util.List;
import javax.validation.Valid;
import com.smartjava.tutorial.dao.TxnInfoDAO;
import com.smartjava.tutorial.dao.impl.TxnInfoDAOImpl;
import com.smartjava.tutorial.model.TxnInfo;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class MainController {
@Autowired
TxnInfoDAO txnInfoDaoObj;
@RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET)
public String welcomePage(Model model) {
model.addAttribute("title", "Welcome");
model.addAttribute("message", "This is Maven Project welcome page!");
return "welcomePage";
}
@RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adminPage(Model model) {
return "adminPage";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(@Valid Model model ) {
return "loginPage";
}
@RequestMapping(value = "/logoutSuccessful", method = RequestMethod.GET)
public String logoutSuccessfulPage(Model model) {
model.addAttribute("title", "Logout");
return "logoutSuccessfulPage";
}
@RequestMapping(value = "/userInfo", method = RequestMethod.GET)
public String userInfo(Model model, Principal principal) {
String str1="";
// After user login successfully.
String userName = principal.getName();
System.out.println("User Name: "+ userName);
List txnInfoObj = txnInfoDaoObj.getAllTxnInfo(userName);
try {
for (TxnInfo txnInfo : txnInfoObj) {
str1 = str1+txnInfo.toString();
}
}catch (Exception e) {
// TODO: handle exception
}
model.addAttribute("message", txnInfoObj);
model.addAttribute("title", userName);
return "userInfoPage";
}
@RequestMapping(value = "/403", method = RequestMethod.GET)
public String accessDenied(Model model, Principal principal) {
if (principal != null) {
model.addAttribute("message", "Hi " + principal.getName()
+ "
You do not have permission to access this page!!!!");
} else {
model.addAttribute("msg",
"You do not have permission to access this page!!!");
}
return "403Page";
}
}
TxnInfoDAO
package com.smartjava.tutorial.dao;
import java.util.List;
import com.smartjava.tutorial.model.TxnInfo;
public interface TxnInfoDAO {
public List getAllTxnInfo(String userName);
}
UserInfoDAO
package com.smartjava.tutorial.dao;
import java.util.List;
import com.smartjava.tutorial.model.UserInfo;
public interface UserInfoDAO {
public UserInfo findUserInfo(String userName);
// [USER,AMIN,..]
public List getUserRoles(String userName);
}
TxnInfoDAOImpl
package com.smartjava.tutorial.dao.impl;
import java.util.*;
import javax.sql.DataSource;
import com.smartjava.tutorial.dao.TxnInfoDAO;
import com.smartjava.tutorial.mapper.TxnInfoMapper;
import com.smartjava.tutorial.model.TxnInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class TxnInfoDAOImpl extends JdbcDaoSupport implements TxnInfoDAO {
public List txnList = null;
@Autowired
public TxnInfoDAOImpl(DataSource dataSource) {
this.setDataSource(dataSource);
}
public List getAllTxnInfo(String userName) {
String str1 = "";
System.out.println("1. Inside getAllTxnInfo()");
String sql = "Select t.id, t.username, t.date, t.amount, t.crdbtype " + " from txn t where t.username = ? ";
Object[] params = new Object[] { userName };
TxnInfoMapper mapper = new TxnInfoMapper();
List txnList = new ArrayList();
List
UserInfoDAOImpl
package com.smartjava.tutorial.dao.impl;
import java.util.List;
import javax.sql.DataSource;
import com.smartjava.tutorial.dao.UserInfoDAO;
import com.smartjava.tutorial.mapper.UserInfoMapper;
import com.smartjava.tutorial.model.TxnInfo;
import com.smartjava.tutorial.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class UserInfoDAOImpl extends JdbcDaoSupport implements UserInfoDAO {
@Autowired
public UserInfoDAOImpl(DataSource dataSource) {
this.setDataSource(dataSource);
}
public UserInfo findUserInfo(String userName) {
String sql = "Select u.Username,u.Password "//
+ " from Users u where u.Username = ? ";
Object[] params = new Object[] { userName };
UserInfoMapper mapper = new UserInfoMapper();
try {
UserInfo userInfo = this.getJdbcTemplate().queryForObject(sql, params, mapper);
return userInfo;
} catch (EmptyResultDataAccessException e) {
return null;
}
}
public List getUserRoles(String userName) {
String sql = "Select r.User_Role "//
+ " from User_Roles r where r.Username = ? ";
Object[] params = new Object[] { userName };
List roles = this.getJdbcTemplate().queryForList(sql,params, String.class);
return roles;
}
}
DisplayTxnInfo
package com.smartjava.tutorial.displayinfo;
import com.smartjava.tutorial.dao.TxnInfoDAO;
import com.smartjava.tutorial.model.TxnInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
public class DisplayTxnInfo implements UserDetailsService{
@Autowired
private TxnInfoDAO txnInfoDAO;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
TxnInfo txnInfo = (TxnInfo) txnInfoDAO.getAllTxnInfo(username);
return null;
}
}
TxnInfoMapper
package com.smartjava.tutorial.mapper; import java.sql.ResultSet; import java.sql.SQLException; import com.smartjava.tutorial.model.TxnInfo; import org.springframework.jdbc.core.RowMapper; public class TxnInfoMapper implements RowMapper{ public TxnInfo mapRow(ResultSet rs, int rowNum) throws SQLException { String id = rs.getString("id"); String userName = rs.getString("username"); String dateTimes = rs.getString("date"); String amount = rs.getString("amount"); String txnType = rs.getString("crdbtype"); return new TxnInfo(userName, dateTimes, amount, txnType); } }
UserInfoMapper
package com.smartjava.tutorial.mapper; import java.sql.ResultSet; import java.sql.SQLException; import com.smartjava.tutorial.model.UserInfo; import org.springframework.jdbc.core.RowMapper; public class UserInfoMapper implements RowMapper{ public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException { String userName = rs.getString("Username"); String password = rs.getString("Password"); return new UserInfo(userName, password); } }
TxnInfo
package com.smartjava.tutorial.model;
public class TxnInfo {
private String username;
private String date;
private String amount;
private String crdbype;
public TxnInfo() {
// TODO Auto-generated constructor stub
}
public void setUsername(String username) {
this.username = username;
}
public void setDate(String date) {
this.date = date;
}
public void setAmount(String amount) {
this.amount = amount;
}
public void setCrdbype(String crdbype) {
this.crdbype = crdbype;
}
public TxnInfo(String username, String date, String amount, String crdbype) {
super();
this.username = username;
this.date = date;
this.amount = amount;
this.crdbype = crdbype;
}
public String getUsername() {
return username;
}
public String getDate() {
return date;
}
public String getAmount() {
return amount;
}
public String getCrdbype() {
return crdbype;
}
@Override
public String toString() {
return "TxnInfo [username=" + username + ", date=" + date + ", amount=" + amount + ", crdbype=" + crdbype + "]";
}
}
UserInfo
package com.smartjava.tutorial.model;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class UserInfo {
@NotEmpty (message = "Please enter your username.")
@Size(min=4, max=10)
private String userName;
@NotEmpty (message = "Please enter your password.")
@Size(min=4, max=10)
private String password;
public UserInfo() {
}
public UserInfo(String userName, String password) {
this.userName = userName;
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
_main.jsp




