how to catch post request parameters in spring mvc java

HI,
I am making the following ajax call :

$.ajax({
        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" +
"</pre>");
            if (!flockback.sendMessage(message)) {
                window.location.href = snippetLocation;
            }
        },
        error: function(request, status, error) {
            alert(request.responseText);
        }
    });

Open in new window


And in my firefox console i see the following post request :
with parameters :
{"id":null,"title":"Title","mode":"application/xml","text":"<robin>\n</robin>"}

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 ?
Thanks
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

0

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:
Hi,
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 :

html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Error 400 Bad Request</title>
</head>
<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/>

</body>
</html>

I have the following added in my pom.xml
<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>


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.

thanks

Open in new window

0
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...
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.6.2</version>
</dependency>

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

1
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Rohit BajajAuthor Commented:
HI,
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(ArgumentPreparedStatementSetter.java:72)
	at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:881)
	at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:866)
	at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:629)
	at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:866)
	at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:927)
	at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:937)
	at org.directi.code.SnippetDao.insertData(SnippetDao.java:24)
	at org.directi.code.controller.HomeController.createSnippet(HomeController.java:35)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)
	at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212)
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
	at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:808)
	at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:587)
	at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
	at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
	at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
	at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
	at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
	at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
	at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
	at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
	at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
	at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
	at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
	at org.eclipse.jetty.server.Server.handle(Server.java:499)
	at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:310)
	at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
	at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
	at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
	at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
	at java.lang.Thread.run(Thread.java:745)

Open in new window

0
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!! :)
0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
You're welcome, did you get the Jackson JSON part working?
0
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 :
http://www.experts-exchange.com/questions/28720201/when-using-redirect-in-spring-mvc-its-redirecting-to-null.html
0
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
Java

From novice to tech pro — start learning today.