热门标签 | 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"));
}

推荐阅读
  • 本文讨论了在ASP中创建RazorFunctions.cshtml文件时出现的问题,即ASP.global_asax不存在于命名空间ASP中。文章提供了解决该问题的代码示例,并详细解释了代码中涉及的关键概念,如HttpContext、Request和RouteData等。通过阅读本文,读者可以了解如何解决该问题并理解相关的ASP概念。 ... [详细]
  • Asp.net Mvc Framework 七 (Filter及其执行顺序) 的应用示例
    本文介绍了在Asp.net Mvc中应用Filter功能进行登录判断、用户权限控制、输出缓存、防盗链、防蜘蛛、本地化设置等操作的示例,并解释了Filter的执行顺序。通过示例代码,详细说明了如何使用Filter来实现这些功能。 ... [详细]
  • t-io 2.0.0发布-法网天眼第一版的回顾和更新说明
    本文回顾了t-io 1.x版本的工程结构和性能数据,并介绍了t-io在码云上的成绩和用户反馈。同时,还提到了@openSeLi同学发布的t-io 30W长连接并发压力测试报告。最后,详细介绍了t-io 2.0.0版本的更新内容,包括更简洁的使用方式和内置的httpsession功能。 ... [详细]
  • 在springmvc框架中,前台ajax调用方法,对图片批量下载,如何弹出提示保存位置选框?Controller方法 ... [详细]
  • 本文介绍了ASP.NET Core MVC的入门及基础使用教程,根据微软的文档学习,建议阅读英文文档以便更好理解,微软的工具化使用方便且开发速度快。通过vs2017新建项目,可以创建一个基础的ASP.NET网站,也可以实现动态网站开发。ASP.NET MVC框架及其工具简化了开发过程,包括建立业务的数据模型和控制器等步骤。 ... [详细]
  • springmvc学习笔记(十):控制器业务方法中通过注解实现封装Javabean接收表单提交的数据
    本文介绍了在springmvc学习笔记系列的第十篇中,控制器的业务方法中如何通过注解实现封装Javabean来接收表单提交的数据。同时还讨论了当有多个注册表单且字段完全相同时,如何将其交给同一个控制器处理。 ... [详细]
  • FeatureRequestIsyourfeaturerequestrelatedtoaproblem?Please ... [详细]
  • 开发笔记:Java是如何读取和写入浏览器Cookies的
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了Java是如何读取和写入浏览器Cookies的相关的知识,希望对你有一定的参考价值。首先我 ... [详细]
  • Imtryingtofigureoutawaytogeneratetorrentfilesfromabucket,usingtheAWSSDKforGo.我正 ... [详细]
  • SpringMVC接收请求参数的方式总结
    本文总结了在SpringMVC开发中处理控制器参数的各种方式,包括处理使用@RequestParam注解的参数、MultipartFile类型参数和Simple类型参数的RequestParamMethodArgumentResolver,处理@RequestBody注解的参数的RequestResponseBodyMethodProcessor,以及PathVariableMapMethodArgumentResol等子类。 ... [详细]
  • 本文介绍了一种处理AJAX操作授权过期的全局方式,以解决Asp.net MVC中Session过期异常的问题。同时还介绍了基于WebImage的图片上传工具类。详细内容请参考链接:https://www.cnblogs.com/starluck/p/8284949.html ... [详细]
  • Todayatworksomeonetriedtoconvincemethat:今天在工作中有人试图说服我:{$obj->getTableInfo()}isfine ... [详细]
  • MySQL数据库锁机制及其应用(数据库锁的概念)
    本文介绍了MySQL数据库锁机制及其应用。数据库锁是计算机协调多个进程或线程并发访问某一资源的机制,在数据库中,数据是一种供许多用户共享的资源,如何保证数据并发访问的一致性和有效性是数据库必须解决的问题。MySQL的锁机制相对简单,不同的存储引擎支持不同的锁机制,主要包括表级锁、行级锁和页面锁。本文详细介绍了MySQL表级锁的锁模式和特点,以及行级锁和页面锁的特点和应用场景。同时还讨论了锁冲突对数据库并发访问性能的影响。 ... [详细]
  • Servlet多用户登录时HttpSession会话信息覆盖问题的解决方案
    本文讨论了在Servlet多用户登录时可能出现的HttpSession会话信息覆盖问题,并提供了解决方案。通过分析JSESSIONID的作用机制和编码方式,我们可以得出每个HttpSession对象都是通过客户端发送的唯一JSESSIONID来识别的,因此无需担心会话信息被覆盖的问题。需要注意的是,本文讨论的是多个客户端级别上的多用户登录,而非同一个浏览器级别上的多用户登录。 ... [详细]
  • 本文讨论了在shiro java配置中加入Shiro listener后启动失败的问题。作者引入了一系列jar包,并在web.xml中配置了相关内容,但启动后却无法正常运行。文章提供了具体引入的jar包和web.xml的配置内容,并指出可能的错误原因。该问题可能与jar包版本不兼容、web.xml配置错误等有关。 ... [详细]
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社区 版权所有