Menus

Jun 7, 2016

How to make spring login application using spring-security in netbeans.

(Sharing is the most valuable work in this world, so friend don’t forget to share.)
I hope this spring-security login application will help you to grasp the concept of spring-security. 
You required additional four packages which are shown in below figure:



















1. Create a database named bind and execute following SQL statements:
CREATE TABLE `authorities` (
  `USERNAME` varchar(10) NOT NULL,
  `AUTHORITY` varchar(10) NOT NULL
);
INSERT INTO `authorities` (`USERNAME`, `AUTHORITY`) VALUES
('Admin', 'ROLE_ADMIN'),
('Admin', 'ROLE_USER'),
('user1', 'ROLE_USER'),
('user2', 'ROLE_USER');
CREATE TABLE `member` (
  `ID` bigint(20) NOT NULL,
  `USERNAME` varchar(10) NOT NULL,
  `PASSWORD` varchar(32) NOT NULL
);
INSERT INTO `member` (`ID`, `USERNAME`, `PASSWORD`) VALUES
(1, 'Admin', '1e6947ac7fb3a9529a9726eb692c8cc5'),
(2, 'user1', '1111');
CREATE TABLE `member_role` (
  `MEMBER_ID` bigint(20) NOT NULL,
  `ROLE` varchar(10) NOT NULL
);
INSERT INTO `member_role` (`MEMBER_ID`, `ROLE`) VALUES
(1, 'ROLE_ADMIN'),
(1, 'ROLE_USER'),
(2, 'ROLE_USER');
CREATE TABLE `users` (
  `USERNAME` varchar(10) NOT NULL,
  `PASSWORD` varchar(32) NOT NULL,
  `ENABLED` smallint(6) DEFAULT NULL
);
INSERT INTO `users` (`USERNAME`, `PASSWORD`, `ENABLED`) VALUES
('Admin', 'Secret', 1),
('user1', '1111', 1),
('user2', '2222', 0);
ALTER TABLE `authorities`
  ADD KEY `USERNAME` (`USERNAME`);
ALTER TABLE `member`
  ADD PRIMARY KEY (`ID`);
ALTER TABLE `member_role`
  ADD KEY `MEMBER_ID` (`MEMBER_ID`);
ALTER TABLE `users`
  ADD PRIMARY KEY (`USERNAME`);
ALTER TABLE `authorities`
ADD CONSTRAINT `authorities_ibfk_1` FOREIGN KEY (`USERNAME`) REFERENCES `users` (`USERNAME`);
ALTER TABLE `member_role`
ADD CONSTRAINT `member_role_ibfk_1` FOREIGN KEY (`MEMBER_ID`) REFERENCES `member` (`ID`);

The structure of our project in netbeans is as follows:
 

2. Login.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
        <title>Login</title>
    </head>
    <body>
        <c:if test="${not empty param.error}">
<font color="red">
Login error. <br />
Reason : ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
</font>
</c:if>
        <form method="POST" action="<c:url value="/j_spring_security_check" />">
            <table>
                <tr>
                    <td align="right">Username</td>
                    <td><input type="text" name="j_username" /></td>
                </tr>
                <tr>
                    <td align="right">Password</td>
                    <td><input type="password" name="j_password" /></td>
                </tr>
                <tr>
                    <td align="right">Remember me</td>
                    <td><input type="checkbox" name="_spring_security_remember_me" /></td>
                </tr>
                <tr>
                    <td colspan="2" align="right">
                        <input type="submit" value="Login" />
                        <input type="reset" value="Reset" />
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>

3. messageList.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Message List</title>
</head>
<body>
<c:forEach items="${messages}" var="message">
<table>
<tr>
<td>Author</td>
<td>${message.author}</td>
</tr>
<tr>
<td>Title</td>
<td>${message.title}</td>
</tr>
<tr>
<td>Body</td>
<td>${message.body}</td>
</tr>
<tr>
<td colspan="2">
<a href="messageDelete?messageId=${message.id}">Delete</a>
</td>
</tr>
</table>
<hr />
</c:forEach>
<a href="messagePost.htm">Post</a>
 <%//<!--<a href="<c:url value="/spring_security_login" />">Login</a>-->
//<!--<a href="<c:url value="/login" />">Login</a>--> %>
<!--<a href="<c:url value="/spring_security_login" />">Login</a>-->
<a href="<c:url value="/login" />">Login</a>
<a href="<c:url value="/j_spring_security_logout" />">Logout</a>
</body>
</html>

4. messagePost.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>Message Post</title>
</head>
<body>
<form:form method="POST" modelAttribute="message">
<table>
<tr>
<td>Title</td>
<td><form:input path="title" /></td>
</tr>
<tr>
<td>Body</td>
<td><form:textarea path="body" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Post" /></td>
</tr>
</table>
</form:form>
</body>
</html>

5. board-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             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.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
    <!--    <http auto-config="true">
        <intercept-url pattern="/messageList*"
               access="ROLE_USER,ROLE_ANONYMOUS" />
        <intercept-url pattern="/messagePost*" access="ROLE_USER" />
        <intercept-url pattern="/messageDelete*" access="ROLE_ADMIN" />
    </http>-->
    <http>
        <form-login login-page="/login" default-target-url="/messageList" authentication-failure-url="/login?error=true"/>
        <logout logout-success-url="/login" />
        <intercept-url pattern="/messageList*" access="ROLE_USER,ROLE_GUEST" />
        <intercept-url pattern="/messagePost*" access="ROLE_USER" />
        <intercept-url pattern="/messageDelete*" access="ROLE_ADMIN" />
        <anonymous username="guest" granted-authority="ROLE_GUEST" />
        <!--<http-basic />-->
        <remember-me />
    </http>
   
    <!--    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="admin" password="secret"
                      authorities="ROLE_ADMIN,ROLE_USER" />
                <user name="user1" password="1111" authorities="ROLE_USER" />
                <user name="user2" password="2222" disabled="true" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>-->
   
    <!--    <authentication-manager>
        <authentication-provider>
            <user-service properties="/WEB-INF/users.properties" />
        </authentication-provider>
    </authentication-manager>-->
   
<!--    <authentication-manager>
<authentication-provider>
<password-encoder hash="md5" />
<user-service>
<user name="admin" password="5ebe2294ecd0e0f08eab7690d2a6ee69"
authorities="ROLE_ADMIN, ROLE_USER" />
<user name="user1" password="b59c67bf196a4758191e42f76670ceba"
authorities="ROLE_USER" />
<user name="user2" password="934b535800b1cba8f96a5d72f72f1611"
disabled="true" authorities="ROLE_USER" />
</user-service>
</authentication-provider>-->
<!--</authentication-manager>-->   
    <authentication-manager>
        <authentication-provider>
            <password-encoder hash="md5" />
            <jdbc-user-service data-source-ref="dataSource"
            users-by-username-query="SELECT username, password, 'true' as enabled FROM member
WHERE username = ?"
authorities-by-username-query="SELECT member.username, member_role.role as authorities FROM member, member_role
WHERE member.username = ? AND member.id = member_role.member_id" />
        </authentication-provider>
    </authentication-manager>
</beans:beans>

6. board-service.xml
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">
    <bean id="messageBoardService"
          class="com.apress.springrecipes.board.service.MessageBoardServiceImpl" />
    <!--    <bean id="springSecurityFilterChain" class="org.acegisecurity.util.FilterChainProxy">
        <property name="filterInvocationDefinitionSource">
            <value>
                CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
                PATTERN_TYPE_APACHE_ANT
                exceptionTranslationFilter, ntlmFilter, filterSecurityInterceptor
            </value>
        </property>
    </bean>-->
   
    <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/board" />
        <property name="username" value="root" />
        <property name="password" value="paawan" />
    </bean>
</beans>

7. dispatcher-servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd      
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
    <context:component-scan base-package="com.apress.springrecipes.board.web" />
    <mvc:annotation-driven />
    <context:annotation-config />
    <!--
    Most controllers will use the ControllerClassNameHandlerMapping above, but
    for the index controller we are using ParameterizableViewController, so we must
    define an explicit mapping for it.
    -->
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.htm">indexController</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

    <!--
    The index controller.
    -->
    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />
<!--    <import resource="board-security.xml"/>-->
</beans>

8. User.properties
admin=secret,ROLE_ADMIN,ROLE_USER
user1=1111,ROLE_USER
user2=2222,disabled,ROLE_USER

9. web.xml
<web-app 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"
         version="3.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/board-service.xml,
            /WEB-INF/board-security.xml
        </param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
   
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>
            org.springframework.web.filter.DelegatingFilterProxy
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

10. Inside package com.apress.springrecipes.board.domain make class Message.java
package com.apress.springrecipes.board.domain;
public class Message {
    private Long id;
    private String author;
    private String title;
    private String body;

    public Long getId() {
        return id;
    }

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

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

}

11. Inside package com.apress.springrecipes.board.service make interface MessageBoardService.java
package com.apress.springrecipes.board.service;
import com.apress.springrecipes.board.domain.Message;
import java.util.List;

public interface MessageBoardService {
public List<Message> listMessages();
public void postMessage(Message message);
public void deleteMessage(Message message);
public Message findMessageById(Long messageId);
}


12. Inside package com.apress.springrecipes.board.service make class MessageBoardServiceImpl.java
package com.apress.springrecipes.board.service;
import com.apress.springrecipes.board.domain.Message;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class MessageBoardServiceImpl implements MessageBoardService {
private Map<Long, Message> messages = new LinkedHashMap<Long, Message>();
@Override
public List<Message> listMessages() {
return new ArrayList<Message>(messages.values());
}
@Override
public synchronized void postMessage(Message message) {
message.setId(System.currentTimeMillis());
messages.put(message.getId(), message);
}
@Override
public synchronized void deleteMessage(Message message) {
messages.remove(message.getId());
}
@Override
public Message findMessageById(Long messageId) {
return messages.get(messageId);
}
}

13. Inside package com.apress.springrecipes.board.web make a class
package com.apress.springrecipes.board.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author Paawan
 */
@Controller

public class LoginController {

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model) {
        return "login";
    }
}

14. Inside package com.apress.springrecipes.board.web make a class
package com.apress.springrecipes.board.web;
import com.apress.springrecipes.board.domain.Message;
import com.apress.springrecipes.board.service.MessageBoardService;
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 org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/messageDelete*")
public class MessageDeleteController {
private MessageBoardService messageBoardService;
@Autowired
public void MessageDeleteController(MessageBoardService messageBoardService) {
this.messageBoardService = messageBoardService;
}
@RequestMapping(method= RequestMethod.GET)
public String messageDelte(@RequestParam(required = true,value = "messageId") Long messageId, Model model) {
Message message = messageBoardService.findMessageById(messageId);
messageBoardService.deleteMessage(message);
model.addAttribute("messages", messageBoardService.listMessages());
return "redirect:messageList";
}
}

15. Inside package com.apress.springrecipes.board.web make a class MessagePostController.java
package com.apress.springrecipes.board.web;

import com.apress.springrecipes.board.domain.Message;
import com.apress.springrecipes.board.service.MessageBoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/messagePost*")
public class MessagePostController {
private MessageBoardService messageBoardService;
@Autowired
public void MessagePostController(MessageBoardService messageBoardService) {
this.messageBoardService = messageBoardService;
}
@RequestMapping(method=RequestMethod.GET)
public String setupForm(Model model) {
Message message = new Message();
model.addAttribute("message",message);
return "messagePost";
}
@RequestMapping(method=RequestMethod.POST)
public String onSubmit(@ModelAttribute("message") Message message, BindingResult result) {
if (result.hasErrors()) {
return "messagePost";
} else {
messageBoardService.postMessage(message);
return "redirect:messageList";
}
}
}

So, have a nice day
Happy coding
Be healthy, be busy J


No comments:

Post a Comment

Contact Form

Name

Email *

Message *