Spring Boot + Ajax: получить список объектов - PullRequest
0 голосов
/ 29 сентября 2019

Я пытаюсь заполнить раскрывающийся список на основе другого раскрывающегося списка в JSP, используя ajax, и я обнаружил, что этот учебник работает отлично: Учебник SpringBoot + Ajax , но учебник невключаю Spring Security, который я включаю в свой проект.

Сначала при запуске проекта выдается ошибка 405, в которой говорится, что метод POST не разрешен, и после некоторых исследований я обнаружилиз-за того, что CSRF по умолчанию включен Spring Boot, поэтому я отключил его и следовал предложенному здесь решению: решение для Ajax POST приводит к ошибке 405 .

После запуска проектаснова это дает мне эту ошибку:

2019-09-29 01:26:55.853  WARN 2200 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'classId': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'classId': was expecting ('true', 'false' or 'null') at [Source: (PushbackInputStream); line: 1, column: 10]]

Прошло 2 дня, и до сих пор не могу решить эту проблему.пожалуйста помоги !!коды приведены ниже.

PS: я отключил csrf в весенней конфигурации безопасности, а в файле jsp я отправил токены csrf вручную, как и в приведенном выше решении.

SpringSecurityConfig.java

//imports.....

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(myDaoAuthenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .anyRequest().authenticated()
            .and()
            .formLogin()
                .loginPage("/showLoginPage")
                .loginProcessingUrl("/authenticateUser")
            .permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/showAccessDeniedPage")
            .and().csrf().disable();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider myDaoAuthenticationProvider() {

        DaoAuthenticationProvider auth = new DaoAuthenticationProvider();

        //set the custom user detailsService
        auth.setUserDetailsService(userService);

        //set the password encoder: BCrypt
        auth.setPasswordEncoder(passwordEncoder());

        return auth;
    }
}

ClassCriteria.java

public class ClassCriteria {

    private int classId;

    public int getClassId() {
        return classId;
    }

    public void setClassId(int classId) {
        this.classId = classId;
    }
}

AccountsManagementController.java

    @PostMapping(value="/loadSectionByClass",produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody List<Section> loadSectionByClass(@RequestBody ClassCriteria classCriteria){
        //This service method works fine
        List<Section> l = sectionService.findAllSectionsByClassId(classCriteria.getClassId());

        return l;
    }

FormPage.jsp

<head>
    <meta charset="windows-1256">
    <title>Student Form</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript">
        var csrfParameter = '${_csrf.parameterName}';
        var csrfToken = '${_csrf.token}';
    </script>
</head>
<body>

<form:form action="..Here towards controller that adds student to database.." modelAttribute="studentCreation">
    Choose class:
    <form:select id="studyClassDD" path="studyClass">
        <form:option value="-">--Please Select--</form:option>
        <form:options items="${AllClasses}" itemValue="id" itemLabel="className"/>
    </form:select><br><br>

    Choose section:
    <form:select id="studySectionDD" path="studySection">
        <form:option value="-">--Please Select--</form:option>
    </form:select><br><br>

    <script type="text/javascript">
        $(document).ready(function() {
             $("#studyClassDD").change(function() {
                   var classId = $(this).find(":selected").val();

                   var jsonParams = {};
                   jsonParams['classId'] = 1;
                   jsonParams[csrfParameter] = csrfToken;

                   $.ajax({
                        type : "POST",
                        contentType : "application/json",
                        dataType : 'json',
                        url : "loadSectionByClass",
                        data: jsonParams,
                        cache : false,
                        timeout : 600000,
                        success : function(data) {

                             var slctSectionDD=$('#studySectionDD'), option="";
                             slctSectionDD.empty();

                             for (var i = 0; i < data.length; i++) {
                                 option = option + "<option value='"+data[i].id + "'>"+data[i].sectionName + "</option>";
                             }
                             slctSectionDD.append(option);
                        },
                        error : function(e) {
                            alert(e);
                        }
                   });
             });
        });
    </script>
</body>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...