spring MVC+mybatis+spring security筆記<二>

上篇中用戶信息配置在了spring-security中,登陸界面也使用的是security自帶的頁面,接下來就將mybatis整合進來,當然用戶信息和權限信息肯定是要從數據庫中獲取了,除此之外,登錄界面也使用自定義的。

步驟一:

首先,先寫個自定義的登錄頁面:

<form method="post" class="am-form" action="<%=path%>/j_spring_security_check">
	      <label for="email">用戶名:</label>
	      <input type="text" name="j_username">
	      <br>
	      <label for="password">密碼:</label>
	      <input type="password" name="j_password" id="password">
	      <br>
	      <label for="remember-me">
	        <input id="remember-me" type="checkbox">
	        	記住密碼
	      </label>
	      <br />
	      <div class="am-cf">
	        <input type="submit" name="submit" value="登 錄" class="am-btn am-btn-primary am-btn-sm am-fl">
	        <input type="submit" onclick="forget();" value="忘記密碼 ^_^? " class="am-btn am-btn-default am-btn-sm am-fr">
	      </div>
	    </form>

注意現在還是使用的security自己的登錄驗證,所以輸入框的name值必須爲:j_username,j_password

然後修改配置文件,只需增加一行:

	<http auto-config="true">
		<intercept-url pattern="/main.jsp" access="ROLE_SALE"/>
		<access-denied-handler error-page="/error.jsp"/>
		<span style="color:#ff6600;"><form-login login-page="/index.jsp" default-target-url="/main.jsp"/></span>
	</http>
啓動項目試一下:



OK了。。

步驟二

在數據庫中先簡單的建三張表:user、role、user_role

user:id  username  password

role:id  name  roleKey  enable

user_role:id  userId(FK) roleId(FK) ----中間表

引入mybatis的jar包和MySQL的驅動包,加入mybatis的配置文件spring-security.xml(這個配置文件資料太多了,就不寫出來了);

稍微修改下web.xml

	<context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>
  		classpath:spring-security.xml,classpath:spring-mybatis.xml
  	</param-value>
  </context-param>
項目中加入User.java、Role.java、UserDao、RoleDao、UserService、RoleService

步驟三

要從數據庫中讀取用戶和權限等信息實現登錄驗證,就需要寫一個實現了UserDetailsService接口的類

package org.advancingCat.security;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.advancingCat.entity.Role;
import org.advancingCat.service.RoleService;
import org.advancingCat.service.UserService;
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;


public class MyUserService implements UserDetailsService{

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		org.advancingCat.entity.User dbUser = null;
		try {
			dbUser = userService.queryByName(username);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(dbUser==null){
			throw new UsernameNotFoundException("用戶名不存在");
		}
		Collection<GrantedAuthority> grantedAuth = getGrantedAuth(dbUser);
		//security的User
		UserDetails user = new User(dbUser.getUsername(), dbUser.getPassword(),true,true,true,true, grantedAuth);
		return user;
	}
	
	/**
	 * 獲取用戶的角色:role中的roleKey字段封裝到Set<GrantedAuthority>中
	 * @param user
	 * @return
	 */
	private Set<GrantedAuthority> getGrantedAuth(org.advancingCat.entity.User user){
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		try {
			List<Role> roleList = roleService.queryByUserId(user.getId());
			for(Role r : roleList){
				authSet.add(new SimpleGrantedAuthority(r.getRoleKey()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return authSet;
	}
}

其中queryByUserId是根據用戶ID獲取用戶的角色集合(有時候用戶不止一個角色)  Rolemapper文件:

<select id="queryByUserId" resultMap="BaseResultMap" parameterType="java.lang.Integer">
	select name,roleKey from role r left join user_role ur on r.id=ur.roleId
	where ur.userId=#{userId}
</select>

修改spring-security.xml,將之前的<user-service>去掉
	<authentication-manager>
		<authentication-provider user-service-ref="myUserService">
		</authentication-provider>
	</authentication-manager>
	
	<beans:bean id="myUserService" class="org.advancingCat.security.MyUserService">
	</beans:bean>


至此,結合數據庫實現一個簡單的登錄就完成了。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章