This spring mvc project is purely based on annotation.
No xml files used here.
Configuration with simple jdbc.
No hibernate.
I implemented this code by using this video
https://www.youtube.com/watch?v=sHETKJUBTyk
I m using:
Java 8
Maven 3.3.9
Tomcat 8.5
Windows 8.1, 64 bit
IDE: Spring Tool Suite
Version: 3.8.2.RELEASE
Platform: Eclipse Neon.1 (4.6.1)
Hope u have all setup for java and maven.
I m starting from creation of project.
In Spring Tool Suite
File -> New -> Maven Project
if u don't find maven in first list
then
file -> new -> other -> (search maven) maven project -> next
Select check box create simple project and then next(leave other option as it is).
Now we have to provide details of projects, e.g. name of project, package name etc.
then finish. It takes some time to create project. U can check progress in Progress tab.
In my IDE it creates Dynamic Web Module 2.5 version.
But I want to create 3.0 version.
To make our project Dynamic Web Module 3.0 version we have to do some extra work.
Steps to modify our project to 3.0
1) Right click on project and select properties
(Select project that we just created)
Then one dialog box will open
We have to search "project facet"
Then we change Dynamic web moduel to 3.0 and java 1.8
So we modify Dynamic web module to 3.0 and java 1.8 and selected my tomcat server and then apply and ok.
Even after this operation we realize that our deployment descriptor version haven't change.
To make change affect our project we have to first close project and then again open project.
Our pom.xml prompting one error that web.xml is missing.
Either u can create web.xml or you can follow
this link, click here.
If link is not working then copy paste url manually please.
https://stackoverflow.com/questions/31835033/web-xml-is-missing-and-failonmissingwebxml-is-set-to-true
Here I m avoiding to create web.xml.
Here my pom.xml code
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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.liferayasif.login.example</groupId>
<artifactId>FirstSecurity</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jdk.version>1.8</jdk.version>
<springframework.version>4.3.0.RELEASE</springframework.version>
<springframework.security.version>4.0.4.RELEASE</springframework.security.version>
<hibernate.version>4.3.6.Final</hibernate.version>
<maven.compiler.version>3.1</maven.compiler.version>
<maven.war.version>2.6</maven.war.version>
<mysql.connector.version>5.1.31</mysql.connector.version>
<testng.version>6.9.4</testng.version>
<mockito.version>1.10.19</mockito.version>
<h2.version>1.4.187</h2.version>
<dbunit.version>2.2</dbunit.version>
<joda-time.version>2.3</joda-time.version>
<dozer.version>5.4.0</dozer.version>
<jackson.version>2.2.3</jackson.version>
</properties>
<dependencies>
<!-- Spring Core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Spring Webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${springframework.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${springframework.security.version}</version>
</dependency>
<!-- Spring JDBC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
</dependencies>
<!-- To avoid compiler and jre version -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.version}</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
<!-- To avoid web.xml error -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven.war.version}</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>SpringMVCLoginExample</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
MySql query to create database and tables that I m using here
create database springmvclogin;
use springmvclogin;
create table users(
id int not null auto_increment,
username varchar(60),
password varchar(60),
primary key(id)
);
create table user_roles(
role_id int not null auto_increment,
username varchar(60),
user_role varchar(60),
primary key(role_id)
);
Data inside my tables are
For users table:
For user_roles table:
Java Class file hierarchy
Now my classes are
1. UserInfo.java
package org.liferayasif.login.example.model;
public class UserInfo {
private String username;
private String password;
public UserInfo(){}
public UserInfo(String username, String password) {
super();
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;
}
}
2. LoginDao.java (interface)
package org.liferayasif.login.example.dao;
import java.util.List;
import org.liferayasif.login.example.model.UserInfo;
public interface LoginDao {
public UserInfo findUserInfoByUserName(String userName);
public List<String> getUserRolesByUserName(String userName);
}
3. LoginDaoImpl.java
package org.liferayasif.login.example.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.liferayasif.login.example.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
@Repository
public class LoginDaoImpl implements LoginDao{
NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Autowired
public void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate) throws DataAccessException{
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}
@Override
public UserInfo findUserInfoByUserName(String username) {
String query = "select * from users where username=:username";
try{
UserInfo userInfo = namedParameterJdbcTemplate.queryForObject(query, getSqlParameterByModel(username, ""), new UserInfoMapper());
return userInfo;
}
catch(EmptyResultDataAccessException e){
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
private SqlParameterSource getSqlParameterByModel(String userName, String password){
MapSqlParameterSource paramSource = new MapSqlParameterSource();
paramSource.addValue("username", userName);
paramSource.addValue("password", password);
return paramSource;
}
private static final class UserInfoMapper implements RowMapper<UserInfo>{
public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException{
String userName = rs.getString("username");
String password = rs.getString("password");
return new UserInfo(userName, password);
}
}
@Override
public List<String> getUserRolesByUserName(String username) {
String query = "select user_role from user_roles WHERE username=:username";
List<String> roles = namedParameterJdbcTemplate.queryForList(query, getSqlParameterByModel(username, ""), String.class);
return roles;
}
}
4. LoginService.java
package org.liferayasif.login.example.service;
import java.util.ArrayList;
import java.util.List;
import org.liferayasif.login.example.dao.LoginDao;
import org.liferayasif.login.example.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 LoginService implements UserDetailsService{
@Autowired
LoginDao loginDao;
public void setLoginDao(LoginDao loginDao) {
this.loginDao = loginDao;
}
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
UserInfo userInfo = loginDao.findUserInfoByUserName(userName);
if(userInfo==null){
throw new UsernameNotFoundException("user name not found");
}
List<String> roles = loginDao.getUserRolesByUserName(userName);
List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>();
if(roles!=null){
for(String role : roles){
GrantedAuthority authority = new SimpleGrantedAuthority(role);
grantedAuthorityList.add(authority);
}
}
UserDetails userDetails = new User(userInfo.getUsername(), userInfo.getPassword(), grantedAuthorityList);
return userDetails;
}
}
5. SecurityConfig.java
package org.liferayasif.login.example.config;
import org.liferayasif.login.example.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
LoginService loginServiceImpl;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(loginServiceImpl);
auth.authenticationProvider(authenticationProvider());
}
@Bean
public DaoAuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(loginServiceImpl);
return authenticationProvider;
}
@Override
protected void configure(HttpSecurity http) throws Exception{
http.csrf().disable();
http.authorizeRequests().antMatchers("/login").permitAll();
http.authorizeRequests().antMatchers("/", "/home").access( "hasRole('ROLE_ADMIN')" );
http.authorizeRequests().and().formLogin()
.loginProcessingUrl("/j_spring_security_check")
.loginPage("/login")
.defaultSuccessUrl("/home")
.failureUrl("/login?error=true")
.usernameParameter("username")
.passwordParameter("password")
.and().logout().logoutUrl("/j_spring_security_logout").logoutSuccessUrl("/login");
}
}
6. WebConfig.java
package org.liferayasif.login.example.config;
import javax.naming.NamingException;
import javax.sql.DataSource;
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.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@Configuration
@ComponentScan({"org.liferayasif.login.example"})
@Import({SecurityConfig.class})
public class WebConfig extends WebMvcConfigurerAdapter{
@Autowired
DataSource dataSource;
@Bean
public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate(){
return new NamedParameterJdbcTemplate(dataSource);
}
@Bean
public DataSource getDataSource() throws NamingException{
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/springmvclogin");
dataSource.setPassword("root");
dataSource.setUsername("root");
return dataSource;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/resources/**").addResourceLocations("/resources");
}
@Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setViewClass(JstlView.class);
internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
}
7. SecurityInitializer.java
package org.liferayasif.login.example.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer{
}
8. WebInit.java
package org.liferayasif.login.example.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer{
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{WebConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
9. LoginController.java
package org.liferayasif.login.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class LoginController {
@RequestMapping(value="/login", method = RequestMethod.GET)
public ModelAndView login(@RequestParam(value="error", required = false) String error){
ModelAndView mav = new ModelAndView();
if(error!=null)
mav.addObject("error", "username or password is incorrect");
mav.setViewName("login/login");
return mav;
}
@RequestMapping(value={"/", "/home"}, method = RequestMethod.GET)
public ModelAndView home(){
ModelAndView mav = new ModelAndView();
mav.setViewName("home/home");
return mav;
}
}
my jsp folder hierarchy
Add your tomcat server and run.
url: http://localhost:8080/SpringMVCLoginExample/login
credentials:
User Name: admin Password: 1234
Please give me your feedback.
|