PYG电商项目开发 -- day04 项目加入spring-security、运营商商家管理

一、项目中配置spring-security


1、pinyoug-manager-web中引入spring-securityjar包坐标


		<!-- 引入spring-security相关配置 -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
		</dependency>


2、web.xml中加入过滤器链配置


	<!-- 加入spring-security的过滤器链的配置 -->
	<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>


3、加入spring-security.xml配置文件,并在web.xml中配置读取


<?xml version="1.0" encoding="UTF-8"?>
<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 pattern="/login.html" security="none"></http>
	<http pattern="/login_error.html" security="none"></http>
	<http pattern="/css/**" security="none"></http>
	<http pattern="/img/**" security="none"></http>
	<http pattern="/js/**" security="none"></http>
	<http pattern="/plugins/**" security="none"></http>
	<http pattern="/assets/**" security="none"></http>
	
	<!-- 页面拦截规则 -->
	<http use-expressions="false">
		<!-- 登录用户是ROLE_ADMIN才能访问以下数据 -->
		<intercept-url pattern="/**" access="ROLE_ADMIN" />
		<!-- 		
			login-page:登录页
			default-target-url:登录成功后跳转的页面
			authentication-failure-url:如果认证(登录)失败后跳转到的页面
			always-use-default-target:登录后一直会跳转到login.html
		-->
		<form-login 
		     login-page="/login.html" 
		     default-target-url="/admin/index.html"
			 authentication-failure-url="/login_error.html" 
			 always-use-default-target="true" />
		<csrf disabled="true" />
		<headers>
			<frame-options policy="SAMEORIGIN" />
		</headers>
		<logout logout-success-url="/login.html"/>
	</http>
	
	<!-- 认证管理器 -->
	<authentication-manager>
		<authentication-provider>
			<user-service>
				<user name="admin" password="123456" authorities="ROLE_ADMIN" />
				<user name="sunwukong" password="dasheng" authorities="ROLE_ADMIN" />
			</user-service>
		</authentication-provider>
	</authentication-manager>
</beans:beans>



4、改造登录页面




二、实现登录之后主页显示用户信息以及退出登录功能


1、编写登录Controller类


package com.pinyougou.manager.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/login")
public class LoginController {

	@RequestMapping("showUserName")
	public Map showUserName() {
		//认证成功,在springsecurit的域中保存了用户信息
		String username = SecurityContextHolder.getContext().getAuthentication().getName();
		Map<String, String> map = new HashMap<>();
		map.put("username", username);
		return map;
	}
}


2、index.html页面处理以及分层js编写


(1)、indexController.js


app.controller("indexController", function($scope, indexService){
	
	//定义显示用户名的方法
	$scope.showUserName = function(){
		indexService.showUserName().success(function(data){
			$scope.username = data.username;
		});
	}
});


(2)、indexService.js


app.service("indexService", function($http){
	
	//定义显示用户名的方法
	this.showUserName = function(){
		return $http.get("../login/showUserName.do");
	}
})


(3)、index.html引入angularjs相关文件


    <!-- 引入angularjs相关文件 -->
    <script type="text/javascript" src="../plugins/angularjs/angular.min.js"></script>
    <!-- 引入自定义angularjs分层文件 -->
    <script type="text/javascript" src="../js/base.js"></script>
    <script type="text/javascript" src="../js/controller/indexController.js"></script>
    <script type="text/javascript" src="../js/service/indexService.js"></script>


(4)、页面信息回显处理




3、用户退出登录功能实现


(1)、index.html中注销按钮改造




(2)、spring-security.xml中注销配置




三、商家入驻功能


1、导入所有商家静态资源到pinyougou-shop-web中






2、实现商家注册功能


(1)、sellerService.js


//服务层
app.service('sellerService',function($http){

	this.saveSeller = function(entity){
		return $http.post("../seller/register.do", entity);
	}
});


(2)、sellerController.js


//控制层 
app.controller('sellerController', function($scope, $controller, sellerService) {

	$scope.saveSeller = function(){
		var entity = $scope.entity;
		sellerService.saveSeller(entity).success(function(data){
			if(data.success){
				alert(data.message);
				location.href = "/admin/home.html";
			}else{
				alert(data.message);
			}
		});
	}
});


(3)、改造register.html页面




(4)、SellerController.java


package com.pinyougou.shop.controller;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.pinyougou.pojo.TbSeller;
import com.pinyougou.sellergoods.service.SellerService;
import com.resultentity.ResultMessage;

@RestController
@RequestMapping("/seller")
public class SellerController {

	@Reference
	private SellerService service;
	
	/**
	 * 商家注册的方法
	 * @param seller
	 * @return
	 */
	@RequestMapping("/register")
	public ResultMessage saveSeller(@RequestBody TbSeller seller) {
		ResultMessage rest = null;
		try {
			service.saveSeller(seller);
			rest = new ResultMessage(true, "数据提交成功,请等待审核!!!");
		} catch (Exception e) {
			e.printStackTrace();
			rest = new ResultMessage(false, "注册失败");
		}
		return rest;
	}
}


(5)、SellerServiceImpl.java


package com.pinyougou.sellergoods.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Service;
import com.pinyougou.mapper.TbSellerMapper;
import com.pinyougou.pojo.TbSeller;
import com.pinyougou.sellergoods.service.SellerService;

@Service
@Transactional
public class SellerServiceImpl implements SellerService {

	@Autowired
	private TbSellerMapper mapper;
	
	@Override
	public void saveSeller(TbSeller seller) {
		//设置注册时间和审核状态
		seller.setCreateTime(new Date());
		seller.setStatus("0");
		mapper.insert(seller);
	}

}


四、manager-web项目中商家审核相关操作


1、实现商家分页列表展示


(1)、商家审核html页面改造




(2)、sellerService.js


/*服务层代码*/
app.service("sellerService", function($http){
	
	//按条件分页查询
	this.search = function(pageNum, pageSize, searchEntity){
		return $http.post("../seller/search.do?pageNum=" + pageNum + "&pageSize=" + pageSize, searchEntity);
	}
	
	//分页查询
	this.findByPage = function(pageNum, pageSize){
		return $http.get("../seller/findByPage?pageNum=" + pageNum + "&pageSize=" + pageSize);
	}
	
})


(3)、sellerController.js


/*controller代码*/
app.controller("sellerController", function($scope, $controller, sellerService){
	
	//继承
	$controller("baseController", {$scope:$scope});
	
	//定义reloadList方法
	$scope.reloadList = function(){
		var pageNum = $scope.paginationConf.currentPage;
		var pageSize = $scope.paginationConf.itemsPerPage;
		$scope.search(pageNum, pageSize, $scope.searchEntity);
	}
	
	//定义待条件列表查询的方法
	$scope.search = function(pageNum, pageSize, searchEntity){
		sellerService.search(pageNum, pageSize, searchEntity).success(function(data){
			$scope.list = data.rows;
			$scope.paginationConf.totalItems = data.total;
		});
	}
	
	//定义分页查询的方法
	$scope.findByPage = function(pageNum, pageSize){
		sellerService.findByPage(pageNum, pageSize).success(function(data){
			$scope.list = data.rows;
			$scope.paginationConf.totalItems = data.total;
		});
	}
	
});


(4)、SellerController.java


package com.pinyougou.manager.controller;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.pinyougou.pojo.TbSeller;
import com.pinyougou.sellergoods.service.SellerService;
import com.resultentity.PageResult;

@RestController
@RequestMapping("/seller")
public class SellerController {

	@Reference
	private SellerService service;
	
	/**
	 * 不带条件的分页查询方法
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/findByPage")
	public PageResult findByPage(Integer pageNum, Integer pageSize) {
		return service.findByPage(pageNum, pageSize);
	}
	
	/**
	 * 带条件分页查询
	 * @param pageNum
	 * @param pageSize
	 * @param seller
	 * @return
	 */
	@RequestMapping("/search")
	public PageResult search(Integer pageNum, Integer pageSize, @RequestBody TbSeller seller) {
		return service.search(pageNum, pageSize, seller);
	}
	
}


(5)、SellerServiceImpl.java


package com.pinyougou.sellergoods.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pinyougou.mapper.TbSellerMapper;
import com.pinyougou.pojo.TbSeller;
import com.pinyougou.pojo.TbSellerExample;
import com.pinyougou.pojo.TbSellerExample.Criteria;
import com.pinyougou.sellergoods.service.SellerService;
import com.resultentity.PageResult;

@Service
@Transactional
public class SellerServiceImpl implements SellerService {

	@Autowired
	private TbSellerMapper mapper;

	/**
	 * 保存商家信息
	 */
	public void saveSeller(TbSeller seller) {
		// 设置注册时间和审核状态
		seller.setCreateTime(new Date());
		seller.setStatus("0");
		mapper.insert(seller);
	}

	/**
	 * 不带条件分页查询
	 */
	public PageResult findByPage(Integer pageNum, Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		Page page = (Page) mapper.selectByExample(null);
		return new PageResult(page.getTotal(), page.getResult());
	}

	/**
	 * 带条件分页查询
	 */
	public PageResult search(Integer pageNum, Integer pageSize, TbSeller seller) {
		PageHelper.startPage(pageNum, pageSize);
		TbSellerExample example = new TbSellerExample();
		Criteria criteria = example.createCriteria();
		if (!StringUtils.isEmpty(seller.getStatus())) {
			criteria.andStatusEqualTo(seller.getStatus());
		}
		Page page = (Page) mapper.selectByExample(example);
		return new PageResult(page.getTotal(), page.getResult());
	}


}


2、去商家审核详情页面


(1)、改造商家审核详情页面




(2)、sellerService.js


	//根据id查询
	$scope.findById = function(id){
		sellerService.findById(id).success(function(data){
			$scope.entity = data;
		});
	}


(3)、sellerController.js


	//根据id查询
	this.findById = function(id){
		return $http.get("../seller/findById?id=" + id);
	}


(4)、SellerController.java


	/**
	 * 根据id查询商家信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/findById")
	public TbSeller findById(String id) {
		return service.findById(id);
	}


(5)、SellerServiceImpl.java


	/**
	 * 根据id查询数据
	 */
	public TbSeller findById(String id) {
		return mapper.selectByPrimaryKey(id);
	}


3、商家审核功能实现


(1)、改造html页面




(2)、sellerService.js


	//修改商家状态
	this.updateStatus = function(sellerId, status){
		return $http.get("../seller/updateStatus.do?sellerId=" + sellerId + "&status=" + status);
	}


(3)、sellerController.js


	//修改商家状态(审核商家)
	$scope.updateStatus = function(sellerId, status){
		sellerService.updateStatus(sellerId, status).success(function(data){
			if(data.success){
				$scope.reloadList();
			}else{
				alert(data.message);
			}
		});
	}


(4)、SellerController.java


	/**
	 * 商家审核操作
	 * @param sellerId
	 * @param status
	 */
	@RequestMapping("/updateStatus")
	public ResultMessage updateStatus(String sellerId, String status) {
		try {
			service.updateStatus(sellerId, status);
			return new ResultMessage(true, "商家审核通过");
		} catch (Exception e) {
			e.printStackTrace();
			return new ResultMessage(false, "商家审核失败");
		}
	}


(5)、SellerServiceImpl.java


	/**
	 * 商家审核操作
	 */
	public void updateStatus(String sellerId, String status) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("sellerId", sellerId);
		map.put("status", status);
		mapper.updateStatus(map);
	}


(6)、TbSellerMapper.xml


	<!-- 自定义更改商家状态的方法 -->
	<update id="updateStatus" parameterType="map">
		update tb_seller set status = #{status} where seller_id = #{sellerId}
	</update>


五、使用spring-security管理商家项目(shop-web)


1、shop-web项目中加入spring-security配置


(1)、引入jar包坐标


		<!-- 引入spring-security相关配置 -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
		</dependency>
	</dependencies>


(2)、web.xml中配置spring-security过滤器链




(3)、加入spring-security.xml配置文件


<?xml version="1.0" encoding="UTF-8"?>
<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 pattern="/shoplogin.html" security="none"></http>
	<http pattern="/shoplogin_error.html" security="none"></http>
	<http pattern="/register.html" security="none"></http>
	<http pattern="/css/**" security="none"></http>
	<http pattern="/img/**" security="none"></http>
	<http pattern="/js/**" security="none"></http>
	<http pattern="/plugins/**" security="none"></http>
	<!-- 放行注册的方法 -->
	<http pattern="/seller/*.do" security="none"></http>
	
	<!-- 页面拦截规则 -->
	<http use-expressions="false">
		<!-- 登录用户是ROLE_USER才能访问以下数据 -->
		<intercept-url pattern="/**" access="ROLE_USER" />
		<form-login 
		     login-page="/shoplogin.html" 
		     default-target-url="/admin/index.html"
			 authentication-failure-url="/shoplogin_error.html" 
			 always-use-default-target="true" />
		<csrf disabled="true" />
		<headers>
			<frame-options policy="SAMEORIGIN" />
		</headers>
		
		<!-- 退出登录功能 -->
		<logout logout-success-url="/shoplogin.html"/>
	</http>
	
	<!-- 自定义登录认证的userService -->
	<beans:bean id="userDetailService" class="com.pinyougou.shop.service.UserDetailServiceImpl"></beans:bean>
	<!-- 认证管理器 -->
	<authentication-manager>
		<authentication-provider user-service-ref="userDetailService">
		</authentication-provider>
	</authentication-manager>
</beans:beans>


(4)、修改登录页面




2、实现匹配数据库中数据的登录功能


(1)、spring-security.xml中加入自定义的service实现类




	
	
	<!-- 自定义登录认证的userService -->
	<beans:bean id="userDetailService" class="com.pinyougou.shop.service.UserDetailServiceImpl">
		<beans:property name="sellerService" ref="sellerService"></beans:property>
	</beans:bean>
	
	<!-- 认证管理器 -->
	<authentication-manager>
		<authentication-provider user-service-ref="userDetailService">
		</authentication-provider>
	</authentication-manager>


(2)、springmvc.xml中加入dubbo配置




(3)、UserDetailServiceImpl.java


package com.pinyougou.shop.service;

import java.util.ArrayList;
import java.util.List;

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 com.pinyougou.pojo.TbSeller;
import com.pinyougou.sellergoods.service.SellerService;

/**
 * spring-security用户认证的实现类
 * 
 * @author wingz
 *
 */
public class UserDetailServiceImpl implements UserDetailsService {

	private SellerService sellerService;

	public void setSellerService(SellerService sellerService) {
		this.sellerService = sellerService;
	}

	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//根据用户名查询数据
		TbSeller seller = sellerService.findByUserName(username);
		//判断
		if(seller != null && "1".equals(seller.getStatus())) {
			List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
			GrantedAuthority gran = new SimpleGrantedAuthority("ROLE_USER");
			authorities.add(gran);
			return new User(username, seller.getPassword(), authorities);
		}
		return null;
	}

}


(4)、SellerServiceImpl.java


	/**
	 * 根据名称查询商家信息
	 */
	public TbSeller findByUserName(String username) {
		TbSellerExample example = new TbSellerExample();
		Criteria criteria = example.createCriteria();
		if(!StringUtils.isEmpty(username)) {
			criteria.andSellerIdEqualTo(username);
		}
		List<TbSeller> list = mapper.selectByExample(example);
		if(list != null && list.size() > 0) {
			return list.get(0);
		}else {
			return null;
		}
	}


3、实现密码加密功能


(1)、SellerController.java中注册时对密码进行加密




(2)、spring-security.xml中配置认证时加密操作




猜你喜欢

转载自blog.csdn.net/wingzhezhe/article/details/80567937