I have a Controller and I want to get feedback to the user of what went wrong. The error callback is executed but the error message is not sent back to the client.
The JQuery call:
var validateButton = $('#validateSteps');
validateButton.bind('click', function() {
var stepsInput = $(':input').serializeArray();
$.postJSON('validate.htm', stepsInput, function(data) {
alert(data);
var steps = $('#steps');
var i = 0;
for(i=0;i<data.length;i++) {
steps.stepWidget('setValidationStatus', {testStepId: data[i].testStepId, interactionType: data[i].interactionType, validationStatus: data[i].validationStatus} );
steps.stepWidget('setErrorDescriptions', {testStepId: data[i].testStepId, interactionType: data[i].interactionType, errorDescriptions: data[i].errorDescriptions} );
}
return false;
}, {
error: function (XMLHttpRequest, textStatus, errorThrown, data) {
alert("error function");
alert(textStatus);
alert(errorThrown);
alert("Internal Server Error: " + data);
return false;
}
});
return false;
});
The Controller:
#RequestMapping(value = "validate.htm", method = RequestMethod.POST)
public #ResponseBody
List<ValidationBean> validateSteps(
#RequestBody List<Map<String, String>> testCaseInputs,
HttpServletResponse response) throws MalformedMessageException,
MalformedProfileException, XmlException, IOException,
MissingDependencyException, MessageValidationException {
List<ValidationBean> validations = new ArrayList<ValidationBean>();
...
return validations;
}
The Exception Handler in the Controller:
#ExceptionHandler(Exception.class)
public #ResponseBody
String handleException(Exception e, HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return e.getMessage();
}
What I want to show to the user is the String that should be returned by the handleException method. In the error callback the data parameter is undefined.
Related
I'm trying to execute my controller and get the return string to be used for my alert message, but my success function won't work. It executes the controller but does not execute the success function. The error executes but does not display any message.
BELOW IS THE AJAX
var jsonData = {
"appIDHidden": appname,
"txtypeHidden": txtype,
"ipaddress": ipaddress
};
$.ajax({
type: 'POST',
url: "checkaccesspermission",
data: jsonData,
dataType: 'json',
success: function(data) {
if(data != "exists"){
alert('Permission Already Exists!');
return false;
}else{
alert('Add Permission test Succesful!');
return true;
}
alert('test123');
},
error: function(jqXHR, textStatus, thrownError)
{
alert(thrownError+jsonData[1]);
},
async: false
});
BELOW IS THE CONTROLLER
#RequestMapping(value="/checkaccesspermission", method=RequestMethod.POST)
public String checkaccesspermission(#ModelAttribute("loginForm") IpAccessManagementModel loginForm, Model model,
HttpSession session, BindingResult result,HttpServletRequest request,
#RequestParam("ipaddress") String ipaddress,
#RequestParam("txtypeHidden") String txtype,
#RequestParam("appIDHidden") String appID) throws IOException{
System.out.println("CHECKACCESSPERMISSIONs");
IpAccessManagementModel sub = new IpAccessManagementModel();
sub.setAppName(appID);
sub.setTxtType(txtype);
sub.setIpAddress(ipaddress);
System.out.println(ipaddress);
ipAccessMGTDAO.addPermission(sub);
String resultCheckExist = ipAccessMGTDAO.checkAccessPermission(sub);
System.out.println("checkResult:|"+resultCheckExist+"|");
return resultCheckExist;
}
Nevermind, i got it to work by adding #public ResponseBody on my Controller :#RequestMapping(value="/checkaccesspermission", method=RequestMethod.POST)
public #ResponseBody
String checkaccesspermission
In my controller I am having if condition and two different response type. I will get response in JSON format from "if" condition, but I am getting response from else condition like unexpected '0 , instead I need to get my error message'.
My controller code snippet
#RequestMapping(value = "/saveuser", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.POST)
public ResponseEntity<?> addUser(#RequestBody TestUser user)
throws NotFoundException {
System.out.println(user.getAnswer().size());
if(questioncount == user.getAnswer().size())
{
return new ResponseEntity<TestUser>(service.addUser(user),
HttpStatus.OK);
}else {
String one="one";
String erromessage = "Only" + questioncount +" questions are allowed";
System.out.println(erromessage);
return new ResponseEntity<String>(erromessage,HttpStatus.NOT_ACCEPTABLE);
}
}
I have a rest controller:
#RestController
#RequestMapping("/query")
public class QueryController {
#Autowired
private QueryService queryService;
#RequestMapping(value = "/select", method = RequestMethod.POST)
public #ResponseBody QueryResultDTO executeQuery(#RequestBody QueryDTO queryDTO) {
try {
QueryResultDTO queryResultDTO = queryService.executeQuery("select * from employees");
queryResultDTO.setSuccessful(true);
return queryResultDTO;
} catch (SQLException e) {
QueryResultDTO queryResultDTO = new QueryResultDTO();
queryResultDTO.setSuccessful(false);
queryResultDTO.setErrorMessage(e.getMessage());
return queryResultDTO;
}
}
}
and I try to send POST request from AngularJS controller:
app.controller("AppCtrl",function($scope,$http) {
var app = this;
$scope.execute= function () {
$http({
url: '../query/select',
method: "POST",
data: { 'message' : $scope.queryText }
})
.then(function(response) {
$scope.queryResult = response.data;
console.log($scope.queryResult);
console.log($scope.queryText)
},
function(response) {
console.log(response);
});
}
});
but It doesn't work. My executeQuery function in Spring Controller isn't even called.
But when I change RequestMethod to GET it works correctly.
#RestController
#RequestMapping("/query")
public class QueryController {
#Autowired
private QueryService queryService;
#RequestMapping(value = "/select", method = RequestMethod.GET)
public #ResponseBody QueryResultDTO executeQuery() {
try {
QueryResultDTO queryResultDTO = queryService.executeQuery("INSERT INTO employee VALUES (7,'dupa')");
queryResultDTO.setSuccessful(true);
return queryResultDTO;
} catch (SQLException e) {
QueryResultDTO queryResultDTO = new QueryResultDTO();
queryResultDTO.setSuccessful(false);
queryResultDTO.setErrorMessage(e.getMessage());
return queryResultDTO;
}
}
}
and in Angular controller:
app.controller("AppCtrl",function($scope,$http) {
var app = this;
$scope.execute= function () {
$http({
url: '../query/select',
method: "GET",
data: { 'message' : $scope.queryText }
})
.then(function(response) {
$scope.queryResult = response.data;
console.log($scope.queryResult);
console.log($scope.queryText)
},
function(response) {
console.log(response);
});
}
});
My main problem is that I'd like to send some data to my Spring controller and then send JSON in response to my Angular controller. Whith GET method response works perfectly, but when I use POST the controller method isn't even called.
Edit:
My QueryDTO class is simple:
public class QueryDTO {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
And some logs with DEBUG level:
2016-06-06 09:28:23.697 DEBUG 7504 --- [nio-8090-exec-2] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2016-06-06 09:28:23.698 DEBUG 7504 --- [nio-8090-exec-2] o.s.web.servlet.DispatcherServlet : Successfully completed request
Try adding the consumes=MediaType.APPLICATION_JSON_VALUE in your method.
#Transactional
#RequestMapping(value = "/userlogincheck", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody void userLoginCheck(#RequestBody UserImpl user, HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException {
JSONObject json = new JSONObject();
try {
String email=user.getEmail();
Long userId=user.getId();
User loginData = accountService.userLoginCheck(email,userId);
if(loginData==null)
{
json.put("status", "FAILURE");
json.put("message", "user does not exist");
json.put("nextPage", "signIn");
}
else
{
json.put("status", "SUCCESS");
json.put("nextPage", updateState);
}
}
catch(Exception e) {
logger.info(e.getMessage());
}
response.setContentType("application/json;charset=UTF-8");
logger.info("response======" + json.toString());
PrintWriter out = response.getWriter();
out.write(json.toString());
}
I had the same issue and was able to fix it by adding CSRF token to my request (this is only an issue if you are using the WebSecurity). https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html
This link describe the following steps:
1) Add the token to your header, with thymeleaf you do as follows (I think you can fetch the token from cookie as well):
<head>
<meta name="_csrf" th:content="${_csrf.token}"/>
.....
</head>
2) Change your request to include the CSRF token as follows (I am not familiar with angular but I guess you can set the header the same way as I did with Jquery):
var token = $("meta[name='_csrf']").attr("content");
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(newTodo),
headers: {
'X-CSRF-TOKEN': token
},
contentType: 'application/json',
dataType: 'json',
success: function(){
alert('callback ');
}
});
I have built an application with Spring-boot and AngularJS with the REST End Point application. I got a little stuck with #RequesMapping in Spring Controller I've made. The problem is, I have the example url:
"localhost:8080/foo/bar/api/cardGenerated/0102".
'01' is first parameter and '02' is second parameter. How can I mapped into #RequestMapping Spring controller to get a url above.
Here's my controller :
#RestController
#RequestMapping("/api")
public class CardGeneratedResource {
#RequestMapping(value = "/cardGenerated/{branchCode}{cardType}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public ResponseEntity<CardGenerated> get(#PathVariable("branchCode") String branchCode,
#PathVariable("cardType") String cardType,
HttpServletResponse response) {
log.debug("REST request to get CardGenerated : " + branchCode + " and " + cardType);
CardGenerated cardGenerated = cardGeneratedRepository.
findTopByBranchCodeAndCardTypeOrderByCardNumberDesc(branchCode, cardType);
if (cardGenerated == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(cardGenerated, HttpStatus.OK);
}
}
so this is my AngularJS $resource:
'use strict';
angular.module('itmApp')
.factory('CardGenerated', function ($resource) {
return $resource('api/cardGenerated/:branchCode:cardType', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
}
});
});
I always got 'Failed to load resource: the server responded with a status of 404 (Not Found)'.
Here you are missing / .
You have two path variable here.so default url is
localhost:8080/foo/bar/api/cardGenerated/FIRST_PATH_VARIABLE/SECOND_PATH_VARIABLE
branchCode (First path variabel)
cardType (Second path variable)
#RequestMapping(value = "/cardGenerated/{branchCode}/{cardType}"
And in frontend side too the same mistake while registering factory definition.
api/cardGenerated/:branchCode/:cardType'
All method is like
#RestController
#RequestMapping("/api")
public class CardGeneratedResource {
#RequestMapping(value = "/cardGenerated/{branchCode}/{cardType}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public ResponseEntity<CardGenerated> get(#PathVariable("branchCode") String branchCode,
#PathVariable("cardType") String cardType,
HttpServletResponse response) {
log.debug("REST request to get CardGenerated : " + branchCode + " and " + cardType);
CardGenerated cardGenerated = cardGeneratedRepository.
findTopByBranchCodeAndCardTypeOrderByCardNumberDesc(branchCode, cardType);
if (cardGenerated == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(cardGenerated, HttpStatus.OK);
}
}
and angular factory is like
'use strict';
angular.module('itmApp')
.factory('CardGenerated', function ($resource) {
return $resource('api/cardGenerated/:branchCode/:cardType', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
}
});
});
NOTE: First try with any rest client or postman and make sure backend api is working properly also angular side check parameters are being passed correctly.
i am trying to get response from servlet page and displaying alert on success. but its show me error always. i am not able to figure it out.
My ajax code:
$(document).ready(function() {
$("#srch").click(function() {
var txt1 = $("#store-qsearch").val();
alert(txt1)
$.ajax({
url : 'http://localhost:8080/searchengine/SearchDataServlet',
data : 'val='+txt1,
type : 'GET',
success : function(response) {
alert("Success");
// create an empty div in your page with some id
},
error: function(){ alert("error");
}
});
});
});
My servlet code:
public class SerachDataServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String searchkey = request.getParameter("val").toString();
SearchInput searchinput = new SearchInput();
searchinput.searchkeys = searchkey;
System.out.println(searchkey);
SearchParser searchparser = new SearchParser();
searchparser.searchData(searchkey);
PrintWriter output = response.getWriter();
output.println("successs");
}
}
change this line data : 'val='+txt1, to data: { val: txt1},
see this for example