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">
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";
}
}
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 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>
I have a java spring mvc webapp that builds a table of statuses making ajax calls to update ping status every 3 seconds and performance/health status every 5 min. It works correctly but the only thing is I added spring security and whenever a second user logs in from a different page it resets both views instead of just building the new view. How do I make it so each new user session has their own view to update without affecting the other open browser sessions?
Here's my jsp page:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%#page session="true" %>
<html>
<head>
<title>Site Connector</title>
<link rel="stylesheet" type="text/css" href="pages/styles/main.css">
<link rel="colorSchemeMapping" href="pages/styles/colorschememapping.xml">
<script type="text/javascript" src="pages/scripts/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
function updateReachability() {
$.ajax({
url: 'updatePing',
type: 'GET',
success: function(data) {
$('#site').html(data);
}
});
}
function updateStatus() {
$.ajax({
url: 'updateStatus',
type: 'GET',
success: function(data) {
$('#site').html(data);
}
});
}
document.addEventListener('DOMContentLoaded', function() {
updateStatus();
setInterval(updateStatus, 300000);
setInterval(updateReachability, 3000);
}, false);
</script>
</head>
<body lang=EN-US link=blue vlink=purple style='tab-interval:.5in'>
<div id="site">
<div id="upper_left">
<img src="pages/sickLogo.gif" alt="SICK Inc. logo"/>
<br />
<br />
<br />
</div>
<div id="upper_right">
<c:if test="${pageContext.request.userPrincipal.name != null}">
<c:url var="logoutUrl" value="/logout"/>
<form action="${logoutUrl}" method="post" id="logoutForm">
Logged in as: ${pageContext.request.userPrincipal.name} <input type="submit" value="logout" />
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
</c:if>
</div>
<h1>Site Connector</h1>
<table>
<tr>
<th>IP Address</th>
<th>Facility Name</th>
<th>URL</th>
<th>Health Status</th>
<th>Performance Status</th>
</tr>
<c:forEach items="${site.hubs}" var="hub">
<tr>
<td bgcolor="${hub.pingStatus}">${hub.ipAddress}</td>
<td>${hub.siteName}</td>
<td>${hub.url}</td>
<td bgcolor="${hub.healthStatus}"></td>
<td bgcolor="${hub.performanceStatus}"></td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
and here's my controller class:
#Controller
public class SiteController {
private static final Logger logger = Logger.getLogger(SiteController.class.getName());
private static String osName = System.getProperty("os.name");
private SiteManager manager = new SiteManager();
private SiteStatus site = new SiteStatus();
private ModelAndView model = new ModelAndView("SiteConnectorPage");
private boolean checkPing = true;
//method to run on initialization to build site list table from file
#RequestMapping("/connector")
public ModelAndView init() {
System.out.println("Connector method called");
//call method to create the list of error codes to search for
try
{
if(osName.matches("^.*Windows.*$"))
{
//change file location to C:/SVP/hub-connector/site-list/SiteList.csv
site = manager.buildSiteStatus("C:/p4_dominer/SiteConnector/SiteList.csv", site);
//set the ping status and URL's for each hub
if(!site.getHubs().isEmpty())
{
//set URL's for each hub and determines their reachability status
manager.buildURL(site.getHubs(), true);
}
else
{
logger.error("Site List is empty, please check contents of input file");//throw empty list exception
}
}
else //path to Linux location
{
site = manager.buildSiteStatus("/home/engineering/SVP/site-connector/site-list/SiteList.csv", site);
if(!site.getHubs().isEmpty())
{
//set URL's for each hub and determines their reachability status
manager.buildURL(site.getHubs(), false);
}
else
{
logger.error("Site List is empty, please check contents of input file");//throw empty list exception
}
}
}
catch (IOException e)
{
logger.error(e.getMessage());
}
model.addObject("site", site);
return model;
}
//method to update ping status
#RequestMapping(value = "/updatePing", method = RequestMethod.GET)
public ModelAndView updatePingStatus()
{
if(checkPing) {
try
{
if(osName.matches("^.*Windows.*$"))
{
System.out.println("updatePing method called");
//set URL's for each hub and determines their reachability status
manager.buildURL(site.getHubs(), true);
}
else
{
//set URL's for each hub and determines their reachability status
manager.buildURL(site.getHubs(), false);
}
}
catch (IOException e)
{
logger.error(e.getMessage());
}
}
return model;
}
#RequestMapping(value="/customLogin", method = RequestMethod.GET)
public ModelAndView loginPage(#RequestParam(value="error", required=false) String error,
#RequestParam(value="logout", required=false) String logout)
{
ModelAndView loginModel = new ModelAndView("customLogin");
if(error != null) {
loginModel.addObject("error", "Login was unsuccessful, Please Try Again.");
}
if(logout != null) {
loginModel.addObject("msg", "You've been logged out successfully.");
}
return loginModel;
}
#RequestMapping(value="/updateStatus", method = RequestMethod.GET)
public ModelAndView updateStatus()
{
System.out.println("updateStatus method called");
//set checkPing to false so updatePingStatus method doesn't update model concurrentlly which was causing the table to flash
checkPing = false;
if(osName.matches("^.*Windows.*$"))
{
/*test code */long startTime = System.nanoTime();
manager.getStatusData(site.getHubs(), site.getDeviceErrors(), true);
/*test code */long endTime = System.nanoTime();
/*test code */long duration = (endTime - startTime) / 1000000;
/*test code*/logger.info("updateStatus took " + duration + " ms");
}
else
{
manager.getStatusData(site.getHubs(), site.getDeviceErrors(), false);
}
checkPing = true;
return model;
}
}
Here's my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<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>
<dispatcher>ERROR</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<servlet>
<servlet-name>connector</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>connector</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/connector-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<welcome-file-list>
<welcome-file>customLogin.jsp</welcome-file>
</welcome-file-list>
</web-app>
And here's my servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd">
<context:component-scan base-package="com.sick.controller" />
<mvc:resources mapping="/pages/**" location="/pages/" />
<mvc:annotation-driven />
<beans:bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/pages/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<http pattern="/pages/**" security="none"/>
<http auto-config="true">
<intercept-url pattern="/login*" access="permitAll"/>
<intercept-url pattern="/customLogin*" access="permitAll"/>
<intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
<logout logout-success-url="/customLogin?logout" />
<form-login login-page="/customLogin" authentication-failure-url="/customLogin?error" default-target-url="/connector" />
<session-management><concurrency-control max-sessions="10" error-if-maximum-exceeded="true"/></session-management>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="admin" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
Finally came up with the answer after a lot of googling. I added sessioning to my controller class so that each client request was updating its own session object and not affecting other open browsers.
#RequestMapping("/connector")
public ModelAndView init(HttpServletRequest request) {
SiteManager manager = new SiteManager();
ModelAndView model = new ModelAndView("SiteConnectorPage");
SiteStatus siteStatus = new SiteStatus();
//create session if one doesn't exist
HttpSession session = request.getSession(true);
System.out.println("Connector method called");
try
{
if(osName.matches("^.*Windows.*$"))
{
siteStatus = manager.buildSiteStatus("C:/SICK/Site Connector/SiteList.csv");
//set the ping status and URL's for each hub
if(!siteStatus.getHubs().isEmpty())
{
//set URL's for each hub and determines their reachability status
manager.buildURL(siteStatus.getHubs(), true);
}
else
{
logger.error("Site List is empty, please check contents of input file");//throw empty list exception
}
}
else //path to Linux location
{
siteStatus = manager.buildSiteStatus("/home/engineering/SVP/site-connector/site-list/SiteList.csv");
if(!siteStatus.getHubs().isEmpty())
{
//set URL's for each hub and determines their reachability status
manager.buildURL(siteStatus.getHubs(), false);
}
else
{
logger.error("Site List is empty, please check contents of input file");//throw empty list exception
}
}
}
catch (IOException e)
{
logger.error(e.getMessage());
}
session.setAttribute("site", siteStatus);
model.addObject("site", siteStatus);
return model;
}
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!