小编Man*_* Zi的帖子

Spring Security CSRF Token不使用AJAX

我在使用csrf令牌的春季启动应用程序中遇到问题.

我有一个表格,我可以编辑一个人.一个人可以拥有

现在让我们想象一下这个人有一辆车然后进入并储存它.下次他想删除这辆车并进入另一辆车.我创建了这个,以便列出他所有的汽车 - 他可以选择从列表中删除它.现在我从这些药片开始,并希望使用相应的ID向服务器发送POST.当我尝试时,我禁止403,我不知道为什么.

如果我从POST更改为GET,那么它可以工作.

我的JavaScript(取自本网站:http://docs.spring.io/autorepo/docs/spring-security/4.0.0.CI-SNAPSHOT/reference/htmlsingle/#the-csrfmetatags-tag)

var csrfParameter = $("meta[name='_csrf_parameter']").attr("content");
var csrfHeader = $("meta[name='_csrf_header']").attr("content");
var csrfToken = $("meta[name='_csrf']").attr("content");

// using JQuery to send a non-x-www-form-urlencoded request
var headers = {};
headers[csrfHeader] = csrfToken;
$.ajax({
    url: "./delete/car",
    type: "GET",
    headers: headers,
});

$.ajax({
     url: "./delete/car",
     type: "POST",
     headers: headers,
});
Run Code Online (Sandbox Code Playgroud)

我的控制器方法:

@RequestMapping(value = "/{login}/delete/car", method = RequestMethod.GET)
    public ModelAndView delete(@PathVariable("login") final String login) {
        System.out.println("Stop");
        return new ModelAndView("redirect:" + WebSecurityConfig.URL_PERSONS_OVERVIEW);
    }

    @RequestMapping(value = "/{login}/delete/car", method = …
Run Code Online (Sandbox Code Playgroud)

java ajax spring spring-mvc csrf

7
推荐指数
1
解决办法
1万
查看次数

Spring绑定抽象对象

我对 Spring 中的表单数据绑定有疑问。

给定一个具有以下结构的对象:

- SiteContent
|-List<Panel> boxList
Run Code Online (Sandbox Code Playgroud)

面板元素如下所示:

- Panel
|- Collection<AbstractPanelElement> panelElements
Run Code Online (Sandbox Code Playgroud)

带有 的集合AbstractPanelElements是关键点,因为 可能AbstractPanelElementsDivider,AddressIcon

如果我提交包含这些类型的多个元素的表单,我会收到以下错误:

org.springframework.beans.InvalidPropertyException: 
    Invalid property 'boxList[0].panelElements[0]' of bean class [com.panel.SiteContent]: 
    Illegal attempt to get property 'panelElements' threw exception; nested exception is org.springframework.beans.NullValueInNestedPathException: 
    Invalid property 'boxList[0].panelElements' of bean class [com.panel.SiteContent]: 
    Could not instantiate property type [com.panel.AbstractPanelElement] to auto-grow nested property path: java.lang.InstantiationException
Run Code Online (Sandbox Code Playgroud)

经过研究,我发现我们可以在控制器中设置以下内容(InitBinder):

@InitBinder
public void initBinder(WebDataBinder binder){
    binder.setAutoGrowNestedPaths(false);
}
Run Code Online (Sandbox Code Playgroud)

但这并不能解决问题,这是有道理的,我认为spring无法实例化抽象类。

现在我的问题是,我是否可以解决这个问题,或者没有办法吗?

java spring spring-mvc spring-boot

5
推荐指数
1
解决办法
1239
查看次数

如何在 Mockito 中模拟 BindingResult

我有一个这样的控制器方法:

@RequestMapping(value = "/{userId}/edit", method = RequestMethod.POST)
public ModelAndView updateUser(@PathVariable(USER_ID_PATH_VAR) final long userId, @Valid @ModelAttribute(MODEL_USER_WEB) final User user, BindingResult bindingResult, 
        final Principal principal, final Model model, @RequestParam(value = "otherLocation", required = false) Boolean isOnlyOneLocation) {
        if (bindingResult.hasErrors()) {
            return new ModelAndView(URL_EDIT_USER);
        }       

        // do something ...
        return new ModelAndView(URL_FINISH_USER);
}
Run Code Online (Sandbox Code Playgroud)

我的测试是这样的:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={ManageUsersControllerTestConfig.class})
public class ManageUserControllerTest {

    @Autowired
    private ManageUserController userController;

    @Autowired
    private Model model;

    private MockMvc mockMvc;

    @Autowired
    private BindingResult bindingResult;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);

        InternalResourceViewResolver viewResolver …
Run Code Online (Sandbox Code Playgroud)

spring unit-testing mocking spring-mvc mockito

5
推荐指数
1
解决办法
4233
查看次数

无法在Spring Boot Test 1.4中找到SpringBootConfiguration

我无法在spring boot 1.4中运行简单的测试.我从官方网站test-the-spring-mvc-slice跟随教程,但我没有让它工作.

每次我收到以下错误:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
Run Code Online (Sandbox Code Playgroud)

任何想法,提示?

提前致谢

编辑:

这是控制器

@Controller
public class UserManagementController {

@GetMapping(value = "/gs/users/getUsers")
    public @ResponseBody String getAllUsers() {
        return "test";
    }
}
Run Code Online (Sandbox Code Playgroud)

这是考验

@RunWith(SpringRunner.class)
@WebMvcTest(UserManagementController.class)
public class UserManagementControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void showUserView() throws Exception {
        this.mvc.perform(get("/gs/users/getUsers"))
            .andExpect(status().isOk())
            .andDo(print());
    }
}
Run Code Online (Sandbox Code Playgroud)

从我的观点来看,它与网站上的这篇文章完全相同.

@WebMvcTest会做:

  • 自动配置Spring MVC,Jackson,Gson,Message转换器等.
  • 加载相关组件(@Controller,@RestController,@JsonComponent等)
  • 配置MockMVC …

testing spring spring-mvc spring-test spring-boot

5
推荐指数
1
解决办法
2万
查看次数

如何使用 javascript 变量访问模型属性

ModelAndView在 spring 中添加了一个属性,之后我将其转发到我的 thymeleaf 视图。

在视图中我有以下代码:

<script th:inline="javascript">
        /*<![CDATA[*/
            var applicationName = /*[[${T(com.sample.constants.ApplicationConstants).MODEL_ATTR_COLLECTED_VALUES}]]*/ "Test";
            var collectedValueJson = [[${collectedValues}]];
            console.log(collectedUserJson);
        /*]]>*/
</script>
Run Code Online (Sandbox Code Playgroud)

由此得出的结果是

var applicationName = 'collectedValues';
var collectedUserJson = '[{\"givenname\":\"Muster\",\"surname\":\"Peter\"}]';
Run Code Online (Sandbox Code Playgroud)

没关系。现在我的愿望是,我可以使用var application这个变量访问模型属性,但这不起作用。

结果是这样的:

var tmp2 = ${applicationName};
Run Code Online (Sandbox Code Playgroud)

/*[[ ]]*/另一种尝试是,我可以使用第一次尝试的语法访问 modelattribute :

var applicationName = ${/*[[${T(com.sample.constants.ApplicationConstants).MODEL_ATTR_COLLECTED_VALUES}]]*/};
Run Code Online (Sandbox Code Playgroud)

但结果将是:

var tmp = ${'collectedValues'
Run Code Online (Sandbox Code Playgroud)

我不知道我能尝试什么。

还有其他建议吗?

提前致谢。

javascript java spring thymeleaf

2
推荐指数
1
解决办法
2万
查看次数

Collectors.toMap的默认返回值

如果我们成像,我们有一个名为person的对象,而人看起来像下面这样:

class Person {
    int id;
    String name;
    String country
    // ...
    // getter/setter
}
Run Code Online (Sandbox Code Playgroud)

我们有一个ListPerson对象,我们要"转换"到一个地图.我们可以使用以下内容:

Map<Long, List<Person>> collect = personList.stream().
    collect(Collectors.toMap(Person::getId, p -> p));
Run Code Online (Sandbox Code Playgroud)

但是可以返回valuemapper的默认值并更改valuemapper的类型?

我想过这样的事情:

Map<Long, List<Person>> collect = 
     personList.stream().collect(Collectors.groupingBy(Person::getId, 0));
Run Code Online (Sandbox Code Playgroud)

但有了这个我得到以下错误 is not applicable for the arguments

我有一个解决方法,但我认为它不是很漂亮.

Map<Long, Object> collect2 = personList.stream().
    collect(Collectors.toMap(Person::getId, pe -> {
            return 0;
    }));
Run Code Online (Sandbox Code Playgroud)

java lambda dictionary java-8 collectors

2
推荐指数
1
解决办法
772
查看次数

使用 'sec:authentication="name"' 构建 url

我想知道是否有可能构建 url。

我使用的是什么:

  • 弹簧靴+弹簧安全
  • 百里香叶

使用以下表达式,我得到用户名

sec:authentication="name"
Run Code Online (Sandbox Code Playgroud)

如果我执行以下操作,将显示当前用户名

<span id="userName" sec:authentication="name">Testuser</span>
Run Code Online (Sandbox Code Playgroud)

但现在我想建立一个如下所示的网址:

<a th:href="@{'~/' + __${{sec.authentication='name'}}__ + '/edit'}" class="text-left">Settings</a>
Run Code Online (Sandbox Code Playgroud)

有了这个,我得到以下错误:

org.springframework.expression.spel.SpelEvaluationException: EL1009E:(pos 4): Property or field 'authentication' cannot be set on null
Run Code Online (Sandbox Code Playgroud)

有什么建议?

提前致谢。

spring spring-security thymeleaf

1
推荐指数
1
解决办法
2029
查看次数

使用其他列表中的值减少列表

是否可以根据其他列表中的条目减少列表?

这是类似的东西:

list1.forEach(l1 -> {
    list2.forEach(l2 -> {
        if (l1.getId() == l2.getId())
            reducedActions.add(l2); // that's the new list where the filtered entries should be add
    });
});
Run Code Online (Sandbox Code Playgroud)

编辑:我所感谢的:

l1: 10, 15, ,16
l2: 1, 2, 12, 10, 11, 14, 16
reducedActions: 10, 16
Run Code Online (Sandbox Code Playgroud)

java lambda java-8 java-stream

1
推荐指数
1
解决办法
466
查看次数

弹簧执行器“ /执行器”端点不可用

我创建了一个简单的示例项目,仅包含spring-web和spring-actuator。我无法/actuator在该项目中调用端点。我唯一得到的是404错误:

There was an unexpected error (type=Not Found, status=404). No message available

在日志中,我什么都看不到。为了避免安全问题,我激活了management.security.enabled=false中的application.properties

在其他具有相同spring,spring-web和spring-actuator版本的项目中,我达到了/actuator终点,但看不到差异。

这是示例项目的github链接:https : //github.com/ManuZiD/mzd-actuator

任何建议都很好。提前致谢。

spring spring-mvc spring-boot spring-boot-actuator

1
推荐指数
1
解决办法
1289
查看次数