热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder.sessionAttr()方法的使用及代码示例

本文整理了Java中org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder.sessio

本文整理了Java中org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder.sessionAttr()方法的一些代码示例,展示了MockHttpServletRequestBuilder.sessionAttr()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。MockHttpServletRequestBuilder.sessionAttr()方法的具体详情如下:
包路径:org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder
类名称:MockHttpServletRequestBuilder
方法名:sessionAttr

MockHttpServletRequestBuilder.sessionAttr介绍

[英]Set a session attribute.
[中]设置会话属性。

代码示例

代码示例来源:origin: spring-projects/spring-framework

@Test
public void sessionAttribute() {
this.builder.sessionAttr("foo", "bar");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals("bar", request.getSession().getAttribute("foo"));
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void mergeSession() throws Exception {
String attrName = "PARENT";
String attrValue = "VALUE";
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
.defaultRequest(get("/").sessionAttr(attrName, attrValue))
.build();
assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getSession().getAttribute(attrName), equalTo(attrValue));
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void session() {
MockHttpSession session = new MockHttpSession(this.servletContext);
session.setAttribute("foo", "bar");
this.builder.session(session);
this.builder.sessionAttr("baz", "qux");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals(session, request.getSession());
assertEquals("bar", request.getSession().getAttribute("foo"));
assertEquals("qux", request.getSession().getAttribute("baz"));
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void requestWhenConnectMessageAndUsingSockJsThenUsesCsrfTokenHandshakeInterceptor() throws Exception {
this.spring.configLocations(xml("SyncSockJsConfig")).autowire();
WebApplicationContext cOntext= (WebApplicationContext) this.spring.getContext();
MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).build();
String csrfAttributeName = CsrfToken.class.getName();
String customAttributeName = this.getClass().getName();
MvcResult result = mvc.perform(get("/app/289/tpyx6mde/websocket")
.requestAttr(csrfAttributeName, this.token)
.sessionAttr(customAttributeName, "attributeValue"))
.andReturn();
CsrfToken handshakeToken = (CsrfToken) this.testHandshakeHandler.attributes.get(csrfAttributeName);
String handshakeValue = (String) this.testHandshakeHandler.attributes.get(customAttributeName);
String sessiOnValue= (String) result.getRequest().getSession().getAttribute(customAttributeName);
assertThat(handshakeToken).isEqualTo(this.token)
.withFailMessage("CsrfToken is populated");
assertThat(handshakeValue).isEqualTo(sessionValue)
.withFailMessage("Explicitly listed session variables are not overridden");
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void requestWhenConnectMessageThenUsesCsrfTokenHandshakeInterceptor() throws Exception {
this.spring.configLocations(xml("SyncConfig")).autowire();
WebApplicationContext cOntext= (WebApplicationContext) this.spring.getContext();
MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).build();
String csrfAttributeName = CsrfToken.class.getName();
String customAttributeName = this.getClass().getName();
MvcResult result = mvc.perform(get("/app")
.requestAttr(csrfAttributeName, this.token)
.sessionAttr(customAttributeName, "attributeValue"))
.andReturn();
CsrfToken handshakeToken = (CsrfToken) this.testHandshakeHandler.attributes.get(csrfAttributeName);
String handshakeValue = (String) this.testHandshakeHandler.attributes.get(customAttributeName);
String sessiOnValue= (String) result.getRequest().getSession().getAttribute(customAttributeName);
assertThat(handshakeToken).isEqualTo(this.token)
.withFailMessage("CsrfToken is populated");
assertThat(handshakeValue).isEqualTo(sessionValue)
.withFailMessage("Explicitly listed session variables are not overridden");
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void sessionAttributesAreClearedBetweenInvocations() throws Exception {
this.mvc.perform(get("/"))
.andExpect(content().string(HELLO))
.andExpect(request().sessionAttribute(FOO, nullValue()));
this.mvc.perform(get("/").sessionAttr(FOO, BAR))
.andExpect(content().string(HELLO))
.andExpect(request().sessionAttribute(FOO, BAR));
this.mvc.perform(get("/"))
.andExpect(content().string(HELLO))
.andExpect(request().sessionAttribute(FOO, nullValue()));
}

代码示例来源:origin: apache/servicemix-bundles

/**
* Set session attributes.
* @param sessionAttributes the session attributes
*/
public MockHttpServletRequestBuilder sessionAttrs(Map sessionAttributes) {
Assert.notEmpty(sessionAttributes, "'sessionAttributes' must not be empty");
for (String name : sessionAttributes.keySet()) {
sessionAttr(name, sessionAttributes.get(name));
}
return this;
}

代码示例来源:origin: entando/entando-core

@Test
public void shouldValidateDeleteOnlinePage() throws ApsSystemException, Exception {
UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
String accessToken = mockOAuthInterceptor(user);
when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true);
when(this.controller.getPageValidator().getPageManager().getOnlinePage(any(String.class))).thenReturn(new Page());
ResultActions result = mockMvc.perform(
delete("/pages/{pageCode}", "online_page")
.sessionAttr("user", user)
.header("Authorization", "Bearer " + accessToken));
result.andExpect(status().isBadRequest());
String respOnse= result.andReturn().getResponse().getContentAsString();
result.andExpect(jsonPath("$.errors", hasSize(1)));
result.andExpect(jsonPath("$.errors[0].code", is(PageController.ERRCODE_ONLINE_PAGE)));
}

代码示例来源:origin: entando/entando-core

@Test
public void shouldAddUserAuthorities() throws Exception {
UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
String accessToken = mockOAuthInterceptor(user);
String mockJson = "[{\"group\":\"group1\", \"role\":\"role1\"},{\"group\":\"group2\", \"role\":\"role2\"}]";
List authorities = (List) this.createMetadata(mockJson, List.class);
when(this.controller.getUserValidator().getGroupManager().getGroup(any(String.class))).thenReturn(mockedGroup());
when(this.controller.getUserValidator().getRoleManager().getRole(any(String.class))).thenReturn(mockedRole());
when(this.controller.getUserService().addUserAuthorities(any(String.class), any(UserAuthoritiesRequest.class))).thenReturn(authorities);
ResultActions result = mockMvc.perform(
put("/users/{target}/authorities", "mockuser")
.sessionAttr("user", user)
.content(mockJson)
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + accessToken));
result.andExpect(status().isOk());
}

代码示例来源:origin: entando/entando-core

@Test
public void shouldValidateDeletePageWithChildren() throws ApsSystemException, Exception {
UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
String accessToken = mockOAuthInterceptor(user);
Page page = new Page();
page.setCode("page_with_children");
page.addChildCode("child");
when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true);
when(this.controller.getPageValidator().getPageManager().getDraftPage(any(String.class))).thenReturn(page);
ResultActions result = mockMvc.perform(
delete("/pages/{pageCode}", "page_with_children")
.sessionAttr("user", user)
.header("Authorization", "Bearer " + accessToken));
result.andExpect(status().isBadRequest());
String respOnse= result.andReturn().getResponse().getContentAsString();
result.andExpect(jsonPath("$.errors", hasSize(1)));
result.andExpect(jsonPath("$.errors[0].code", is(PageController.ERRCODE_PAGE_HAS_CHILDREN)));
}

代码示例来源:origin: entando/entando-core

@Test
public void shouldValidateMovePageInvalidPosition() throws ApsSystemException, Exception {
UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
String accessToken = mockOAuthInterceptor(user);
PagePositionRequest request = new PagePositionRequest();
request.setCode("page_to_move");
request.setParentCode("new_parent_page");
request.setPosition(0);

when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true);
when(this.controller.getPageValidator().getPageManager().getDraftPage("new_parent_page")).thenReturn(new Page());

ResultActions result = mockMvc.perform(
put("/pages/{pageCode}/position", "page_to_move")
.sessionAttr("user", user)
.content(convertObjectToJsonBytes(request))
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + accessToken));
result.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors", hasSize(1)))
.andExpect(jsonPath("$.errors[0].code", is(PageController.ERRCODE_CHANGE_POSITION_INVALID_REQUEST)));
}

代码示例来源:origin: entando/entando-core

@Test
public void shouldValidateMovePageMissingParent() throws ApsSystemException, Exception {
UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
String accessToken = mockOAuthInterceptor(user);
PagePositionRequest request = new PagePositionRequest();
request.setCode("page_to_move");
request.setParentCode("new_parent_page");
request.setPosition(0);
when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true);
ResultActions result = mockMvc.perform(
put("/pages/{pageCode}/position", "page_to_move")
.sessionAttr("user", user)
.content(convertObjectToJsonBytes(request))
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + accessToken));
result.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors", hasSize(1)))
.andExpect(jsonPath("$.errors[0].code", is(PageController.ERRCODE_CHANGE_POSITION_INVALID_REQUEST)));
}

代码示例来源:origin: entando/entando-core

@Test
public void shouldGetUsersList() throws Exception {
UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
String accessToken = mockOAuthInterceptor(user);
when(this.userService.getUsers(any(RestListRequest.class), any(String.class))).thenReturn(mockUsers());
ResultActions result = mockMvc.perform(
get("/users")
.param("withProfile", "0")
.param("sort", "username")
.param("filter[0].attribute", "username")
.param("filter[0].operator", "like")
.param("filter[0].value", "user")
.sessionAttr("user", user)
.header("Authorization", "Bearer " + accessToken));
System.out.println("result: " + result.andReturn().getResponse().getContentAsString());
result.andExpect(status().isOk());
}

代码示例来源:origin: entando/entando-core

@Test
public void shouldValidateMovePageNameMismatch() throws ApsSystemException, Exception {
UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
String accessToken = mockOAuthInterceptor(user);
PagePositionRequest request = new PagePositionRequest();
request.setCode("WRONG");
request.setParentCode("new_parent_page");
request.setPosition(1);

when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true);
when(this.controller.getPageValidator().getPageManager().getDraftPage("new_parent_page")).thenReturn(new Page());

ResultActions result = mockMvc.perform(
put("/pages/{pageCode}/position", "page_to_move")
.sessionAttr("user", user)
.content(convertObjectToJsonBytes(request))
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + accessToken));
result.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors", hasSize(1)))
.andExpect(jsonPath("$.errors[0].code", is(PageController.ERRCODE_URINAME_MISMATCH)));
}

代码示例来源:origin: entando/entando-core

@Test
public void shouldAdd4CharsUsernamePost() throws Exception {
UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
String accessToken = mockOAuthInterceptor(user);
String mockJson = "{\"username\": \"user\",\n"
+ " \"password\": \"new_password\",\n"
+ " \"status\": \"active\"\n"
+ "}";
when(this.userService.addUser(any(UserRequest.class))).thenReturn(this.mockUser());
ResultActions result = mockMvc.perform(
post("/users")
.sessionAttr("user", user)
.content(mockJson)
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + accessToken));
result.andExpect(status().isOk());
String respOnse= result.andReturn().getResponse().getContentAsString();
System.out.println(response);
result.andExpect(jsonPath("$.errors", hasSize(0)));
}

代码示例来源:origin: entando/entando-core

@Test
public void shouldValidateUserPut() throws Exception {
UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
String accessToken = mockOAuthInterceptor(user);
String mockJson = "{\n"
+ " \"username\": \"username_test\",\n"
+ " \"status\": \"inactive\",\n"
+ " \"password\": \"invalid spaces\"\n"
+ " }";
when(this.userManager.getUser(any(String.class))).thenReturn(this.mockUserDetails("username_test"));
ResultActions result = mockMvc.perform(
put("/users/{target}", "mismach")
.sessionAttr("user", user)
.content(mockJson)
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + accessToken));
String respOnse= result.andReturn().getResponse().getContentAsString();
System.out.println("users: " + response);
result.andExpect(status().isConflict());
}

代码示例来源:origin: DanielMichalski/spring-web-rss-channels

@Test
public void testSendEmail() throws Exception {
String from = "test@mail.com";
String message = "Mail message";
String name = "Name";
ContactForm cOntactForm= new ContactForm();
contactForm.setMail(from);
contactForm.setMessage(message);
contactForm.setName(name);
Mockito.when(mailService.sendEMail(from, mailTo, "Message from " + name, message)).thenReturn(true);
mockMvc.perform(post("/contact").accept(MediaType.APPLICATION_XHTML_XML)
.sessionAttr("contactForm", contactForm))
.andExpect(redirectedUrl("contact?sent=false"))
.andExpect(model().attributeExists("contactForm"));
}
}

代码示例来源:origin: mstine/RefactoringTheMonolith

@Test
public void shouldLoadOrderWhenContinuing() throws Exception {
this.mockMvc.perform(get("/continueOrder")
.sessionAttr("currentOrder", 10000L))
.andExpect(status().isOk())
.andExpect(model().attributeExists("currentOrder"))
.andExpect(view().name("order"));
}
}

代码示例来源:origin: entando/entando-core

@Test
public void shouldBeUnauthorized() throws Exception {
UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24")
.withGroup(Group.FREE_GROUP_NAME)
.build();
String accessToken = mockOAuthInterceptor(user);
ResultActions result = mockMvc.perform(
get("/pages/{parentCode}", "mock_page")
.sessionAttr("user", user)
.header("Authorization", "Bearer " + accessToken)
);
String respOnse= result.andReturn().getResponse().getContentAsString();
result.andExpect(status().isForbidden());
}

代码示例来源:origin: mstine/RefactoringTheMonolith

@Test
public void startsANewPizza() throws Exception {
this.mockMvc.perform(get("/addPizza")
.sessionAttr("currentOrder", 10000L))
.andExpect(status().isOk())
.andExpect(model().attributeExists("basePizzaMenuOptions"))
.andExpect(model().attributeExists("currentPizza"))
.andExpect(view().name("chooseBaseOptions"));
}

推荐阅读
  • 本文详细探讨了HTML表单中GET和POST请求的区别,包括它们的工作原理、数据传输方式、安全性及适用场景。同时,通过实例展示了如何在Servlet中处理这两种请求。 ... [详细]
  • 深入理解Cookie与Session会话管理
    本文详细介绍了如何通过HTTP响应和请求处理浏览器的Cookie信息,以及如何创建、设置和管理Cookie。同时探讨了会话跟踪技术中的Session机制,解释其原理及应用场景。 ... [详细]
  • 技术分享:从动态网站提取站点密钥的解决方案
    本文探讨了如何从动态网站中提取站点密钥,特别是针对验证码(reCAPTCHA)的处理方法。通过结合Selenium和requests库,提供了详细的代码示例和优化建议。 ... [详细]
  • 使用 Azure Service Principal 和 Microsoft Graph API 获取 AAD 用户列表
    本文介绍了一段通用代码示例,该代码不仅能够操作 Azure Active Directory (AAD),还可以通过 Azure Service Principal 的授权访问和管理 Azure 订阅资源。Azure 的架构可以分为两个层级:AAD 和 Subscription。 ... [详细]
  • 深入解析 Spring Security 用户认证机制
    本文将详细介绍 Spring Security 中用户登录认证的核心流程,重点分析 AbstractAuthenticationProcessingFilter 和 AuthenticationManager 的工作原理。通过理解这些组件的实现,读者可以更好地掌握 Spring Security 的认证机制。 ... [详细]
  • 本文深入探讨了HTTP请求和响应对象的使用,详细介绍了如何通过响应对象向客户端发送数据、处理中文乱码问题以及常见的HTTP状态码。此外,还涵盖了文件下载、请求重定向、请求转发等高级功能。 ... [详细]
  • 解决FCKeditor应用主题后上传问题及优化配置
    本文介绍了在Freetextbox收费后选择FCKeditor作为替代方案时遇到的上传问题及其解决方案。通过调整配置文件和调试工具,最终解决了上传失败的问题,并对相关配置进行了优化。 ... [详细]
  • 深入理解 .NET 中的中间件
    中间件是插入到应用程序请求处理管道中的组件,用于处理传入的HTTP请求和响应。它在ASP.NET Core中扮演着至关重要的角色,能够灵活地扩展和自定义应用程序的行为。 ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • Java 中 Writer flush()方法,示例 ... [详细]
  • Java 中的 BigDecimal pow()方法,示例 ... [详细]
  • 主要用了2个类来实现的,话不多说,直接看运行结果,然后在奉上源代码1.Index.javaimportjava.awt.Color;im ... [详细]
  • 本文详细介绍了Java中org.eclipse.ui.forms.widgets.ExpandableComposite类的addExpansionListener()方法,并提供了多个实际代码示例,帮助开发者更好地理解和使用该方法。这些示例来源于多个知名开源项目,具有很高的参考价值。 ... [详细]
  • 本文探讨了如何在 PHP 的 Eloquent ORM 中实现数据表之间的关联查询,并通过具体示例详细解释了如何将关联数据嵌入到查询结果中。这不仅提高了数据查询的效率,还简化了代码逻辑。 ... [详细]
  • PHP 过滤器详解
    本文深入探讨了 PHP 中的过滤器机制,包括常见的 $_SERVER 变量、filter_has_var() 函数、filter_id() 函数、filter_input() 函数及其数组形式、filter_list() 函数以及 filter_var() 和其数组形式。同时,详细介绍了各种过滤器的用途和用法。 ... [详细]
author-avatar
平凡洗护店
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有