Search code examples
javajqueryajaxspringspring-security

simple AJAX JQuery example gives me 500 internal server error


hi i'm working in a spring mvc project and i'm getting this error when i hit the button in my form

500 (Internal Server Error)                                    jquery.min.js:6
x.ajaxTransport.x.support.cors.e.crossDomain.send  jquery.min.js:6 
x.extend.ajax                                      AddUser:19 
doAjaxPost                                         AddUser:41 
onclick

i'm trying to do a simple AJAX JQuery example that adds users to a list but i get that error when i press the add button in my form

this is my controller class:

@Controller
public class UserListController {

 private List<User> userList = new ArrayList<User>();

     @RequestMapping(value="AddUser",method=RequestMethod.GET)
     public String showForm(){

         return "AddUser";
     }

     @RequestMapping(value="AddUser",method=RequestMethod.POST)
     public @ResponseBody String addUser(@ModelAttribute(value="user") User user, BindingResult result ) 
     {
         String returnText;

         if(!result.hasErrors())
         {
             userList.add(user);
             returnText = "User has been added to the list. Total number of users are " + userList.size();

         }
         else
         {
             returnText = "Sorry, an error has occur. User has not been added to list.";
         }

         return returnText;
     }

     @RequestMapping(value="ShowUsers")
     public String showUsers(ModelMap model) 
     {
         model.addAttribute("Users", userList);

         return "ShowUsers";
     }

}

and this is my AddUser.jsp page

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Add Users using ajax</title>

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

        <!-- <script src="resources/js/libs/jquery-2.0.2.min.js"></script> -->

        <script type="text/javascript">

        function doAjaxPost() {
        // get the form values
        var name = $('#name').val();
        var education = $('#education').val();

        $.ajax({
        type: "POST",
        url: "AddUser",
        data: "name=" + name + "&education=" + education,
        success: function(response){
        // we have the response
        $('#info').html(response);
        $('#name').val('');
        $('#education').val('');
        },
        error: function(e){
        alert('Error: ' + e);
        }
        });
        }
        </script>
    </head>
    <body>
        <h1>Add Users using Ajax ........</h1>
        <table>
            <tr><td>Enter your name : </td><td> <input type="text" id="name"><br/></td></tr>
            <tr><td>Education : </td><td> <input type="text" id="education"><br/></td></tr>
            <tr><td colspan="2"><input type="button" value="Add Users" onclick="doAjaxPost()"><br/></td></tr>
            <tr><td colspan="2"><div id="info" style="color: green;"></div></td></tr>
        </table>
        <a href="/views/ShowUsers">Show All Users</a>
    </body>
</html>

and my MvcConfiguration class since i'm using a java based configuration and not using XML

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "controllers" })
public class MvcConfig extends WebMvcConfigurerAdapter
{
     @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
       configurer.enable();
    }

//  JSP VIEW-RESOLVER
    @Bean
    public InternalResourceViewResolver jspViewResolver() {
       InternalResourceViewResolver bean = new InternalResourceViewResolver();
       bean.setOrder(2);
       bean.setPrefix("/WEB-INF/views/");
       bean.setSuffix(".jsp");
       return bean;
    }
}

EDIT: i starter a new project just for the sake of trying to know what error i'm having, i delete spring secuirty in my application, but i still can figure out whats wrong.

1) i actually dont delete spring security i just starte a new project to try to solve my url problem

2) i change my controllers and the URL attribute in my ajax script

new RequestMapping controllers:

 @RequestMapping(value="AddUser",method=RequestMethod.GET)

i deleted the "/" in the value="AddUser"

i dont have a "/" in any of my controllers if put a "/" in the controllers i have the same 500 Internal server error


Solution

  • This might be because of the CSRF protection which is enabled by default in Java configuration. Try in your configuration...

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // ...
            .csrf().disable();
    }
    

    Let me know if this works.

    EDIT**

    To include CSRF token in AJAX request, if you are using JSON, you need to put it on the http header. Sample JSP example typically would be...

    <html>
    <head>
    <meta name="_csrf" content="${_csrf.token}"/>
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
    </head>
    

    Then in your javascript call, get this parameters and add it to XMLHttpRequest's header.

    Hope this helps.

    Further reading