下面列出了javax.servlet.http.HttpServletRequestWrapper#javax.servlet.http.HttpSession 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
HttpSession session = req.getSession(true);
Storage storage = (Storage) session.getAttribute(Storage.class.getName());
if (storage == null) {
storage = new Storage();
session.setAttribute(Storage.class.getName(), storage);
}
// create odata handler and configure it with EdmProvider and Processor
OData odata = OData.newInstance();
ServiceMetadata edm = odata.createServiceMetadata(new DemoEdmProvider(), new ArrayList<EdmxReference>());
ODataHttpHandler handler = odata.createHandler(edm);
handler.register(new DemoEntityCollectionProcessor(storage));
handler.register(new DemoEntityProcessor(storage));
handler.register(new DemoPrimitiveProcessor(storage));
// let the handler do the work
handler.process(req, resp);
} catch (RuntimeException e) {
LOG.error("Server Error occurred in ExampleServlet", e);
throw new ServletException(e);
}
}
@Override
public Enumeration<String> getAttributeNamesInScope(int scope) {
switch (scope) {
case PAGE_SCOPE:
return getAttributeNames();
case REQUEST_SCOPE:
return this.request.getAttributeNames();
case SESSION_SCOPE:
HttpSession session = this.request.getSession(false);
return (session != null ? session.getAttributeNames() : null);
case APPLICATION_SCOPE:
return this.servletContext.getAttributeNames();
default:
throw new IllegalArgumentException("Invalid scope: " + scope);
}
}
/**
* 向购物车添加商品
* @return 购物车页面的视图名称
*/
@RequestMapping(value="/addCar", method = RequestMethod.POST)
public String addCar(Long pid, Integer count, HttpSession session, Map<String, Object> map) {
// 1.首先获得选中的商品
Product product = productService.getProductByProductId(pid);
// 2.创建一个购物项,并设置商品的数量,商品的数量,商品的单价
CartItem cartItem = new CartItem();
cartItem.setProduct(product);
cartItem.setCount(count);
// 注:如果以后要开通优惠券系统,则需要在这里加判断即可
cartItem.setPrice(product.getSalePrice());
// 3.将该商品的信息放入session中
Cart cart = (Cart) session.getAttribute("cart");
if (cart == null) {
cart = new Cart();
session.setAttribute("cart", cart);
}
// 4.将购物项添加进来
cart.addCart(cartItem);
return "front/car";
}
@RequestMapping("/api/admin/import")
@ResponseBody
public Result importConfig(@PathVariable MultipartFile file, HttpSession session) {
Result result = new Result();
try {
String filename = file.getOriginalFilename();
// 如果已登录 && 文件不为空 && 是ini文件
if (logged(session) && (!file.isEmpty()) && filename.matches(".*(\\.ini)$")) {
File config = new File("config.ini");
config.renameTo(new File("config.ini.backup"));
File newConfig = new File(config.getAbsolutePath());
file.transferTo(newConfig);
Logger.log(newConfig.getPath());
Prop.reload();
result.setCode(200);
} else {
result.setCode(500);
}
} catch (Exception e) {
e.printStackTrace();
result.setCode(500);
}
return result;
}
public void testSearchImageResource_2() throws Throwable {
this.executeEdit("ART102", "admin");//Contenuto customers
String contentOnSessionMarker = super.extractSessionMarker("ART102", ApsAdminSystemConstants.EDIT);
//iniziazione parametri sessione
HttpSession session = this.getRequest().getSession();
session.setAttribute(ResourceAttributeActionHelper.ATTRIBUTE_NAME_SESSION_PARAM, "Foto");
session.setAttribute(ResourceAttributeActionHelper.RESOURCE_TYPE_CODE_SESSION_PARAM, "Image");
session.setAttribute(ResourceAttributeActionHelper.RESOURCE_LANG_CODE_SESSION_PARAM, "it");
this.initContentAction("/do/jacms/Content/Resource", "search", contentOnSessionMarker);
this.addParameter("resourceTypeCode", "Image");//per replicare il chain in occasione dei chooseResource da edit Contenuto.
String result = this.executeAction();
assertEquals(Action.SUCCESS, result);
ResourceFinderAction action = (ResourceFinderAction) this.getAction();
assertEquals(3, action.getResources().size());
assertTrue(action.getResources().contains("82"));
}
@ResponseBody
@RequestMapping(value = "/register.do", method = RequestMethod.POST)
public String register(User user, Invitecode invitecode, @RequestParam(value = "yzm", required = false) String yzm, HttpSession session) {
if (user.getUname().length() > 16 || user.getUpwd().length() > 16 || user.getUpwd().length() < 6) {
return "注册失败:用户名或密码长度必须小于16位";
}
if (session.getAttribute("yzm").equals(yzm.toLowerCase())) {
user.setUpwd(DigestUtils.md5DigestAsHex(user.getUpwd().getBytes()));
user.setLevel(1);
user.setUcreatetime(new Date());
user.setUstate(1);
try {
userService.register(user, invitecode);
return "注册成功";
} catch (MessageException e) {
return e.getMessage();
}
} else
return "验证码错误";
}
@Test
public void testAddEventWithWebAuthenticationDetails() {
HttpSession session = new MockHttpSession(null, "test-session-id");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
request.setRemoteAddr("1.2.3.4");
WebAuthenticationDetails details = new WebAuthenticationDetails(request);
Map<String, Object> data = new HashMap<>();
data.put("test-key", details);
AuditEvent event = new AuditEvent("test-user", "test-type", data);
customAuditEventRepository.add(event);
List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
assertThat(persistentAuditEvents).hasSize(1);
PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0);
assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4");
assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id");
}
public CopyOnWriteArrayList<UserSessionBase> getActiveSessionsOnServer() {
CopyOnWriteArrayList<HttpSession> activeHttpUserSessions = RangerHttpSessionListener.getActiveSessionOnServer();
CopyOnWriteArrayList<UserSessionBase> activeRangerUserSessions = new CopyOnWriteArrayList<UserSessionBase>();
if (CollectionUtils.isEmpty(activeHttpUserSessions)) {
return activeRangerUserSessions;
}
for (HttpSession httpSession : activeHttpUserSessions) {
if (httpSession.getAttribute(RangerSecurityContextFormationFilter.AKA_SC_SESSION_KEY) == null) {
continue;
}
RangerSecurityContext securityContext = (RangerSecurityContext) httpSession.getAttribute(RangerSecurityContextFormationFilter.AKA_SC_SESSION_KEY);
if (securityContext.getUserSession() != null) {
activeRangerUserSessions.add(securityContext.getUserSession());
}
}
return activeRangerUserSessions;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
if (!httpRequest.getRequestURI().startsWith("/api/")
&& !isSupported(httpRequest.getHeader(USER_AGENT_HEADER_NAME))) {
HttpSession session = httpRequest.getSession();
if (session.getAttribute(CONTINUE_WITH_UNSUPPORTED_BROWSER_TOKEN) == null) {
if (request.getParameter(CONTINUE_WITH_UNSUPPORTED_BROWSER_TOKEN) != null) {
session.setAttribute(CONTINUE_WITH_UNSUPPORTED_BROWSER_TOKEN, true);
} else {
httpRequest
.getRequestDispatcher(UNSUPPORTED_BROWSER_MESSAGE_PAGE)
.forward(request, response);
return;
}
}
}
chain.doFilter(request, response);
}
@Test
public void testAddEventWithWebAuthenticationDetails() {
HttpSession session = new MockHttpSession(null, "test-session-id");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
request.setRemoteAddr("1.2.3.4");
WebAuthenticationDetails details = new WebAuthenticationDetails(request);
Map<String, Object> data = new HashMap<>();
data.put("test-key", details);
AuditEvent event = new AuditEvent("test-user", "test-type", data);
customAuditEventRepository.add(event);
List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
assertThat(persistentAuditEvents).hasSize(1);
PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0);
assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4");
assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id");
}
public void getPageBean(HttpSession session, PageBean<Record> pageBean,Record record,boolean status) {
pageBean.put("record",record);
pageBean.put("running",status);
pageBean.put("currTime",new Date());
if (!JobXTools.isPermission(session)) {
User user = JobXTools.getUser(session);
pageBean.put("userId",user.getUserId());
}
List<RecordBean> records = recordDao.getByPageBean(pageBean);
if (CommonUtils.notEmpty(records)) {
int count = recordDao.getCount(pageBean.getFilter());
List<Record> recordList = new ArrayList<Record>(0);
for (RecordBean bean:records) {
Record item = Record.transfer.apply(bean);
List<Record> redoList = getRedoList(bean.getRecordId());
if (CommonUtils.notEmpty(recordList)) {
item.setRedoList(redoList);
item.setRedoCount(redoList.size());
}
recordList.add(item);
}
pageBean.setResult(recordList);
pageBean.setTotalCount(count);
}
}
private void loginUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
Map<String, Object> responseData = new HashMap<String, Object>();
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
IAuthenticationProvider authenticationProvider = Config.getAuthenticationProvider();
if(user == null) {
user = authenticationProvider.login(request);
}
if (user == null) {
responseData.put(LOGIN_STATUS_FIELD, false);
String form = authenticationProvider.getLoginForm();
if (form != null) {
responseData.put(LOGIN_FORM_FIELD, form);
}
} else {
Config.getAuthorizationProvider().setUserSecurityAttributes(user);
responseData.put(LOGIN_STATUS_FIELD, true);
responseData.put(USER_FIELD, user);
session.setAttribute("user", user);
}
HttpUtil.sendResponse(response, new ObjectMapper().writeValueAsString(responseData), HttpUtil.JSON);
}
/**
* Prj2000 권한정보 삭제(단건) AJAX
* 권한정보 삭제 처리
* @param
* @return
* @exception Exception
*/
@RequestMapping(value="/prj/prj2000/prj2000/deletePrj2000AuthGrpInfoAjax.do")
public ModelAndView deletePrj2000AuthGrpInfoAjax(HttpServletRequest request, HttpServletResponse response, ModelMap model ) throws Exception {
try{
// request 파라미터를 map으로 변환
Map<String, String> paramMap = RequestConvertor.requestParamToMapAddSelInfo(request, true);
HttpSession ss = request.getSession();
LoginVO loginVO = (LoginVO) ss.getAttribute("loginVO");
paramMap.put("licGrpId", loginVO.getLicGrpId());
// 메뉴 삭제
prj2000Service.deletePrj2000AuthGrpInfoAjax(paramMap);
//등록 성공 메시지 세팅
model.addAttribute("message", egovMessageSource.getMessage("success.common.delete"));
return new ModelAndView("jsonView");
}
catch(Exception ex){
Log.error("deletePrj2000AuthGrpInfoAjax()", ex);
//삭제실패 메시지 세팅 및 저장 성공여부 세팅
model.addAttribute("saveYN", "N");
model.addAttribute("message", egovMessageSource.getMessage("fail.common.delete"));
return new ModelAndView("jsonView");
}
}
private void setMailingWorkflowParameters(HttpServletRequest req, ComMailing mailing) {
HttpSession session = req.getSession();
Integer workflowId = (Integer) session.getAttribute(WorkflowParametersHelper.WORKFLOW_ID);
if (workflowId != null && workflowId > 0) {
Map<String, String> forwardParams = AgnUtils.getParamsMap((String) session.getAttribute(WorkflowParametersHelper.WORKFLOW_FORWARD_PARAMS));
int mailingIconId = NumberUtils.toInt(forwardParams.get("nodeId"));
workflowService.assignWorkflowDrivenSettings(AgnUtils.getAdmin(req), mailing, workflowId, mailingIconId);
}
}
@PostMapping(value = "/login")
public String login(@RequestParam("userName") String userName,
@RequestParam("password") String password,
@RequestParam("verifyCode") String verifyCode,
HttpSession session) {
if (StringUtils.isEmpty(verifyCode)) {
session.setAttribute("errorMsg", "验证码不能为空");
return "admin/login";
}
if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
session.setAttribute("errorMsg", "用户名或密码不能为空");
return "admin/login";
}
String kaptchaCode = session.getAttribute("verifyCode") + "";
if (StringUtils.isEmpty(kaptchaCode) || !verifyCode.equals(kaptchaCode)) {
session.setAttribute("errorMsg", "验证码错误");
return "admin/login";
}
AdminUser adminUser = adminUserService.login(userName, password);
if (adminUser != null) {
session.setAttribute("loginUser", adminUser.getNickName());
session.setAttribute("loginUserId", adminUser.getAdminUserId());
//session过期时间设置为7200秒 即两小时
//session.setMaxInactiveInterval(60 * 60 * 2);
return "redirect:/admin/index";
} else {
session.setAttribute("errorMsg", "登陆失败,请联系作者获得测试账号");
return "admin/login";
}
}
@RequestMapping(value= "/admin", method = RequestMethod.POST)
public ModelAndView admin(@RequestParam("SAMLRequest") String encodedSamlRequest,
@RequestParam(value = "realm", required = false) String realm, HttpSession httpSession){
User user = (User) httpSession.getAttribute(USER_SESSION_KEY);
AuthRequestService.Request requestInfo = authRequestService.processRequest(encodedSamlRequest, realm, null);
user.getAttributes().put("isAdmin", "true");
user.setImpersonationUser(null);
SamlAssertion samlAssertion = samlService.buildAssertion(user.getUserId(), user.getRoles(),
user.getAttributes(), requestInfo);
ModelAndView mav = new ModelAndView("post");
mav.addObject("samlAssertion", samlAssertion);
return mav;
}
@RequestMapping("editsingle.do")
@ResponseBody
@RequestRepeat
public Job editSingleJob(HttpSession session, HttpServletResponse response, Long id) {
Job job = jobService.getById(id);
if (job == null) {
write404(response);
return null;
}
if (!jobService.checkJobOwner(session, job.getUserId())) return null;
return job;
}
@RequestMapping("/auth2Login.do")
public void auth2Login(@RequestParam String code,@RequestParam String state,HttpServletResponse response,HttpSession session) throws IOException {
String redirectUrl = valueOperations.get(state);
Assert.hasLength(redirectUrl,"redirectUrl地址为空");
AuthAccessToken accessToken = wechatUserInfoServiceAPI.getUserInfoByCode(code);
FrontUser frontUser = new FrontUser();
WechatUserInfo wechatUserInfo = new WechatUserInfo();
if ("snsapi_base".equals(accessToken.getScope())) {//不需要用户信息
frontUser.setUserId(accessToken.getOpenid());
wechatUserInfo.setOpenid(accessToken.getOpenid());
} else if ("snsapi_userinfo".equals(accessToken.getScope())) {
UserInfo userinfo = wechatUserInfoServiceAPI.userinfo(accessToken);
frontUser.setUserId(userinfo.getOpenid());
frontUser.setName(userinfo.getNickname());
wechatUserInfo.setOpenid(userinfo.getOpenid());
wechatUserInfo.setNickname(userinfo.getNickname());
wechatUserInfo.setSex(userinfo.getSex());
wechatUserInfo.setProvince(userinfo.getProvince());
wechatUserInfo.setCity(userinfo.getCity());
wechatUserInfo.setCountry(userinfo.getCountry());
wechatUserInfo.setHeadImgUrl(userinfo.getHeadimgurl());
wechatUserInfo.setUnionid(userinfo.getUnionid());
}
WechatUserInfo dbWechatUserInfo = wechatUserInfoService.findByOpenId(wechatUserInfo.getOpenid());
if (null == dbWechatUserInfo) {
wechatUserInfoService.save(wechatUserInfo);
} else {
wechatUserInfo.setId(dbWechatUserInfo.getId());
wechatUserInfoService.updateSelective(wechatUserInfo);
}
FrontSubject.putUserSession(session, frontUser);
response.sendRedirect(redirectUrl);
}
@Override
protected void service(final HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
OData odata = OData.newInstance();
EdmxReference reference = new EdmxReference(URI.create("../v4.0/cs02/vocabularies/Org.OData.Core.V1.xml"));
reference.addInclude(new EdmxReferenceInclude("Org.OData.Core.V1", "Core"));
final ServiceMetadata serviceMetadata = odata.createServiceMetadata(
new EdmTechProvider(),
Collections.singletonList(reference),
new MetadataETagSupport(metadataETag));
HttpSession session = request.getSession(true);
DataProvider dataProvider = (DataProvider) session.getAttribute(DataProvider.class.getName());
if (dataProvider == null) {
dataProvider = new DataProvider(odata, serviceMetadata.getEdm());
session.setAttribute(DataProvider.class.getName(), dataProvider);
LOG.info("Created new data provider.");
}
ODataHttpHandler handler = odata.createHandler(serviceMetadata);
// Register processors.
handler.register(new TechnicalEntityProcessor(dataProvider, serviceMetadata));
handler.register(new TechnicalPrimitiveComplexProcessor(dataProvider, serviceMetadata));
handler.register(new TechnicalActionProcessor(dataProvider, serviceMetadata));
handler.register(new TechnicalBatchProcessor(dataProvider));
// Register helpers.
handler.register(new ETagSupport());
handler.register(new DefaultDebugSupport());
// Process the request.
handler.process(request, response);
} catch (final RuntimeException e) {
LOG.error("Server Error", e);
throw new ServletException(e);
}
}
@RequestMapping(value = "/login/timeOut")
@ResponseBody
public Response timeOut(short StatusCode, HttpSession session) {
Response response = ResponseFactory.getResponse();
response.setStateCode(StateCode.LOGIN_TIMEOUT);
response.setMessage("会话已经超时,请重新登录");
return response;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
// you can also make an authenticated request to logout, but here we choose to
// simply delete the session variables for simplicity
HttpSession session = req.getSession(false);
if (session != null) {
session.invalidate();
}
// rebuild session
req.getSession();
}
private static Object getObjectFromSession(String attributeKey) {
HttpSession session = getSession();
if (session != null) {
return session.getAttribute(attributeKey);
}
return null;
}
@Override
public void addElement(StringBuilder buf, Date date, Request request,
Response response, long time) {
HttpSession session = null;
if (request != null) {
session = request.getSession(false);
if (session != null) {
buf.append(wrap(session.getAttribute(attribute)));
}
}
}
/**
* Test isRequestedSessionIdValid method.
*/
@Test
public void testIsRequestedSessionIdValid() {
DefaultWebApplication webApp = new DefaultWebApplication();
DefaultWebApplicationRequest request = new TestWebApplicationRequest();
DefaultWebApplicationResponse response = new TestWebApplicationResponse();
request.setWebApplication(webApp);
response.setWebApplication(webApp);
webApp.linkRequestAndResponse(request, response);
HttpSession session = request.getSession(true);
request.setRequestedSessionId(session.getId());
assertTrue(request.isRequestedSessionIdValid());
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HttpSession session = request.getSession();
FrontUser frontUser =FrontSubject.getUserSession(session);
if (null == frontUser) {
response.sendError(HttpStatus.NEED_LOGIN.getValue());
return false;
} else {
FrontSubject.put(frontUser);
return true;
}
}
private void setExternalAuth(HttpSession session, boolean externalAuth)
{
if (externalAuth)
{
session.setAttribute(LOGIN_EXTERNAL_AUTH, Boolean.TRUE);
}
else
{
session.removeAttribute(LOGIN_EXTERNAL_AUTH);
}
}
/**
* Removes any temporary authentication-related data which may have been stored in the session
* during the authentication process.
*
* @param request http request.
*/
private void clearAuthenticationAttributes(HttpServletRequest request) {
// Don't create new session.
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public OIDCAuthenticationClient(ConfigurationContext ctx, String serverURL, String cookie,
HttpSession session) throws Exception {
this.session = session;
String serviceEPR = serverURL + "OIDCAuthenticationService";
stub = new OIDCAuthenticationServiceStub(ctx, serviceEPR);
ServiceClient client = stub._getServiceClient();
Options options = client.getOptions();
options.setManageSession(true);
if (cookie != null) {
options.setProperty(HTTPConstants.COOKIE_STRING, cookie);
}
}
/**
* @param tenantId
* @param httpSession
*/
public static void addSession(Integer tenantId, HttpSession httpSession) {
if (!httpSessions.containsKey(tenantId)) {
httpSessions.put(tenantId, new HashSet<HttpSession>());
}
httpSessions.get(tenantId).add(httpSession);
}
public static synchronized HttpSession getSession(String session_id) {
if (session_id == null){
return null;
}else{
return mymap.get(session_id);
}
}