基于服务器端保存用户的查询参数
基于服務器端保存用戶的查詢參數
最近公司項目有一個新的需求, 希望用戶在PC查詢的參數能夠同步更新到APP端, 避免讓用戶在PC和APP端重復輸入查詢條件, 基于項目是前后端分離, APP和PC的請求參數都是一樣的且都是POST請求, 因此考慮采用攔截器的方式攔截獲取POST請求中的請求體, 同時前端請求后臺時, 統一在Header中加入當前頁面名稱(pageName)的參數, 以用戶Sessioin中的工號和pageName作為key, 將請求參數保存到Mongodb中, 基本的方案就是這樣, 下面是具體實現
自定義線程池
/*** 線程池配置** @author Eric on 2019/5/4.* @version 1.0*/ @Configuration public class ThreadPoolConfig {private static final int PROCESSOR_NUM = Runtime.getRuntime().availableProcessors();private static final int MIN_CORE_SIZE = PROCESSOR_NUM < 8 ? 16 : PROCESSOR_NUM * 2;private static final String DEFAULT_THREAD = "default";@Bean("default")public ThreadPoolTaskExecutor executorService() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setThreadNamePrefix(DEFAULT_THREAD);executor.setCorePoolSize(MIN_CORE_SIZE);executor.setMaxPoolSize(PROCESSOR_NUM * 16);executor.setQueueCapacity(PROCESSOR_NUM * 2);executor.setKeepAliveSeconds(30);executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());executor.initialize();return executor;}}自定義攔截器
HelloService封裝了保存到Mongodb或者更新到Mongodb的操作 用戶信息是從session中獲取, 具體用戶信息的實體類可以自定義
/*** 記錄本次請求參數的攔截器** @author wang.js on 2019/4/26.* @version 1.0*/ @Component public class RequestParamInterceptor implements HandlerInterceptor {@Resourceprivate HelloService helloService;@Resource(name = "default")private ThreadPoolTaskExecutor executor;private static final Logger LOGGER = LoggerFactory.getLogger(RequestParamInterceptor.class);@Overridepublic boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) {HttpSession session = httpServletRequest.getSession();if (session != null) {String pageName = httpServletRequest.getHeader("pageName");SystemUser user = (SystemUser) session.getAttribute("user");String body = new RequestWrapper(httpServletRequest).getBody();if (user != null && !StringUtils.isEmpty(pageName) && !StringUtils.isEmpty(body)) {executor.submit(() -> {helloService.saveOrUpdate(new MongoBean(pageName + user.getStaffCode(), body), "test");LOGGER.info("保存成功, key:{}, value:{}", pageName + user.getStaffCode(), body);});}}return true;}@Overridepublic void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {}@Overridepublic void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {}}HellService
HellService只是封裝了Mongodb的保存和更新操作, 僅供參考
/*** @author wang.js* @date 2018/10/29* @copyright yougou.com*/ @Service public class HelloService {@Autowiredprivate MongoBeanDao mongoBeanDao;/*** 保存* @param mongoBean*/public void save(MongoBean mongoBean) {mongoBeanDao.insert(mongoBean, "test");}/*** 查找* @param id*/public MongoBean find(String id, String collectionName) {Query query = new Query(Criteria.where("id").is(id));return mongoBeanDao.findByQuery(query, MongoBean.class, collectionName);}/*** 更新** @param mongoBean* @param collectionName* @return*/public boolean update(MongoBean mongoBean, String collectionName) {Update update = new Update().set("value", mongoBean.getValue());Query query = new Query(Criteria.where("id").is(mongoBean.getId()));mongoBeanDao.updateByQuery(update, query, MongoBean.class, collectionName);return true;}public void saveOrUpdate(MongoBean mongoBean, String collectionName) {MongoBean mongoBean1 = find(mongoBean.getId(), collectionName);if (mongoBean1 == null) {save(mongoBean);} else {update(mongoBean, collectionName);}} }自定義HttpServletRequestWrapper
因為HttpServletRequest的輸入流只能讀取一次, 所以這里使用自定義HttpServletRequestWrapper將body中的信息保存起來, 方便后續多次使用 /** * @author wang.js on 2019/4/26. * @version 1.0 */ public class RequestWrapper extends HttpServletRequestWrapper {
private final String body;public RequestWrapper(HttpServletRequest request) {super(request);StringBuilder stringBuilder = new StringBuilder();BufferedReader bufferedReader = null;InputStream inputStream = null;try {inputStream = request.getInputStream();if (inputStream != null) {bufferedReader = new BufferedReader(new InputStreamReader(inputStream));char[] charBuffer = new char[128];int bytesRead;while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {stringBuilder.append(charBuffer, 0, bytesRead);}}} catch (IOException ex) {ex.printStackTrace();} finally {if (inputStream != null) {try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}if (bufferedReader != null) {try {bufferedReader.close();} catch (IOException e) {e.printStackTrace();}}}body = stringBuilder.toString();}@Overridepublic ServletInputStream getInputStream() throws IOException {final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());return new ServletInputStream() {@Overridepublic boolean isFinished() {return false;}@Overridepublic boolean isReady() {return false;}@Overridepublic void setReadListener(ReadListener readListener) {}@Overridepublic int read() throws IOException {return byteArrayInputStream.read();}};}@Overridepublic BufferedReader getReader() throws IOException {return new BufferedReader(new InputStreamReader(this.getInputStream()));}String getBody() {return this.body;}}注冊filter
/*** 過濾器** @author wang.js on 2019/4/26.* @version 1.0*/ @WebFilter(urlPatterns = "/*",filterName = "channelFilter") public class ChannelFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {ServletRequest requestWrapper = null;if(servletRequest instanceof HttpServletRequest) {requestWrapper = new RequestWrapper((HttpServletRequest) servletRequest);}if(requestWrapper == null) {filterChain.doFilter(servletRequest, servletResponse);} else {filterChain.doFilter(requestWrapper, servletResponse);}}@Overridepublic void destroy() {} }自定義webMvc的配置
/*** 自定義webMvc的配置** @author Eric on 2018/8/19.* @version 1.0*/ @Configuration public class MyWebMvcConfig extends WebMvcConfigurerAdapter {@Resourceprivate RequestParamInterceptor requestParamInterceptor;/*** 加入到Spring MVC的攔截器鏈中** @param registry 攔截器注冊*/@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(requestParamInterceptor);}@Overridepublic void configurePathMatch(PathMatchConfigurer configurer) {super.configurePathMatch(configurer);} }以上操作就可以把在PC和APP端的請求參數保存到Mongodb中, 之后用戶進入相應的頁面時, 只需要根據當前頁面的pageName來獲取該用戶上次的請求參數即可
轉載于:https://www.cnblogs.com/shanzhai/p/10809204.html
總結
以上是生活随笔為你收集整理的基于服务器端保存用户的查询参数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 无约束梯度算法
- 下一篇: appium 移动端自动化测试工具(4)