/** * 注销 * * @param session * @param response */ @RequestMapping("/logout") public void logout(HttpSession session, HttpServletResponse response, HttpServletRequest request) { session.removeAttribute(WebConst.LOGIN_SESSION_KEY); Cookie cookie = new Cookie(WebConst.USER_IN_COOKIE, ""); cookie.setValue(null); cookie.setMaxAge(0);// 立即销毁cookie cookie.setPath("/"); response.addCookie(cookie); try { response.sendRedirect("/admin/login"); } catch (IOException e) { e.printStackTrace(); LOGGER.error("注销失败", e); } }
@PostMapping("/register") public String register(HttpServletRequest request, Model model){ String invitationcode = request.getParameter("invitationcode"); InvitationCode invitationCode = invitationCodeRepository.findByCodeAndState(invitationcode,0); boolean result = invitationCode == null ? true : false; if(result){ return "register"; } Role role = roleRepository.findByName("ROLE_USER"); Set<Role> authorities = new HashSet<>(); authorities.add(role); String username = request.getParameter("username"); String password = request.getParameter("password"); Author author = new Author(); author.setId(UUID.randomUUID().toString()); author.setUsername(username); author.setNick(username); author.setPassword(MD5Tools.md5EncodePassword(password,author.getUsername())); author.setAuthorities(authorities); author.setCreateTime(new Date().getTime()); author.setUpdateTime(new Date().getTime()); authorService.save(author); return "redirect:/login"; }
@PostMapping("/getUserId") @ResponseBody public String getUserId(HttpServletRequest request){ //根据当前登录用户账号获取用户信息 String account = request.getParameter("account"); Author author = authorRepository.findByUsername(account); //把上面得到的数据,打包转换为一个JSON,返回给Ajax. //先构造一个Map,把上面的数据放进去。 HashMap<String,Object> jsonMap = new HashMap<>(); if(author != null){ jsonMap.put("data",author.getId()); }else{ jsonMap.put("data","isLogin"); } ObjectMapper mapper = new ObjectMapper(); try{ String json = mapper.writeValueAsString(jsonMap); return json; }catch (Exception e){ e.printStackTrace(); } return "error"; }
@RequestMapping(value = "/checkCodes", method = RequestMethod.POST) @ResponseBody public String checkCode(HttpServletRequest request){ String invitationcode = request.getParameter("invitationcode"); InvitationCode invitationCode = invitationCodeRepository.findByCodeAndState(invitationcode,0); boolean result = invitationCode == null ? true : false; //把上面得到的数据,打包转换为一个JSON,返回给Ajax. //先构造一个Map,把上面的数据放进去。 HashMap<String,Object> jsonMap = new HashMap<>(); jsonMap.put("data",result); ObjectMapper mapper = new ObjectMapper(); try{ String json = mapper.writeValueAsString(jsonMap); return json; }catch (Exception e){ e.printStackTrace(); } return "error"; }
@Test public void doFilter_should_pass_a_requst_wrapper_to_the_filter_chain() throws Exception { // GIVeN XForwardedFilter filter = new XForwardedFilter(); HttpServletRequest request = mock(HttpServletRequest.class); FilterChain filterChain = mock(FilterChain.class); HttpServletResponse response = mock(HttpServletResponse.class); // WHeN filter.doFilter(request, response, filterChain); // THeN ArgumentCaptor<HttpServletRequestWrapper> argumentCaptor = ArgumentCaptor.forClass(HttpServletRequestWrapper.class); verify(filterChain).doFilter(argumentCaptor.capture(), eq(response)); assertThat(argumentCaptor.getValue().getRequest()).isSameAs(request); }
@Test public void getContextPath_should_return_header_value() throws Exception { // GIVeN HttpServletRequest request = mock(HttpServletRequest.class); ForwardedHttpServletRequestWrapper requestWrapper = new ForwardedHttpServletRequestWrapper(request); when(request.getHeader(XForwardedFilter.CONTEXT_HEADER_NAME)) .thenReturn(CONTEXT_HEADER_VALUE); // WHeN String contextPath = requestWrapper.getContextPath(); // THeN verify(request, never()).getContextPath(); verify(request).getHeader(XForwardedFilter.CONTEXT_HEADER_NAME); assertThat(contextPath).isEqualTo(CONTEXT_HEADER_VALUE); }
@RequestMapping(value = "/signout", method = RequestMethod.GET) @ResponseBody public String logout(HttpServletResponse response, HttpServletRequest request) { Cookie cookie = new Cookie("Authorization", ""); cookie.setMaxAge(0); cookie.setPath("/"); response.addCookie(cookie); return Hret.success(200, "success", null); }
@PostMapping(value = "login") @ResponseBody public RestResponseBo doLogin(@RequestParam String username, @RequestParam String password, @RequestParam(required = false) String remeber_me, HttpServletRequest request, HttpServletResponse response) { Integer error_count = cache.get("login_error_count"); try { UserVo user = usersService.login(username, password); request.getSession().setAttribute(WebConst.LOGIN_SESSION_KEY, user); if (StringUtils.isNotBlank(remeber_me)) { TaleUtils.setCookie(response, user.getUid()); } logService.insertLog(LogActions.LOGIN.getAction(), null, request.getRemoteAddr(), user.getUid()); } catch (Exception e) { error_count = null == error_count ? 1 : error_count + 1; if (error_count > 3) { return RestResponseBo.fail("您输入密码已经错误超过3次,请10分钟后尝试"); } cache.set("login_error_count", error_count, 10 * 60); String msg = "登录失败"; if (e instanceof TipException) { msg = e.getMessage(); } else { LOGGER.error(msg, e); } return RestResponseBo.fail(msg); } return RestResponseBo.ok(); }
@RequestMapping(value="/logout", method = RequestMethod.GET) public String logoutPage (HttpServletRequest request, HttpServletResponse response) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { new SecurityContextLogoutHandler().logout(request, response, auth); } return "redirect:/login?logout"; }
@ExceptionHandler(value = Exception.class) public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { ModelAndView mav = new ModelAndView(); mav.addObject("exception", e); mav.addObject("url", req.getRequestURI()); mav.setViewName(ERROR_VIEW_NAME); return mav; }
@ExceptionHandler(value = JsonResultException.class) @ResponseBody public ErrorInfo<String> jsonErrorHandler(HttpServletRequest request,JsonResultException e) throws Exception { ErrorInfo<String> stringErrorInfo = new ErrorInfo<>(); stringErrorInfo.setCode(ERROR_CODE); stringErrorInfo.setMsg("URL:["+request.getRequestURL()+"]"); stringErrorInfo.setResult(ERROR_RESULT); stringErrorInfo.setData(e.toString()); return stringErrorInfo; }
@ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<?> resourceNotFoundExceptionHandler(HttpServletRequest request, ResourceNotFoundException e) { logError(request, e); return ResponseEntity .status(HttpStatus.NOT_FOUND) .body(new Error() .setCode(ErrorCode.RESOURCE_NOT_FOUND_ERROR) .setMessage(e.getMessage())); }
@ExceptionHandler(ParameterIllegalException.class) public ResponseEntity<?> parameterIllegalExceptionHandler(HttpServletRequest request, ParameterIllegalException e) { logError(request, e); return ResponseEntity .status(HttpStatus.BAD_REQUEST) .body(new Error() .setCode(ErrorCode.PARAMETER_ILLEGAL_ERROR) .setMessage("An invalid value was specified for one of the query parameters in the request URL.")); }
@ExceptionHandler(ServerInternalErrorException.class) public ResponseEntity<?> serverInternalErrorExceptionHandler(HttpServletRequest request, ServerInternalErrorException e) { logError(request, e); return ResponseEntity .status(HttpStatus.INTERNAL_SERVER_ERROR) .body(new Error() .setCode(ErrorCode.RESOURCE_NOT_FOUND_ERROR) .setMessage("The server encountered an internal error. Please retry the request.")); }
@ExceptionHandler(Exception.class) public ResponseEntity<?> exceptionHandler(HttpServletRequest request, Exception e) { logError(request, e); return ResponseEntity .status(HttpStatus.INTERNAL_SERVER_ERROR) .body(new Error() .setCode(ErrorCode.SERVER_INTERNAL_ERROR) .setMessage("The server met an unexpected error. Please contact administrators.")); }
@Test public void testRun() { HttpServletRequest req = mock(HttpServletRequest.class); when(req.getMethod()).thenReturn("GET"); when(req.getRequestURL()).thenReturn(new StringBuffer("http://foo")); RequestContext context = mock(RequestContext.class); when(context.getRequest()).thenReturn(req); RequestContext.testSetCurrentContext(context); filter.run(); this.outputCapture.expect(Matchers.containsString("GET request to http://foo")); }
@RequestMapping("/tick") public void handeTick(HttpServletRequest request, HttpServletResponse response) throws IOException { DataInputStream input = new DataInputStream(request.getInputStream()); DataOutputStream output = new DataOutputStream(response.getOutputStream()); MessageOutput messageOutput = new MessageOutput(mapper, output); RemoteMessage message; while ((message = mapper.decode(input)) != null) { messageHandlerRegistry.processMessage(message, messageOutput); } messageOutput.send(statisticsManager.getStatistics()); mapper.endOutput(output); }
@RequestMapping(method = RequestMethod.GET) public ResponseEntity<?> registerCashDesk(@Context HttpServletRequest req, // @PathVariable(value = "id") String id) { Registration reg = registrationDao.getRegistration(id); if (reg == null) { return ResponseEntity.notFound().build(); } // TODO: odkomentit // reg.getValidity().setTo(new Date()); InitDto ret = getResponse(reg); return ResponseEntity.ok(ret); }
public ResponseEntity<?> registerCashDesk(@Context HttpServletRequest req, // @PathVariable(value = "id") String id) { Registration reg = getCashdesk(id); if (reg == null) { return ResponseEntity.notFound().build(); } Collection<CertificateKeystore> keystore = reg.getCashDesk().getKeystore(); boolean has = keystore.iterator().hasNext(); if (has) { KeyStore k = loadKeystore(keystore.iterator().next().getKeystoreBase64()); } // reg.getCashDesk().get; String ret = "{"// + "\"keystore\": \"" + keystore.iterator().next().getKeystoreBase64() + "\""// + ",\"dic\": \"CZ5853136575\""// + ",\"login\": \"CZ5853136575_fkabc\""// + ",\"pass\": \"F46gba3-_45f?2=\""// + ",\"cashdesk\": {"// + "\"id\": \"CZ123/AB/312\""// + ",\"premiseId\": \"OV_HLNADR_01\""// + ",\"settings\": {"// + "\"items\":\"" + Base64.getEncoder().encodeToString("{'image':'qwrdekl4kh3245234j'}".getBytes()) + "\""// + "}"// + "}"// + ",\"version\": \"1.0\""// + ",\"url\": \"https://api.eetlite.cz\""// + ",\"\": \"\""// + "}"; return ResponseEntity.ok(ret); }
private String getUserName(HttpServletRequest req) { // TODO: should be in filter and put automatically to some CONTEXT String auth = req.getHeader("Authorization"); if (auth != null) { auth = auth.substring("Basic ".length()); } if (auth == null) { return null; } auth = new String(Base64.getDecoder().decode(auth.getBytes())); String user = auth.substring(0, auth.indexOf(":")); return user; }
@RequestMapping(value = "/callback", method = RequestMethod.GET) public RedirectView fitbitAuthCallback(@RequestParam("code") String code, HttpServletRequest request) throws IOException { credentialManager.addVerifiedUser("me", code); return new RedirectView("/health/fitbit/status"); }
@RequestMapping(value = "register", method = RequestMethod.POST) public String registerUser(@ModelAttribute("username") String username, @ModelAttribute("password") String password, @ModelAttribute("email") String email, HttpServletRequest request) { String confirmationKey = service.generateConfirmationKey(); service.register(username, password, email, confirmationKey); String scheme = request.getScheme(); String serverName = request.getServerName(); int serverPort = request.getServerPort(); return scheme + "://" + serverName + ":" + serverPort + "/action/verify/" + confirmationKey; }
@Test public void getContextPath_should_call_super_method_when_no_header() throws Exception { // GIVeN HttpServletRequest request = mock(HttpServletRequest.class); ForwardedHttpServletRequestWrapper requestWrapper = new ForwardedHttpServletRequestWrapper(request); // WHeN requestWrapper.getContextPath(); // THeN verify(request).getContextPath(); }
@RequestMapping(value="ping-web-api", method=RequestMethod.GET) public @ResponseBody Map<String, String> apiProbeAjax(HttpServletRequest request){ return requestHelper.getTokenInfo(request); }
private void logError(HttpServletRequest request, Exception e) { log.error("[URI: " + request.getRequestURI() + "]" + "[error: " + e.getMessage() + "]"); }
/********************************** HELPER METHOD **********************************/ private void logError(HttpServletRequest request, Exception e) { log.error("[URI: " + request.getRequestURI() + "]" + "[error: " + e.getMessage() + "]"); }