I want to redirect to a another jsp page.in Spring MVC But I get HTTP Status 404 - /registration.jsp error.all i want to do is to open page. register new person page or add new product page from the home page
the path or project hierarchy:
I dont want to use JSTL or tag's. What is the best way to do this?
I tried this on my JSP page:
<ul class="nav child_menu" style="display: none"> <li>User Registartion
</li>
<li><a href="${pageContext.request.contextPath}/grcon?path=usermang">User Management</></li></ul>
And my controller:
#RequestMapping(value ="/grcon/{path}" ,method = RequestMethod.GET)
public ModelAndView getGrcon(#PathParam(value = "path") String path)
{
ModelAndView modegeron = null;
if (path != null && path.equals("register")) {
modegeron = new ModelAndView("registeruser");
} else if (path != null && path.equals("usermang"))
{
modegeron = new ModelAndView("manageuser");
} else {
modegeron = new ModelAndView("index");
}
return modegeron;
}
}
spring-dispatcher-servlet.xml
<context:component-scan base-package="recon.controller" />
<!-- viewResolver tell which viewResolver to use it tell the location of
the view in the project -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:resources location="/resoures/**" mapping="/resoures/"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
</beans>
web.xml
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>15</session-timeout>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
HTTP Message
HTTP Status 400 - Required String parameter 'path' is not present
type Status report
message Required String parameter 'path' is not present
description The request sent by the client was syntactically incorrect.
Apache Tomcat/7.0.67
You can either pick request parameters or url template variables in your controller or jsp.To use url template variables replace #PathParam(value="path") with #PathVariable(value = "path").
In your jsp replace the link url with
href="${pageContext.request.contextPath}/grcon/register and href="${pageContext.request.contextPath}/grcon/usermang
To use request parameters replace #PathParam(value = "path") with #RequestParam(value = "path"). Then mantain your jsp url links as they already use request parameters
NB. The PathParam annoation is not part of Spring MVC. Its a JAX-RS annotation for use with JEE standard
After lots for reading i notice i was not doing the right thing the below code work for me
Controller
#RequestMapping(value ="/register" ,method = RequestMethod.GET)
public ModelAndView getRegister()
{
ModelAndView modelregister = new ModelAndView();
modelregister.setViewName("registeruser");
modelregister.addObject("Registration", "info");
return modelregister;
}
#RequestMapping(value ="/manageuser" ,method = RequestMethod.GET)
public ModelAndView getManageUser()
{
ModelAndView modelManageUser = new ModelAndView();
modelManageUser.setViewName("manageuser");
modelManageUser.addObject("User Records", "records");
return modelManageUser;
}
JSP
<ul class="nav child_menu" style="display: none">
<li>User Registration</li>
<li>User Management</li>
</ul>
Related
I am using Spring Security 3.1.3.RELEASE in my maven pom because the book am reading is 2013 and that is what they used and have the following code snippets:
// AdminController
#Controller
#RequestMapping("/admin")
public class AdminController {
#RequestMapping(method=RequestMethod.POST, value="/movies")
#ResponseBody
public String createMovie(#RequestBody String movie) {
System.out.println("Adding movie!! "+movie);
return "created";
}
}
// LoginController
#Controller
#RequestMapping("")
public class LoginController {
#RequestMapping(method= {RequestMethod.GET, RequestMethod.POST}, value="/custom_login")
public String showLogin() {
return "login";
}
}
// web.xml
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-security.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>terrormovies</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>terrormovies</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
// Spring security Config :: applicationContext-security.xml
<security:http auto-config="true">
<security:intercept-url pattern="/admin/**/*" access="ROLE_ADMIN" />
<security:form-login login-page="/custom_login" username-parameter="user_param" password-parameter="pass_param"/>
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user authorities="ROLE_ADMIN" name="admin" password="admin" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
//login.jsp
<%# 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>Terror movies</title>
</head>
<body>
<form action="/j_spring_security_check" method="POST">
Username<input type="text" name="user_param"/><br/>
Password<input type="password" name="pass_param"/><br/>
<input type="submit" value="Login"/>
</form>
</body>
<% if(request.getParameter("error") != null){
out.println("ERROR LOGIN");
}
%>
</html>
When I start my application I get the login page with the form alright. I enter admin/admin as username/password respectively. When i click on the login button I get this error page saying:
Problem accessing /admin/movies. Reason:
Request method 'GET' not supported
Powered by Jetty://
instead of going to the method createMovie(#RequestBody String movie) in the
AdminController.
The address of this error page is :: http://localhost:8080/admin/movies
The LoginController and AdminController are in the same package.
What am I missing here?
Updated
In the form action:: <form action="/j_spring_security_check" method="POST">,
where does "/j_spring_security_check"` leads to? I think that is where the problem is. Am beginner in Spring Security so I can't figure it out now. I did a search but not any good answer.
The error response message you are receiving tells you exactly what the problem is:
When i click on the login button i get this error page saying::
Problem accessing /admin/movies. Reason:
Request method 'GET' not supported
Powered by Jetty://
And in your controller you have set this method:
#Controller
#RequestMapping("/admin")
public class AdminController {
#RequestMapping(method=RequestMethod.POST, value="/movies")
#ResponseBody
public String createMovie(#RequestBody String movie) {
System.out.println("Adding movie!! "+movie);
return "created";
}
}
And just as the message says, the /admin/movies method is mapped just for POST requests, so a GET request which is what is generated on redirection from the login success cannot be handled.
So here the trouble is not really the spring-security config, the problem is just that after login you are making a request to a request-mapping annotated method which does not support GET requests.
To solve it you could just configure this method into the existing AdminController:
#RequestMapping(method=RequestMethod.GET, value="/movies")
public String createMovieForm() {
return "createMovieForm";
}
And create a jsp with a form which points to the POST mapped controller method:
<form action="/admin/movies" method="POST">
Movie<input type="text" name="movie"/><br/>
<input type="submit" value="Login"/>
</form>
I would be easier too if you delete the #RequestBody annotation in the POST method, so finally the AdminController should end like this:
#Controller
#RequestMapping("/admin")
public class AdminController {
#RequestMapping(method=RequestMethod.POST, value="/movies")
#ResponseBody
public String createMovie(String movie) {
System.out.println("Adding movie!! "+movie);
return "created";
}
#RequestMapping(method=RequestMethod.GET, value="/movies")
public String createMovieForm() {
return "createMovieForm";
}
}
In my Spring MVC application, I want to redirect my page from index.jsp page to final.jsp page using AJAX. But the redirected page (final.jsp) is not being displayed when I click the Redirect Page button in my application. I have used System.out.println("inside /redirect"); and System.out.println("inside /finalPage"); inside my Java code to check whether the AJAX GET request is being received at server or not, and only inside /redirect is being printed which which means that the /finalPage is not being called. Moreover, my browser's console does not show any error. So please tell, what can be the problem and where is that problem? I have posted my complete code below:
WebController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class WebController {
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
return "index";
}
#RequestMapping(value = "/redirect", method = RequestMethod.GET)
public String redirect() {
System.out.println("inside /redirect");
return "redirect:/finalPage";
}
#RequestMapping(value = "/finalPage", method = RequestMethod.GET)
public String finalPage() {
System.out.println("inside /finalPage");
return "final";
}
}
index.jsp
<%#taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring Page Redirection</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h2>Spring Page Redirection</h2>
<p>Click below button to redirect the result to new page</p>
<button onClick="redFun()">Redirect Page</button>
<script>
function redFun() {
$.ajax({
type : "GET",
url : "/HelloWeb/redirect"
});
}
</script>
</body>
</html>
final.jsp
<%#taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring Page Redirection</title>
</head>
<body>
<h2>Redirected Page</h2>
</body>
</html>
web.xml:
<web-app id = "WebApp_ID" version = "2.4"
xmlns = "http://java.sun.com/xml/ns/j2ee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
HelloWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
</beans>
Your browser is not following the redirect because you're using ajax to hit your controller's redirect method. You have two options:
Don't use ajax at all, and let your browser respond naturally to the redirect status.
function redFun() {
window.location = "/HelloWeb/redirect";
}
Look for an HTTP 302 response to the XmlHttpRequest, and change window.location to the value of the Location header in the response:
function redFun() {
$.ajax({
type: "GET",
url: "/HelloWeb/redirect"
}).fail(function (jqXHR, status, err) {
if (jqXHR.status === 302) {
window.location = jqXHR.getResponseHeader('Location');
}
});
}
Hi I am facing two problem
HTTP status 404 (!important)
When I select Run on server on one particular project 'Two different dynamic projects executes' .
HTTP Status 404
message /RealTimeCurValue/RTCurrValue.do
description The requested resource is not available.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<display-name>Pavan</display-name>
<welcome-file-list>
<welcome-file>RTCurrValue.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>RTCV</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>ContextConfigLocation</param-name>
<param-value>/WEB-INF/classes/Spring/RTCV-servlet.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>RTCV</servlet-name>
<url-pattern>*.to</url-pattern>
</servlet-mapping>
RTCV-servlet.xml
<context:component-scan base-package="com.fact.mvcApp" />
<bean id="RTC"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
RealTimeCurrValueController.java
#Component
#RequestMapping("/")
public class RealTimeCurrValueController
{
#Autowired
private RealTimeCurrValueService service;
public RealTimeCurrValueController()
{
System.out.println(this.getClass().getSimpleName()+ "Created");
}
#RequestMapping(value="/RTCurrValue.do", method = RequestMethod.POST)
public ModelAndView realTimeCurrValueController( #ModelAttribute RealTimeCurrValueDTO dto , HttpServletRequest req)
{
System.out.println("RealTimeCurrValue Controller Started ");
CbBtc rtvcDTO = null;
System.out.println(dto);
if(dto!= null)
{
String cValue = dto.getCryptoCurrency();
System.out.println("cValue-----" +cValue);
try
{
rtvcDTO = service.rtcvService(cValue);
}
catch (IOException e)
{
e.printStackTrace();
}
if(rtvcDTO != null)
{
HttpSession session =req.getSession();
System.out.println(" Success");
return new ModelAndView("Welcome.jsp" , "value" , rtvcDTO.getAmount() );
}
}
System.out.println("RealTimeCurrValue Controller Ended ");
return null;
}
}
RTCurrValue.jsp
<form action="RTCurrValue.do" method="post">
Currency: <input type="text" name="currency" />
<input type= "submit" value="OK">
</form>
Your form action is relative to the current page i.e. /RTCurrValue, so the url used to post the form is "/RTCurrValue/RTCurrValue.do" which is giving the 404.
If your web app is running as the ROOT web app then try adding a / to the form action. action="/RTCurrValue.do".
If your web app is running in some other context then add the context to the action. action="/someContext/RTCurrValue.do"
Or better construct the URL using the standard tags.
<c:url var="formAction" value="/RTCurrValue.do"/>
<form action="${formAction}" method="post">
I have a from and when the form is filled and submitted I wanted the request to be http://localhost:8080/restroo/admin/adminLog but it gives http://localhost:808/adminLogand getting 404 error. I don't know why I am having this problem and actually I was having problem in using two controllers in spring.
web.xml
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I have spring-servlet.xml
admin.jsp
<form method="post" action="/adminLog" modelAttribute="adminUser">
First Name: <input type = "text" name = "userName">
<br />
password <input type = "password" name = "password" />
<input type = "submit" value = "Submit" />
</form>
AdminPageController.java
#Controller
#RequestMapping("/admin/*")
public class AdminPageController {
#Autowired
AdminUser adminUser;
#Autowired
MenuItems menuItems;
#Autowired
MenuItemsDao menuItemsDao;
#Autowired
AdminLoginDao adminLoginDao;
#RequestMapping(value="", method=RequestMethod.GET)
public ModelAndView addMenuItems(#ModelAttribute MenuItems menuItems){
// if(menuItems != null){
// menuItemsDao.addItems(menuItems);
// }
return new ModelAndView("admin");
}
#RequestMapping(value="/adminLog", method=RequestMethod.POST)
public ModelAndView adminLogin(#ModelAttribute("adminUser") AdminUser ad){
List<AdminUser> adminUser = adminLoginDao.adminLogin();
int len = adminUser.size();
for(int i=1;i<=len;i++){
String userN = adminUser.get(i).getUserName();
String pass = adminUser.get(i).getPassword();
if(userN.equals(ad.getUserName()) && (pass.equals(ad.getPassword()))){
return new ModelAndView("adminLogin");
}
}
return new ModelAndView("admin");
}
}
You are using Internal Resource View Resolver It is not able fetch view Not In Web-INF Floader.
Find This http://www.baeldung.com/spring-mvc-view-resolver-tutorial.
You have to change servlet mapping by adding a prefix for the API of the whole app:
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/restroo</url-pattern>
</servlet-mapping>
I am trying to send JSON to a Spring MVC Controller. On the Spring MVC side, everything is configured correctly.
Below is the code but doesn't seem to run:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$('#myForm').on('submit', function(e) {
e.preventDefault();
var frm = $("#myForm");
var dat = frm.serialize();
$.ajax({
type: 'POST',
url: $('#myForm').attr('action'),
data: dat,
contentType: 'application/json'
success: function(hxr) {
alert("Success: " + xhr);
}
});
});
</script>
</head>
<body>
<h2>Application</h2>
<form id="myForm" action="/application/save" method="POST" accept="application/json" onclick="i()">
<input type="text" name="name" value="myName">
<input type="submit" value="Submit">
</form>
In Tomcat I get the following error:
org.springframework.web.servlet.mvc.support.DefaultHandlerE
xceptionResolver handleNoSuchRequestHandlingMethod
WARNING: No matching handler method found for servlet request: path '/application/save', method 'POST', parameters map['name' -> array['myName']]
Any ideas where I am going wrong? I am new to JSON. I am trying to to send JSON to Spring MVC controller.
#Controller
#RequestMapping("/run/*")
public class HistoryController {
#RequestMapping(value = "save", method = RequestMethod.POST, headers = {"content-type=application/json"})
public #ResponseBody Response save(#RequestBody User user) throws Exception {
Response userResponse = new Response();
System.out.println("UserId :" + " " + user.getName());
return userResponse;
}
}
#RequestMapping(value = "find", method = RequestMethod.GET)
public #ResponseBody Response find() {
System.out.println("Run");
Response userResponse = new Response();
userResponse.setVersionNumber("1.0");
return userResponse;
}
When invoking /application/run/save I get a JSON response. However the #RequestBody does not work.
I still have had no luck. Have read some many similiar problems. The requirement is that the server will only accept application/json types. I am using a Spring MVC Controller. As mentioned earlier, the code sends a response back as JSON through #ResponseBody. I want to get information through the #RequestBody in my Spring MVC Controller. I am using JSP to send JSON to Spring MVC Controller. My code and Spring MVC can be seen below:
I am new to JSON and Javascript.
JSP - index.jsp
<%#page language="java" contentType="text/html"%>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$('#myForm').on('submit', function(e) {
var frm = $("#myForm");
var dat = JSON.stringify(frm.serializeArray());
$.ajax({
type: 'POST',
url: $('#myForm').attr('action'),
data: dat,
contentType: 'application/json',
dataType: 'json',
error: function() {
alert('failure');
}
success: function(hxr) {
alert("Success: " + xhr);
}
});
);
};
</script>
</head>
<body>
<h2>Application</h2>
<form id="myForm" action="/application/save" method="POST" accept="application/json" onclick="i()">
<input type="text" name="userId" value="User">
<input type="submit" value="Submit">
</form>
</body>
</html>
When running this I am not getting any output. In the Chrome I get 404 Not found error and in Tomcat I get the following error:
org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleNoSuchRequestHandlingMethod
WARNING: No matching handler method found for servlet request: path '/application/sa
ve', method 'POST', parameters map['userId' -> array<String>['User']]
Is something wrong here in the JSP part?
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
version="2.5">
<display-name>WebApp</display-name>
<context-param>
<!-- Specifies the list of Spring Configuration files in comma separated format.-->
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/service.xml</param-value>
</context-param>
<listener>
<!-- Loads your Configuration Files-->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>application</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>application</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<context:component-scan base-package="com.web"/>
<mvc:annotation-driven/>
<context:annotation-config/>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean id="jacksonMessageChanger" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json"/>
</bean>
<!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageChanger"/>
</list>
</property>
</bean>-->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="jacksonMessageChanger"/>
</util:list>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json"/>
</map>
</property>
</bean>-->
</beans>
Controller
package com.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestBody;
import com.webchannel.domain.User;
import com.webchannel.domain.UserResponse;
#Controller
#RequestMapping("/application/*")
public class SaveController {
#RequestMapping(value = "save", method = RequestMethod.POST, headers = {"content-type=application/json"})
public #ResponseBody UserResponse save(#RequestBody User user) throws Exception {
UserResponse userResponse = new UserResponse();
System.out.println("UserId :" + " " + user.getUserId());
return userResponse;
}
#RequestMapping(value = "delete", method = RequestMethod.GET)
public #ResponseBody UserResponse delete() {
System.out.println("Delete");
UserResponse userResponse = new UserResponse();
userResponse.setSuccess(true);
userResponse.setVersionNumber("1.0");
return userResponse;
}
}
When invoking /application/delete I get JSON returned. So I know my JacksonProcessor is configured correctly. The problem is in #RequestBody.
Where am I going wrong? Please help me.
This question is a bit hard to follow since there seems to be a few different problems.
But looking just at this problem:
In Tomcat I get the following error:
org.springframework.web.servlet.mvc.support.DefaultHandlerE xceptionResolver handleNoSuchRequestHandlingMethod WARNING: No matching handler method found for servlet request: path '/application/run', method 'POST', parameters map['name' -> array['myName']]
In the HTML you posted, you have a <form> that is set to POST to /application/run.
However, in your #Controller class, you do not have any method bound to this URL.
Because you've annotated the class with #RequestMapping("/run/*") and the method is annotated with #RequestMapping("save"), the save() method is actually bound to the URL /run/save - which is neither the URL you are sending data to with $.ajax() nor the URL the form is pointing at.
I would suggest turning up logging on the org.springframework.web loggers to DEBUG - when your app starts up Spring will log every URL that each method is mapped to.
I think you may need make couple of changes
Since your controller has #RequestMapping("/run/*"), you may need to change this to #RequestMapping("/run/") and in the jsp form action you may need to change <form id="myForm" action="/application/run/save" method="POST" accept="application/json" onclick="i()">, since you have defined #RequestMapping(value = "save", method = RequestMethod.POST, headers = {"content-type=application/json"}) for the 'save` method in the controller.
You may need to define the #RequestParam in the save method in controller like public #ResponseBody Response save(#RequestParam(required=true, value="name") String name, #RequestBody User user) throws Exception {...}
Since it clearly says that there is no handler attached to the request you are submitting.
Try the following
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$('#myForm').on('submit', function(e) {
e.preventDefault();
var frm = $("#myForm");
var dat = frm.serialize();
$.ajax({
type: 'POST',
url: $('#myForm').attr('action'),
data: dat,
contentType: 'application/json'
success: function(hxr) {
alert("Success: " + hxr);
}
});
});
</script>
</head>
<body>
<h2>Application</h2>
<form id="myForm" action="/application/run" method="POST">
<input type="text" name="name" value="myName">
<input type="submit" value="Submit">
</form>
The dataType:'json' is specifying what the format you are expecting from the server,
And it would be better to assist if you post your handler code.
There is no method in the controller mapped to your /application/run. I'm not sure which one you want to call, but to the url you have to add find orsave. Or create a method mapped to /application/run. Cheers!