Spring MVC – Creating the Homepage -Part 3 | “Web App Series”

In this tutorial , we will be continuing with the login form for our web app. We will be adding users to the database and assigning roles to them to prevent unauthorized access to sections of our web app.  We will also see how to secure the login system by replacing simple text based passwords to encrypted formats. Before you begin with this tutorial , I highly recommend you to go through Creating the Home Page Part 1Introduction to the Web App Series & Creating the Homepage – Part 2.

First lets change the successful login page so that we know that we have successfully logged in. (Instead of getting the same login page again duh!!).

Lets start by creating some folders inside /WEB-INF/views . I like to keep things organized (even you should).

Lets create two folders user & admin. This will help us keep views separate for both the user & the admin.

Now lets create a JSP file welcome.jsp inside user folder.

This will be our entry point view for the users when they login. Now lets make some changes to the code -

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>One's Price - Find out where to buy your daily needs at
	the cheapest price !</title>
<meta name="description"
	content="One's Price, where we tell you the nearest store that has the cheapest price for the stuff you are looking for">

<link rel="stylesheet"
	href="<c:url value="resources/css/normalize.css"/>" />
<link rel="stylesheet" href="<c:url value="resources/css/main.css"/>" />

<link rel="stylesheet"
	href="<c:url value="resources/css/bootstrap-responsive.min.css"/>" />
<link rel="stylesheet"
	href="<c:url value="resources/css/bootstrap.min.css"/>" />
<link rel="stylesheet" href="<c:url value="resources/css/style.css"/>" />

<link rel="stylesheet" href="<c:url value="resources/css/userStyle.css"/>" />

<script src="<c:url value="resources/js/jquery-1.8.0.min.js" />"></script>
<script src="<c:url value="resources/js/modernizr-2.6.1.min.js"/>"></script>
</head>
<body>
	<!--[if lt IE 7]>
            <p class="chromeframe">You are using an outdated browser. <a href="http://browsehappy.com/">Upgrade your browser today</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to better experience this site.</p>
        <![endif]-->
	<header>
		<div id="headerPanel" class="headerPanel">
			<div class="panelL">
				<img src="<c:url value="/resources/images/logoSmall.png"/>">
				<h3>Find out where to buy your daily needs at the cheapest
					price !</h3>
			</div>
		</div>
	</header>

	<div class="subnav">
		<ul class="nav nav-pills">
			<li><a href="<c:url value="/" />">Home</a></li>
			<li><a href="#">About</a></li>
			<li><a href="#">Profile</a></li>
			<li><a href="#">Download App</a></li>
			<li><a href="#global">Contact Us</a></li>
			<li><a href="#global">Send Feedback</a></li>


		</ul>
	</div>

	<div class="wrapper">
		<div class="container home-container">

			<form name='f' id="login"
				action="<c:url value='j_spring_security_check' />" method="POST">
				<img id="logo"
					src="<c:url value="/resources/images/logoSmall.png" />">
				<div class="row-fluid">
					<div class="span8">
						<h1>Welcome ${userName}!</h1>

					
					</div>

					

				</div>
			</form>
		</div>

	</div>
	<script src="<c:url value="resources/js/bootstrap.js"/>"></script>
</body>
</html>

I have copied the code from home.jsp and modified it a bit

  • Removed the login form
  • Changed the menu links
  • Added a new stylesheet – userStyle.css (you can create this css file as described before for stlye.css).
  • Added a variable ${userName} to show the userName of the logged in user.

Now lets create a controller class - userController.java

userController.java -

package com.onesprice.webapp;

import java.security.Principal;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class UserController {

	private String currentUserName="";
	
	@RequestMapping(value="/welcome",method = RequestMethod.GET)
	public String welcome(Model model,Principal principal){
		
		currentUserName = principal.getName();
		model.addAttribute("userName",currentUserName);
		
		return "user/welcome";
	}
	
}

 

The only thing new in this controller is the Principal object. This provides the logged in user details(part of Java Security). We get the usename by the method getName()-

principal.getName();

Now we need to make changes to our security configuration to let it know where to go after successful login -

<form-login login-page="/" 
  		       default-target-url="/welcome"
			   authentication-failure-url="/loginError" />

We just need to change the default-target-url to “/welcome” (same as in our controller mapping).

Now when we login into our app , we see the greeting message along with the username.

Now that we have our login page in place, its time to create a user database.

Lets start by creating a table in our database onesprice (see Introduction). You can use phpmyAdmin or MySQL console to create your table.

CREATE TABLE `users` (
 USER_ID int(10) unsigned NOT NULL,
 USERNAME varchar(40) NOT NULL,
 PASSWORD text NOT NULL,
 EMAIL text NOT NULL, 
 ADDRESS text NOT NULL,
 USER_LAT float(5) NOT NULL,
 USER_LONG float(5) NOT NULL,
 ENABLED tinyint(1) NOT NULL,
 PRIMARY KEY (USER_ID),
 UNIQUE KEY USERNAME (USERNAME)
)

And lets create a table for user roles (ROLE_ADMIN, ROLE_USER)

CREATE TABLE user_roles (
 USER_ROLE_ID int(10) unsigned NOT NULL,
 USER_ID int(10) unsigned NOT NULL,
 AUTHORITY varchar(40) NOT NULL,
 PRIMARY KEY (USER_ROLE_ID),
 FOREIGN KEY (USER_ID) REFERENCES users (USER_ID)
);

Note the foreign key constrain on USER_ID that i have added in the table user roles.

For now lets manually insert two users one with ROLE_ADMIN & one with ROLE_USER. We will design a sign up form for the users later on.

INSERT INTO users (USER_ID, USERNAME, PASSWORD, EMAIL, ADDRESS,USER_LAT,USER_LONG,ENABLED) VALUES
(1, 'admin', 'onesAdmin', 'admin@onesprice.com', '9th Street Boulevard', -23.38,-41.85,1),
(2, 'ones', 'price', 'ones@onesprice.com', '19th Street KingCross', -13.38,41.85,1)

Now lets add user roles for these users

INSERT INTO user_roles (USER_ROLE_ID`, USER_ID, AUTHORITY) VALUES
(1, 1, 'ROLE_ADMIN'),
(2, 2, 'ROLE_USER')

Now that we have setup the database and the tables , its time to define a bean for our datasource in the root-context.xml. What does this mean?

Nothing too difficult , this only means that we need to define a bean for the JDBC connector so that our web app can talk to the database that we just setup in MySql.

First lets add the JDBC dependency in pom.xml to use JDBC Connector

<!-- Spring JDBC -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.9</version>
	</dependency>

We define a bean by just adding these lines to root-context.xml in /WEB-INF/spring/

<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/onesprice" />
		<property name="username" value="ones" />
		<property name="password" value="price" />
</bean>

Now that we have a bean with id dataSource,  we can use this as input wherever we want database access. That’s what a bean does, gives you everything ready  and easy to access!

Now we are ready to configure spring-security.xml again (this time doing something cool). We will replace the <authentication-provider>

<authentication-manager>
	  <authentication-provider>
	
		<jdbc-user-service data-source-ref="dataSource"
 
		   users-by-username-query="
		      select username,password, enabled 
		      from users where username=?" 
 
		   authorities-by-username-query="
		      select users.username, user_roles.authority from users, user_roles 
 			 where user_roles.user_id = users.user_id and users.username =? " 
 
		/>
	  </authentication-provider>
	</authentication-manager>

Thats all ? Yes , that is almost it ! Now lets try to login as user

What the Foo ?  We dont have access to this page ! Lets fix this (We will also be changing this access denied page to something better than this in the upcoming tutorials! ) , if you remember the lines

<intercept-url pattern="/welcome*" access="ROLE_ADMIN" /> 

Lets change it to

<intercept-url pattern="/welcome*" access="ROLE_USER" />

(We dont want to give admin access to the user welcome page :D )

Now lets try it again -

Voila !

So , now we can login on basis of user details in our database. But the password is still text based (unsecured) so lets add sha algorithm to hash it.

To do this we just need to add

  <authentication-provider>
	 .....
     <password-encoder hash="sha" />
         .....
  </authentication-provider>

This will look for sha encoded password from the database field Password and match it for authentication. But we haven’t hashed the password yet, we will do this when we create the registration form for the user and store the hashed password instead of plain text.

That’s all folks ! In the next few tutorials we will be creating the user registration page, modify the user welcome page and finally start building the core for our app.

Posted in HTML5, Spring MVC, Tutorials and tagged , , , , , , , . Bookmark the permalink. RSS feed for this post. Leave a trackback.

13 Responses to Spring MVC – Creating the Homepage -Part 3 | “Web App Series”

  1. Neil says:

    Thanks very much for putting these tutorials online which I have been following and learning a lot about Spring MVC.
    I cannot however get this tutorial to work. It doesn’t seem to even try and connect to MySQL, I can change the port number, MySQL user/password and nothing happens.
    I is loading in the dataSource bean though as I can see that in the console.
    I am on a Mac and I have switched the default MAMP MySQL port to be 3306 but still nothing. I get ‘INFO : com.onesprice.webapp.LoginController – Login error’ in the console every time no matter what user and password I put in. Any ideas? Thanks.

  2. Neil says:

    I have got it working by using the root/root user/password for MySQL, the newly created ones/price doesn’t seem to work.

  3. Thank you for your thoughtful present of having written this article. The message seems to be given to me specifically. Our son also had a lot to learn from this – though he was the individual that found your site first. Most of us can’t imagine a more superb present than a gift to encourage that you do more.
    Welcome to my website http://www.about-dogs.zoomshare.com.

  4. Angla Tyer says:

    Woah this weblog is magnificent i really like reading your articles. Stay up the good work! You realize, a lot of persons are hunting around for this information, you could help them greatly.

  5. You really make it seem so easy together with your presentation however I find this topic to be actually one thing which I think I’d by no means understand. It sort of feels too complicated and extremely wide for me. I am taking a look ahead on your next post, I will attempt to get the hang of it!

  6. I have been exploring for a bit for any high-quality articles or weblog posts in this sort of house . Exploring in Yahoo I eventually stumbled upon this website. Studying this information So i’m glad to show that I’ve an incredibly good uncanny feeling I discovered just what I needed. I most certainly will make certain to don?t overlook this web site and provides it a glance regularly.

  7. I think that is among the so much important info for me. And i’m happy studying your article. However want to remark on some basic things, The site style is perfect, the articles is truly great : D. Excellent job, cheers

  8. Howdy! I’m at work browsing your blog from my new iphone! Just wanted to say I love reading your blog and look forward to all your posts! Keep up the outstanding work!

  9. Daniel says:

    Hey there,
    Thanks for the great Spring MVC tutorials! This is the first series of tutorials I’ve found that actually make you build something more than the standard Spring MVC “Hello World” app. Are you going to continue this series soon?

  10. Patrice says:

    Hey Shrey
    Thanks for the tutorial! Did you eveer try to show 2 differents login page wether its an admin or a normal user ?

    regards

    • shreks7 says:

      I would not show two different login page but use same one but redirect them depending on the ROLE , to relevant pages. Because you dont know who their authentication role before they login. So essentially either of them can view the login page .

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Enter your email address:

    Delivered by FeedBurner

  • Categories

Swedish Greys - a WordPress theme from Nordic Themepark.

Buffer