how to catch post request parameters in spring mvc java

I am making the following ajax call :

        contentType: "application/json; charset=utf-8",
        url : _url,
        type: "POST",
        data : JSON.stringify(objectTobeSent),
        success: function(result, status, xhr) {
            var snippetLocation = xhr.getResponseHeader("Location");
            var message = new flockback.Message(objectTobeSent.title, "", snippetLocation);
            message.addPreviewHTML("<pre> \n" +
"int main (int argc, char **argv) { \n" +
"  if (argc < 2) { \n" +
"    fprintf(stderr, \"Usage: %s foo bar baz\", argv[0]); \n" +
"  } \n" +
"} \n" +
            if (!flockback.sendMessage(message)) {
                window.location.href = snippetLocation;
        error: function(request, status, error) {

Open in new window

And in my firefox console i see the following post request :
with parameters :

Open in new window

Now i am having the following line in controller :

 @RequestMapping(value = "/snippets", method = RequestMethod.POST)
public String createSnippet(HttpServletRequest request)

Open in new window

But when i do request.getParameters("data");
I get null;
How do i get the json string that is being passed in the post request ?
Rohit BajajAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mccarlIT Business Systems Analyst / Software DeveloperCommented:
Are you sure that you want the raw JSON data? If so, you should be able to do this...
@RequestMapping(value = "/snippets", method = RequestMethod.POST)
public String createSnippet(@RequestBody String jsonString) {
    // Do something with jsonString (note you can also still keep HttpServletRequest as a parameter aswell if you need it for other things

Open in new window

But perhaps you would like Spring to process the JSON for you. If you have Jackson library on the classpath you should be able to do this...
@RequestMapping(value = "/snippets", method = RequestMethod.POST, consumes = "application/json")
public String createSnippet(@RequestParam String id, @RequestParam String title, @RequestParam String mode, @RequestParam String text) {
    // Spring will automatically parse the JSON and populate the method parameters with the values passed in the request
    // you can also still keep HttpServletRequest as a parameter aswell if you need it for other things

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Rohit BajajAuthor Commented:
Thanks the first code works.
But when i used the second on which requires jackson its giving some error . Also the code not coming inside createSnippet.

I get following error on html page :

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Error 400 Bad Request</title>
<body><h2>HTTP ERROR 400</h2>
<p>Problem accessing /snippets. Reason:
<pre>    Bad Request</pre></p><hr><i><small>Powered by Jetty://</small></i><hr/>


I have the following added in my pom.xml

Also what i want to achieve is get those parameters convert it into an object and then put it into database.
I think this cannot be done using jdbc, it probably requires hibernate..
If you can give some guidelines to start with it would be great.


Open in new window

mccarlIT Business Systems Analyst / Software DeveloperCommented:
Hmmm, I'm not 100% sure but it may be that your version of Spring (whatever it may be) doesn't work with that old Jackson v1. Can you try using Jackson v2 using a Maven dependency like this...

Open in new window

I realize it may be hard to change to newer version if you are already using elsewhere in your project.

I think this cannot be done using jdbc
No, I think this would be perfect for plain old JDBC (Hibernate would probably be overkill for such a simple task). And since you are using Spring anyway, you can use the spring-jdbc packages to make life a little easier. It contains a class called JdbcTemplate that can make using JDBC quite simple. You can setup the JdbcTemplate instance by using Spring to inject a DataSource object, and then you can simply do this in your handler method above...

jdbcTemplate.update("INSERT INTO a_table (id, title, mode, text) VALUES (?, ?, ?, ?)", id, title, mode, text);

Open in new window

Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

Rohit BajajAuthor Commented:
I tried that jdbc update but my application giving error at the line :
        jdbcTemplate.update("INSERT INTO snippets (id, title, mode, text) VALUES (?, ?, ?, ?)", snippet.getId(), snippet.getTitle(), snippet.getMode(), snippet.getText());

Caused by: 
java.lang.NoClassDefFoundError: Could not initialize class org.springframework.jdbc.core.StatementCreatorUtils
	at org.springframework.jdbc.core.ArgumentPreparedStatementSetter.cleanupParameters(
	at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(
	at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(
	at org.springframework.jdbc.core.JdbcTemplate.execute(
	at org.springframework.jdbc.core.JdbcTemplate.update(
	at org.springframework.jdbc.core.JdbcTemplate.update(
	at org.springframework.jdbc.core.JdbcTemplate.update(
	at org.directi.code.SnippetDao.insertData(
	at org.directi.code.controller.HomeController.createSnippet(
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(
	at java.lang.reflect.Method.invoke(
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(
	at org.springframework.web.servlet.DispatcherServlet.doService(
	at org.springframework.web.servlet.FrameworkServlet.processRequest(
	at org.springframework.web.servlet.FrameworkServlet.doPost(
	at javax.servlet.http.HttpServlet.service(
	at javax.servlet.http.HttpServlet.service(
	at org.eclipse.jetty.servlet.ServletHolder.handle(
	at org.eclipse.jetty.servlet.ServletHandler.doHandle(
	at org.eclipse.jetty.server.handler.ScopedHandler.handle(
	at org.eclipse.jetty.server.session.SessionHandler.doHandle(
	at org.eclipse.jetty.server.handler.ContextHandler.doHandle(
	at org.eclipse.jetty.servlet.ServletHandler.doScope(
	at org.eclipse.jetty.server.session.SessionHandler.doScope(
	at org.eclipse.jetty.server.handler.ContextHandler.doScope(
	at org.eclipse.jetty.server.handler.ScopedHandler.handle(
	at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(
	at org.eclipse.jetty.server.handler.HandlerCollection.handle(
	at org.eclipse.jetty.server.handler.HandlerWrapper.handle(
	at org.eclipse.jetty.server.Server.handle(
	at org.eclipse.jetty.server.HttpChannel.handle(
	at org.eclipse.jetty.server.HttpConnection.onFillable(
	at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(
	at org.eclipse.jetty.util.thread.QueuedThreadPool$

Open in new window

Rohit BajajAuthor Commented:
ohk. I got that working... was using older version of spring n all..
Thanks a lot mccarl... you have helped me a lot!! :)
mccarlIT Business Systems Analyst / Software DeveloperCommented:
You're welcome, did you get the Jackson JSON part working?
Rohit BajajAuthor Commented:
No i didnt try after upgrading the libraries. I just converted it manually inside like :
 public ModelAndView createSnippet(@RequestBody String jsonString) throws IOException {
        Snippet snippet = new ObjectMapper().readValue(jsonString, Snippet.class);
        String uuid = snippetDao.insertData(snippet);
        return new ModelAndView("redirect:" + "snippets/" + uuid);

Open in new window

Hey mccarl.. i have posted one more question.. which i am struggling with may be you can have a look :
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.