JSON data to a Spring MVC controller - error 415 - java

I have a problem with my application. When I send JSON data I get return error 415 - The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
I am new in this and I still trying understanding this.
JSP page:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
jQuery(document).ready(function() {
$("#form-temp").submit(function(event) {
event.preventDefault();
searchViaAjax();
});
});
function searchViaAjax() {
var temp = {}
temp["temp"] = $("#temp").val();
$.ajax({
type : "POST",
contentType : "application/json",
url : "/update",
data : JSON.stringify(temp),
dataType : 'json',
cache: false,
timeout: 600000,
success : function(temp) {
console.log("SUCCESS: ", data);
//display(temp);
}
});
}
/* function display(temp) {
var json = "<h4>Ajax Response</h4><pre>"+ JSON.stringify(data, null, 4) + "</pre>";
$('#feedback').html(json);
} */
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Formularz wprowadzania temperatury</title>
</head>
<body>
<form id="form" method="post" action="update" id="form-temp">
<div><label for="temp">Podaj temperaturÄ™</label></div>
<div><input type="text" name="temp" id="temp"/></div>
<div><button id="sendBtn">Dodaj</button></div>
</form>
<form id="form" method="get" action="stats">
<div><button id="sendBtn">Lista temperatur</button></div>
</form>
</body>
</html>
Controller:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import pl.e.rekrutacja.domain.repository.TempRepository;
import pl.e.rekrutacja.model.Temp;
#RestController
public class UpdateController {
#Autowired
private TempRepository tempRepository;
// #ResponseBody
#RequestMapping(value = "/update", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public String startPage(#RequestBody Temp temp){
tempRepository.addTemp(temp);
return "input_form_temp";
}
}
Model class:
public class Temp {
private double value;
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public Temp(double value) {
super();
this.value = value;
}
}
Application context:
<?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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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">
<mvc:annotation-driven enable-matrix-variables="true"/>
<context:component-scan base-package="pl.e.rekrutacja" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id= "tempRepositoryImpl" class="pl.e.rekrutacja.domain.repository.impl.TempRepositoryImpl"/>
</beans>
web.xml:
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<filter>
<filter-name>encoding-filter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding-filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/webcontext/DispatcherServlet-context.xml
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

Your controller is returning a view name to the requested resource. Instead it must return the state of the Temp object in JSON format.
#RequestMapping(value = "/update", method = RequestMethod.POST)
public #ResponseBody Temp tempStartPage(#PathVariable(#RequestBody Temp temp)) {
return tempRepository.addTemp(temp);
}
The #ResponseBody will handle the consumes = "application/json", produces = "application/json" .

Related

Spring web application.Unable to view the view page

Getting the following error in my console
printing ra
Dec 19, 2020 2:19:52 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping for GET /FirstSpringWebExample/WEB-INF/hello.html
My files are as below,
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/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>FirstSpringWebExample</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.sri.controller" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/" />
<property name = "suffix" value = ".html" />
</bean>
</beans>
HelloController.java
package com.sri.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class HelloController {
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
System.out.println("printing");
return "hello";
}
#RequestMapping(value = "/hellot", method = RequestMethod.GET)
public String printHellos(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
System.out.println("printing ra");
return "hello";
}
}
hello.html
<html>
<head>
<title>Hello Spring MVC</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
Here in above code.Controller is working fine but view is not working.Here it is getting as requested resource not available.
I have changed the html extension to jsp extension.Now it is working (Dont know why InternalViewResolver cant render html page)

Spring Security 3.1.3 Issues

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";
}
}

redirected page is not being displayed with spring-mvc ajax request

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');
}
});
}

Spring +AngularJs + Tomcat 9.0 - 403 error when sending a PUT request

I am getting the following error when I click on 'Add To Cart'.
PUT http://localhost:8080/emusicstore/rest/cart/add/97 403 ()
viewProduct.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#include file="/WEB-INF/views/template/header.jsp" %>
<div class="container-wrapper">
<div class="container">
<div class="page-header">
<h1>Product Detail</h1>
<p class="lead">Here is the detail information of the product!</p>
</div>
<div class="container" ng-app = "cartApp">
<div class="row">
<div class="col-md-5">
<img src="<c:url value="/resources/images/${product.productId}.png" /> " alt="image"
style="width:100%"/>
</div>
<div class="col-md-5">
<h3>${product.productName}</h3>
<p>${product.productDescription}</p>
<p>
<strong>Manufacturer</strong> : ${product.productManufacturer}
</p>
<p>
<strong>Category</strong> : ${product.productCategory}
</p>
<p>
<strong>Condition</strong> : ${product.productCondition}
</p>
<h4>${product.productPrice} USD</h4>
<br>
<c:set var="role" scope="page" value="${param.role}" />
<c:set var="url" scope="page" value="/productList" />
<c:if test="${role='admin'}">
<c:set var="url" scope="page" value="/admin/productInventory" />
</c:if>
<p ng-controller="cartCtrl">
Back
<a href="#" class="btn btn-warning btn-large"
ng-click="addToCart('${product.productId}')"><span
class="glyphicon glyphicon-shopping-cart"></span>Add To Cart</a>
<span class="glyphicon glyphicon-hand-right"></span>View Cart
</p>
</div>
</div>
</div>
<script src="<c:url value="/resources/js/controller.js" /> "></script>
controller.js
var cartApp = angular.module ("cartApp", []);
cartApp.controller("cartCtrl", function ($scope, $http){
$scope.refreshCart = function (cartId) {
$http.get('/emusicstore/rest/cart/'+$scope.cartId).success(function (data) {
$scope.cart=data;
});
};
$scope.clearCart = function () {
$http.delete('/emusicstore/rest/cart/'+$scope.cartId).success($scope.refreshCart($scope.cartId));
};
$scope.initCartId = function (cartId) {
$scope.cartId = cartId;
$scope.refreshCart(cartId);
};
$scope.addToCart = function (productId) {
$http.put('/emusicstore/rest/cart/add/'+productId).success(function (data) {
$scope.refreshCart($http.get('/emusicstore/rest/cart/cartId'));
alert("Product successfully added to the cart!")
});
};
$scope.removeFromCart = function (productId) {
$http.put('/emusicstore/rest/cart/remove/'+productId).success(function (data) {
$scope.refreshCart($http.get('/emusicstore/rest/cart/cartId'));
});
};
});
CartController.java
package com.store.emusicstore.controller;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
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.ResponseStatus;
import com.store.emusicstore.dao.CartDao;
import com.store.emusicstore.dao.ProductDao;
import com.store.emusicstore.model.Cart;
import com.store.emusicstore.model.CartItem;
import com.store.emusicstore.model.Product;
#Controller
#RequestMapping("/rest/cart")
public class CartController {
#Autowired
private CartDao cartDao;
#Autowired
private ProductDao productDao;
#RequestMapping(value="/{cartId}" , method = RequestMethod.GET)
public #ResponseBody Cart read(#PathVariable(value ="cartId") String cartId){
return cartDao.read(cartId);
}
#RequestMapping(value="/{cartId}", method = RequestMethod.PUT)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void update(#PathVariable(value = "cartId" ) String cartId, #RequestBody Cart cart) {
cartDao.update(cartId, cart);
}
#RequestMapping(value = "/{cartId}", method = RequestMethod.DELETE)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void delete(#PathVariable(value="cartId") String cartId) {
cartDao.delete(cartId);
}
#RequestMapping(value="/add/{productId}", method = RequestMethod.PUT)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void addItem(#PathVariable (value = "productId") String productId, HttpServletRequest request) {
System.out.println("Inside addItem()");
String sessionId = request.getSession(true).getId();
Cart cart = cartDao.read(sessionId);
if(cart == null) {
cart = cartDao.create(new Cart(sessionId));
}
Product product = productDao.getProductById(Long.valueOf(productId));
if (product == null) {
throw new IllegalArgumentException(new Exception());
}
cart.addCartItem(new CartItem(product));
cartDao.update(sessionId, cart);
}
#RequestMapping(value="/remove/{productId}", method=RequestMethod.PUT)
#ResponseStatus(value=HttpStatus.NO_CONTENT)
public void removeItem(#PathVariable Long productId, HttpServletRequest request) {
String sessionId = request.getSession(true).getId();
Cart cart = cartDao.read(sessionId);
Product product = productDao.getProductById(productId);
if (product == null || cart == null) {
throw new IllegalArgumentException(new Exception());
}
cart.removeCartItem(new CartItem(product));
cartDao.update(sessionId, cart);
}
#ExceptionHandler(IllegalArgumentException.class)
#ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Illegal request, please verify your payload")
public void handleClientErrors(Exception e){}
#ExceptionHandler(Exception.class)
#ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Internal Server")
public void handleServerErrors(Exception e){}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<display-name>springMultipartFilter</display-name>
<filter-name>springMultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>springMultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<display-name>springMultipartFilter</display-name>
<filter-name>springMultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>springMultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
Things I have tried inorder to resolve this but DID NOT WORK :
Set 'readonly' as false in tomcat's web.xml
Disabled csrf by adding
security:csrf disabled="true"
in root-context inside security:http tag.
Added CorsFilter
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type,X-Requested-With,accept,authorization,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET, POST, PUT, DELETE, OPTIONS, HEAD</param-value>
I am still not able to get rid of the 403 error when it sends the put request.
I don't know if that is the problem, but just from reading your code:
in your js:
$scope.addToCart = function (productId) {
$http.put('/emusicstore/rest/cart/add/'+productId).success(function (data) {
$scope.refreshCart($http.get('/emusicstore/rest/cart/cartId'));
alert("Product successfully added to the cart!")
});};
and in your java:
#RequestMapping(value="/add/{productId}", method = RequestMethod.PUT)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void addItem(#PathVariable (value = "productId") String productId, HttpServletRequest request) {
System.out.println("Inside addItem()");
String sessionId = request.getSession(true).getId();
Cart cart = cartDao.read(sessionId);
if(cart == null) {
cart = cartDao.create(new Cart(sessionId));
}
Product product = productDao.getProductById(Long.valueOf(productId));
if (product == null) {
throw new IllegalArgumentException(new Exception());
}
cart.addCartItem(new CartItem(product));
cartDao.update(sessionId, cart);
}
you're java returns no data in the response, but in the js your function expects the data.
note that 403 is usually bad mapping or security issues.

Getting java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute [duplicate]

This question already has answers here:
What causes "java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute"?
(7 answers)
Closed 6 years ago.
Getting java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute error in spring 3.0. How can I resolve it?
Below is the code for the files
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form handling</title>
</head>
<body>
<form:form action="/emp/showEmployee" method="POST">
<table>
<tbody>
<tr><td>Employee Name: </td><td><form:input path="empName"/></td></tr>
<tr><td>Employee Skill: </td><td><form:input path="empSkill"/></td></tr>
<tr><td><input type="submit" value = "Submit"></td></tr>
</tbody>
</table>
</form:form>
</body>
</html>
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!-- Processes application requests -->
<servlet>
<servlet-name>emp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>emp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/WEB-INF/views/index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/context-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
context-config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
EmployeeController.java
package com.springmvctut.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.springmvctut.bean.EmployeeForm;
#Controller
public class EmployeeController {
#RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView employee() {
return new ModelAndView("employeeForm", "command", new EmployeeForm());
}
#RequestMapping(value = "/showEmployee", method = RequestMethod.POST)
public String showEmployee(#ModelAttribute("SpringWeb")EmployeeForm employeeForm, ModelMap modelMap){
modelMap.addAttribute("name", employeeForm.getEmpName());
modelMap.addAttribute("skill", employeeForm.getEmpSkill());
return "employeedetails";
}
}
EmployeeForm.java(Bean class)
package com.springmvctut.bean;
public class EmployeeForm {
private String empName;
private String empSkill;
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpSkill() {
return empSkill;
}
public void setEmpSkill(String empSkill) {
this.empSkill = empSkill;
}
public String toString(){
return "Employee name-"+empName+" Employee Skill-"+empSkill;
}
}
add this to your form element :
<form:form action="/emp/showEmployee" method="POST" modelAttribute="employee">
update your controller
#ModelAttribute
public void addEmplployeeTomModel(Model model){
model.addAttribute("employee",new EmployeeForm())
}
#RequestMapping(value = "/showEmployee", method = RequestMethod.POST)
public String showEmployee(#ModelAttribute("employee")EmployeeForm employeeForm, ModelMap modelMap){
modelMap.addAttribute("name", employeeForm.getEmpName());
modelMap.addAttribute("skill", employeeForm.getEmpSkill());
return "employeedetails";
}

Categories

Resources