品牌模块功能添加

This commit is contained in:
zhh 2018-04-13 17:46:45 +08:00
parent 42d8ff5fb3
commit 6c918f208a
18 changed files with 668 additions and 7 deletions

View File

@ -25,24 +25,47 @@
<artifactId>mall-mbg</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<build>
<plugins>

View File

@ -0,0 +1,56 @@
package com.macro.mall.bo;
import com.macro.mall.model.UmsAdmin;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Arrays;
import java.util.Collection;
/**
* SpringSecurity需要的用户详情
*/
public class AdminUserDetails implements UserDetails {
private UmsAdmin umsAdmin;
public AdminUserDetails(UmsAdmin umsAdmin) {
this.umsAdmin = umsAdmin;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
//返回当前用户的权限
return Arrays.asList(new SimpleGrantedAuthority("TEST"));
}
@Override
public String getPassword() {
return umsAdmin.getPassword();
}
@Override
public String getUsername() {
return umsAdmin.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}

View File

@ -0,0 +1,73 @@
package com.macro.mall.config;
import com.macro.mall.bo.AdminUserDetails;
import com.macro.mall.model.UmsAdmin;
import com.macro.mall.service.UmsAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
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;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
/**
* SpringSecurity的配置
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UmsAdminService adminService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()//配置权限
// .antMatchers("/").access("hasRole('TEST')")//该路径需要TEST角色
// .antMatchers("/brand/list").authenticated()//该路径需要登录认证
// .antMatchers("/brand/list").hasAuthority("TEST")//该路径需要TEST权限
.antMatchers("/**").permitAll()
.and()//启用基于http的认证
.httpBasic()
.realmName("/")
.and()//配置登录页面
.formLogin()
.loginPage("/login")
.failureUrl("/login?error=true")
.and()//配置退出路径
.logout()
.logoutSuccessUrl("/")
// .and()//记住密码功能
// .rememberMe()
// .tokenValiditySeconds(60*60*24)
// .key("rememberMeKey")
.and()//关闭跨域伪造
.csrf()
.disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(new Md5PasswordEncoder());
}
@Bean
public UserDetailsService userDetailsService() {
//获取登录用户信息
return new UserDetailsService() {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UmsAdmin admin = adminService.getAdminByUsername(username);
if(admin!=null){
return new AdminUserDetails(admin);
}
throw new UsernameNotFoundException("用户名或密码错误");
}
};
}
}

View File

@ -0,0 +1,37 @@
package com.macro.mall.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Swagger2API文档的配置
*/
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.macro.mall.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("mall后台系统")
.description("mall后台模块")
.contact("macro")
.version("1.0")
.build();
}
}

View File

@ -0,0 +1,98 @@
package com.macro.mall.controller;
import com.macro.mall.dto.CommonResult;
import com.macro.mall.dto.PmsBrandDto;
import com.macro.mall.service.PmsBrandService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* 品牌功能Controller
*/
@Controller
public class PmsBrandController {
@Autowired
private PmsBrandService brandService;
private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);
@ApiOperation(value = "获取全部品牌列表")
@RequestMapping(value = "/brand/listAll", method = RequestMethod.GET)
@ResponseBody
public Object getBrandList() {
return new CommonResult().success(brandService.listAllBrand());
}
@ApiOperation(value = "添加品牌")
@RequestMapping(value = "/brand/create", method = RequestMethod.POST)
@ResponseBody
public Object createBrand(@Validated @RequestBody PmsBrandDto pmsBrand, BindingResult result) {
if (result.hasErrors()) {
return new CommonResult().validateFailed(result.getFieldError().getDefaultMessage());
}
CommonResult commonResult;
int count = brandService.createBrand(pmsBrand);
if (count == 1) {
commonResult = new CommonResult().success(pmsBrand);
LOGGER.debug("createBrand success:{}", pmsBrand);
} else {
commonResult = new CommonResult().failed();
LOGGER.debug("createBrand failed:{}", pmsBrand);
}
return commonResult;
}
@ApiOperation(value = "更新品牌")
@RequestMapping(value = "/brand/update/{id}", method = RequestMethod.POST)
@ResponseBody
public Object updateBrand(@PathVariable("id") Long id, @Validated @RequestBody PmsBrandDto pmsBrandDto, BindingResult result) {
if(result.hasErrors()){
return new CommonResult().validateFailed(result.getFieldError().getDefaultMessage());
}
CommonResult commonResult;
int count = brandService.updateBrand(id, pmsBrandDto);
if (count == 1) {
commonResult = new CommonResult().success(pmsBrandDto);
LOGGER.debug("updateBrand success:{}", pmsBrandDto);
} else {
commonResult = new CommonResult().failed();
LOGGER.debug("updateBrand failed:{}", pmsBrandDto);
}
return commonResult;
}
@ApiOperation(value = "删除品牌")
@RequestMapping(value = "/brand/delete/{id}", method = RequestMethod.GET)
@ResponseBody
public Object deleteBrand(@PathVariable("id") Long id) {
int count = brandService.deleteBrand(id);
if (count == 1) {
LOGGER.debug("deleteBrand success :id={}", id);
return new CommonResult().success(null);
} else {
LOGGER.debug("deleteBrand failed :id={}", id);
return new CommonResult().failed();
}
}
@ApiOperation(value = "分页获取品牌列表")
@RequestMapping(value = "/brand/list", method = RequestMethod.GET)
@ResponseBody
public Object listBrand(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize) {
return new CommonResult().pageSuccess(brandService.listBrand(pageNum, pageSize));
}
@ApiOperation(value = "根据编号查询品牌信息")
@RequestMapping(value = "/brand/{id}", method = RequestMethod.GET)
@ResponseBody
public Object getBrand(@PathVariable("id") Long id) {
return new CommonResult().success(brandService.getBrand(id));
}
}

View File

@ -1,4 +1,4 @@
package com.macro.mall.demo.bo;
package com.macro.mall.dto;
import com.github.pagehelper.PageInfo;

View File

@ -0,0 +1,100 @@
package com.macro.mall.dto;
import com.macro.mall.validator.FlagValidator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
/**
* 品牌传递参数
*/
@ApiModel(value = "PmsBrandDto")
public class PmsBrandDto {
@ApiModelProperty(value = "品牌名称",required = true)
@NotNull(message = "名称不能为空")
private String name;
@ApiModelProperty(value = "品牌首字母")
private String firstLetter;
@ApiModelProperty(value = "排序字段")
@Min(value = 0, message = "排序最小为0")
private Integer sort;
@ApiModelProperty(value = "是否为厂家制造商")
@FlagValidator(value = {"0","1"}, message = "厂家状态不正确")
private Integer factoryStatus;
@ApiModelProperty(value = "是否进行显示")
@FlagValidator(value = {"0","1"}, message = "显示状态不正确")
private Integer showStatus;
@ApiModelProperty(value = "品牌logo",required = true)
@NotNull(message = "品牌logo不能为空")
private String logo;
@ApiModelProperty(value = "品牌大图")
private String bigPic;
@ApiModelProperty(value = "品牌故事")
private String brandStory;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFirstLetter() {
return firstLetter;
}
public void setFirstLetter(String firstLetter) {
this.firstLetter = firstLetter;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Integer getFactoryStatus() {
return factoryStatus;
}
public void setFactoryStatus(Integer factoryStatus) {
this.factoryStatus = factoryStatus;
}
public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getBigPic() {
return bigPic;
}
public void setBigPic(String bigPic) {
this.bigPic = bigPic;
}
public String getBrandStory() {
return brandStory;
}
public void setBrandStory(String brandStory) {
this.brandStory = brandStory;
}
}

View File

@ -0,0 +1,23 @@
package com.macro.mall.service;
import com.macro.mall.dto.PmsBrandDto;
import com.macro.mall.model.PmsBrand;
import java.util.List;
/**
* 商品品牌Service
*/
public interface PmsBrandService {
List<PmsBrand> listAllBrand();
int createBrand(PmsBrandDto pmsBrandDto);
int updateBrand(Long id, PmsBrandDto pmsBrandDto);
int deleteBrand(Long id);
List<PmsBrand> listBrand(int pageNum, int pageSize);
PmsBrand getBrand(Long id);
}

View File

@ -0,0 +1,13 @@
package com.macro.mall.service;
import com.macro.mall.model.UmsAdmin;
/**
* 后台管理员Service
*/
public interface UmsAdminService {
/**
* 根据用户名获取后台管理员
*/
UmsAdmin getAdminByUsername(String username);
}

View File

@ -0,0 +1,58 @@
package com.macro.mall.service.impl;
import com.github.pagehelper.PageHelper;
import com.macro.mall.dto.PmsBrandDto;
import com.macro.mall.mapper.PmsBrandMapper;
import com.macro.mall.model.PmsBrand;
import com.macro.mall.model.PmsBrandExample;
import com.macro.mall.service.PmsBrandService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 商品品牌Service实现类
*/
@Service
public class PmsBrandServiceImpl implements PmsBrandService{
@Autowired
private PmsBrandMapper brandMapper;
@Override
public List<PmsBrand> listAllBrand() {
return brandMapper.selectByExample(new PmsBrandExample());
}
@Override
public int createBrand(PmsBrandDto pmsBrandDto) {
PmsBrand pmsBrand = new PmsBrand();
BeanUtils.copyProperties(pmsBrandDto,pmsBrand);
return brandMapper.insertSelective(pmsBrand);
}
@Override
public int updateBrand(Long id, PmsBrandDto pmsBrandDto) {
PmsBrand pmsBrand = new PmsBrand();
BeanUtils.copyProperties(pmsBrandDto,pmsBrand);
pmsBrand.setId(id);
return brandMapper.updateByPrimaryKeySelective(pmsBrand);
}
@Override
public int deleteBrand(Long id) {
return brandMapper.deleteByPrimaryKey(id);
}
@Override
public List<PmsBrand> listBrand(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
return brandMapper.selectByExample(new PmsBrandExample());
}
@Override
public PmsBrand getBrand(Long id) {
return brandMapper.selectByPrimaryKey(id);
}
}

View File

@ -0,0 +1,29 @@
package com.macro.mall.service.impl;
import com.macro.mall.mapper.UmsAdminMapper;
import com.macro.mall.model.UmsAdmin;
import com.macro.mall.model.UmsAdminExample;
import com.macro.mall.service.UmsAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* UmsAdminService实现类
*/
@Service
public class UmsAdminServiceImpl implements UmsAdminService{
@Autowired
private UmsAdminMapper adminMapper;
@Override
public UmsAdmin getAdminByUsername(String username) {
UmsAdminExample example = new UmsAdminExample();
example.createCriteria().andUsernameEqualTo(username);
List<UmsAdmin> adminList = adminMapper.selectByExample(example);
if(adminList!=null&&adminList.size()>0){
return adminList.get(0);
}
return null;
}
}

View File

@ -0,0 +1,22 @@
package com.macro.mall.validator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
/**
* 用户验证状态是否在指定范围内的注解
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.PARAMETER})
@Constraint(validatedBy = FlagValidatorClass.class)
public @interface FlagValidator {
String[] value() default {};
String message() default "flag is not found";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

View File

@ -0,0 +1,27 @@
package com.macro.mall.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* 状态标记校验器
*/
public class FlagValidatorClass implements ConstraintValidator<FlagValidator,Integer> {
private String[] values;
@Override
public void initialize(FlagValidator flagValidator) {
this.values = flagValidator.value();
}
@Override
public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
boolean isValid = false;
for(int i=0;i<values.length;i++){
if(values[i].equals(String.valueOf(value))){
isValid = true;
break;
}
}
return isValid;
}
}

View File

@ -1,5 +1,15 @@
spring.datasource.url=jdbc:mysql://localhost:3306/mall
spring.datasource.username=root
spring.datasource.password=root
#mybatisÅäÖÃ
mybatis.mapper-locations=classpath:mapper/*.xml,classpath*:com/**/mapper/*.xml
mybatis.mapper-locations=classpath:mapper/*.xml,classpath*:com/**/mapper/*.xml
#日志配置DEBUG,INFO,WARN,ERROR
logging.level.root=warn
#单独配置日志级别
logging.level.com.macro.mall=debug
#配置日志生成路径
#logging.path=/var/logs
#配置日志文件名称
#logging.file=demo_log.log

View File

@ -1,6 +1,6 @@
package com.macro.mall.demo.controller;
import com.macro.mall.demo.bo.CommonResult;
import com.macro.mall.demo.dto.CommonResult;
import com.macro.mall.demo.dto.PmsBrandDto;
import com.macro.mall.demo.service.DemoService;
import io.swagger.annotations.Api;

View File

@ -0,0 +1,92 @@
package com.macro.mall.demo.dto;
import com.github.pagehelper.PageInfo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 通用返回对象
*/
public class CommonResult {
public static final int SUCCESS = 0;
public static final int FAILED = 1;
public static final int VALIDATE_FAILED = 2;
private int code;
private String message;
private Object data;
/**
* 普通成功返回
*
* @param data 获取的数据
*/
public CommonResult success(Object data) {
this.code = SUCCESS;
this.message = "操作成功";
this.data = data;
return this;
}
/**
* 返回分页成功数据
*/
public CommonResult pageSuccess(List data) {
PageInfo pageInfo = new PageInfo(data);
long totalPage = pageInfo.getTotal() / pageInfo.getPageSize();
Map<String, Object> result = new HashMap<>();
result.put("pageSize", pageInfo.getPageSize());
result.put("totalPage", totalPage);
result.put("pageNum", pageInfo.getPageNum());
result.put("list", pageInfo.getList());
this.code = SUCCESS;
this.message = "操作成功";
this.data = result;
return this;
}
/**
* 普通失败提示信息
*/
public CommonResult failed() {
this.code = FAILED;
this.message = "操作失败";
return this;
}
/**
* 参数验证失败使用
*
* @param message 错误信息
*/
public CommonResult validateFailed(String message) {
this.code = VALIDATE_FAILED;
this.message = message;
return this;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}

View File

@ -22,10 +22,10 @@ public class PmsBrandDto {
@Min(value = 0, message = "排序最小为0")
private Integer sort;
@ApiModelProperty(value = "是否为厂家制造商")
@FlagValidator(values = {"0","1"}, message = "厂家状态不正确")
@FlagValidator(value = {"0","1"}, message = "厂家状态不正确")
private Integer factoryStatus;
@ApiModelProperty(value = "是否进行显示")
@FlagValidator(values = {"0","1"}, message = "显示状态不正确")
@FlagValidator(value = {"0","1"}, message = "显示状态不正确")
private Integer showStatus;
@ApiModelProperty(value = "品牌logo")
private String logo;

View File

@ -12,7 +12,7 @@ import java.lang.annotation.*;
@Target({ElementType.FIELD,ElementType.PARAMETER})
@Constraint(validatedBy = FlagValidatorClass.class)
public @interface FlagValidator {
String[] values() default {};
String[] value() default {};
String message() default "flag is not found";