public static ServletRequestAttributes getRequestAttributes()
{
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
return (ServletRequestAttributes) attributes;
}
(ServletRequestAttributes) attributes.getRequest;
拿到容器里的对象的方式
package com.qf.fmall.websocket;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.fmall.entity.Candidate;
import com.qf.fmall.mapper.CandidateMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
@Component
@ServerEndpoint("/test/{random}")
@Slf4j
public class CandidateSocketServer implements ApplicationContextAware {
public static Map<Double,Session> map= new HashMap<Double,Session>();
// @Autowired
// private CandidateMapper candidateMapper;
private static ApplicationContext applicationContext;
@OnOpen
public void onOpen(Session session, @PathParam("random")Double random) throws IOException, InterruptedException {
System.out.println("连接成功");
log.info("传进来的id={}",random);
map.put(random,session);
}
@OnMessage
public void onMessage(Session session,String msg) throws IOException {
ArrayList<Candidate> candidates = new ArrayList<>();
CandidateMapper candidateMapper = applicationContext.getBean(CandidateMapper.class);
Candidate c1 = candidateMapper.selectOne(new QueryWrapper<Candidate>().eq("id", 1));
Candidate c2 = candidateMapper.selectOne(new QueryWrapper<Candidate>().eq("id", 2));
candidates.add(c1);
candidates.add(c2);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(candidates);
session.getBasicRemote().sendText(json);
}
@OnClose
public void onClose(Session session) throws IOException, InterruptedException {
session.close();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
CandidateSocketServer.applicationContext = applicationContext;
}
}