目录
目录
一、拦截器------拦截登录
①添加自定义拦截器
@Configuration
public class OrderMVCConfigurer implements WebMvcConfigurer {
@Autowired
private OrderIntercept orderIntercept;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(orderIntercept);
}
}
②定义实现拦截器
@Component
public class OrderIntercept implements HandlerInterceptor {
public static ThreadLocal<MemberEntity> usernameVoThreadLocal=new ThreadLocal<>();
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//获取session里面的ZhangSan里面的值
MemberEntity attribute = (MemberEntity) request.getSession().getAttribute("ZhangSan");
System.out.println(attribute+"-=--============");
if (attribute==null){
// 没有登录
request.getSession().setAttribute("errors","清先登录");
response.sendRedirect("http://auth.gulimall.com");
return false;
}else {
// 登录成功了
usernameVoThreadLocal.set(attribute);
return true;
}
}
}
二、项目初始化时对常用数据进行缓存(提高速度)
使用spring中的InitializingBean接口,监听spring的启动过程,在spring装载完所有的bean的时候,会自动调用实现InitializingBean的afterPropertiesSet()方法,在里面去调用初始化用的服务或者逻辑就行。
秒杀场景:
@Controller
@RequestMapping("/miaosha")
public class MiaoshaController implements InitializingBean {
@Autowired
RedisService redisService;
@Autowired
GoodsService goodsService;
private HashMap<Long, Boolean> localOverMap = new HashMap<Long, Boolean>();
/**
* 系统初始化
* 将所有的商品库存加载到缓存中
* */
public void afterPropertiesSet() throws Exception {
List<GoodsVo> goodsList = goodsService.listGoodsVo();
if(goodsList == null) {
return;
}
for(GoodsVo goods : goodsList) {
redisService.set(GoodsKey.getMiaoshaGoodsStock, ""+goods.getId(), goods.getStockCount());
localOverMap.put(goods.getId(), false);
}
}
}
拓展
关于InitializingBean
和init-method
方法在初始化bean的的一些介绍,所以这里就一并记录下。
InitializingBean
的afterPropertiesSet
和init-method
相同点是都是初始化方法使用的,但是这里问题是他们谁先执行?答案是t最先执行,after再执行,init后执行。
@ComponentScan(value = "com.example.demo.other")
@Component
public class ValueInitializingBean implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet========");
}
@Bean(initMethod = "i",destroyMethod = "")
public A testInit(){
System.out.println("Init========");
return null;
}
@PostConstruct
public void t(){
System.out.println("tttttttt");
}
}
class A{
public void i(){
}
}
三、json字符串转对象的几种方式
1. java自带的原生sf.json
json字符串转对象
import net.sf.json.JSONObject
String response="{\"status\":\"error\",\"message\":\"没有选中文件!\"}";
JSONObject jsonObject=JSONObject.fromObject(response);
String documentId=(String) jsonObject.get("message");
JSONObject jsonObject = new JSONObject(JSON字符串);
2.阿里巴巴的fastjson
json字符串转对象
import com.alibaba.fastjson.JSON
HashMap al = (HashMap)JSON.parseObject(JSON字符串,HashMap.class);
PersonalVo user = (PersonalVo)JSON.parseObject(JSON字符串,PersonalVo.class);
List<类型> list=JSON.parseArray(JSON字符串,类型.class);
对象转json字符串
String json=JSON.toJSONString(要转换的对象)
3.Gson解析
json字符串转对象
Student stu = new Gson().fromJson(json, Student.class);
对象转json字符串
String json = new Gson().toJson(对象)
4.JackJson解析
json字符串转对象
Student stu = new ObjectMapper().readValue(json字符串, Student .class);
四、返回数据限制R
public class R extends HashMap<String, Object> {
private static final long serialVersionUID = 1L;
// 比较复杂的对象就可以传一个TypeReference
public <T>T getData(TypeReference<T> typeReference){
Object object = this.get("data");
String s = JSON.toJSONString(object);
T t= JSON.parseObject(s, typeReference);
return t;
}
public R setData(Object data){
put("data",data);
return this;
}
public R() {
put("code", 0);
put("msg", "success");
}
public static R error() {
return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员");
}
public static R error(String msg) {
return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
}
public static R error(int code, String msg) {
R r = new R();
r.put("code", code);
r.put("msg", msg);
return r;
}
public static R ok(String msg) {
R r = new R();
r.put("msg", msg);
return r;
}
public static R ok(Map<String, Object> map) {
R r = new R();
r.putAll(map);
return r;
}
public static R ok() {
return new R();
}
public R put(String key, Object value) {
super.put(key, value);
return this;
}
public Integer getCode() {
return (Integer) this.get("code");
}
}