AWS lambda/api gateway does not redirect - java

I have a very simple spring route that im attempting to run on aws lambda. The route simply returns the text/string "redirect:/upload" instead of redirecting. I have the html file in the /resources/templates folder.
#RequestMapping(path = "/test", method = RequestMethod.POST)
public String UploadPage2() {
return "redirect:/upload";
}

I think the problem is from the return type of method: String.
You can do:
public RedirectView UploadPage2() {
return new RedirectView("/upload");
}
Second question
To return an view on path /test with GET request, you need another method with same path but different method
#RequestMapping(path = "/test", method = RequestMethod.GET)
public ModelAndView testGet(){
return new ModelAndView("uploadview");
}

Related

how to achieve Dynamic URL in REST WebService

I am trying to develop new web service for my application.
For that I am using Spring REST-webservice.
In the controller end, I am trying to fetch the list of records based on the agent passed.Now the requirement , the agent can be passed or it can be null.In case of null agent all records should be selected.else only those records to be fetched.
Tried using below code for achieving dynamism., as per one of the search result however it is not working.
#RequestMapping(value = "/staging/{agentCode: [^/]*?}" , method =
RequestMethod.GET)
Here is my existing code:
#Controller
#RequestMapping(value="/batches")
public class BatchController {
#SuppressWarnings({ "rawtypes" })
#RequestMapping(value="/staging/{agentCode}", method =
RequestMethod.GET)
#ResponseBody
public ResponseEntity IntmBatch(#PathVariable("agentCode") String
agentCode)
{
//code here
}
CASE 1:when I use URL like .,
www.example.com/myapplication/batches/staging/1234
it works fine and desired result is fetched.
CASE 2:However in case I am not passing any parameter say.,
www.example.com/myapplication/batches/staging/
where in , I am not passing any parameter., it says me mapping not found.
Can you please let me know how to achieve this dynamic URL in REST GET Request Method Call.
Thanks in advance!!
Instead of using #Pathvariable you can use #RequestParam for optional values in URL.
So your URL will be like.
CASE 1 : www.example.com/myapplication/batches/staging?agentCode=1234 &
CASE 2 : www.example.com/myapplication/batches/staging
Hope it will work solve your issue.
#SuppressWarnings({ "rawtypes" })
#RequestMapping(value="/staging", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity IntmBatch(#RequestParam(name="agentCode",required=false) String agentCode)
{
//code here
}
create one more method in controller with #RequestMapping(value = "/staging", method = RequestMethod.GET) as follows.
#RequestMapping(value = "/staging", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity returnAll() {
System.out.println("returning all ");
// code here
return null;
}

Java - Pass multiple parameters to ajax post

I have this simple controller from ajax request. It works but I wanted to return many stuff, not only List TestFlow.getFlow(flowName);
#RequestMapping(value = "/execute-flow/getFlow" , method = RequestMethod.POST)
public #ResponseBody List<String> getFlow(#RequestParam("flowName") String flowName) {
return TestFlow.getFlow(flowName);
}
Can I return multiple things to the ajax post?
For example:
#RequestMapping(value = "/execute-flow/getFlow" , method = RequestMethod.POST)
public #ResponseBody List<String> getFlow(#RequestParam("flowName") String flowName) {
return TestFlow.getFlow(flowName);
return TestFlow.getInputs(flowName);
return TestFlow.getCode(flowName);
}
Not sure what exactly you're after, but
return Arrays.asList(
TestFlow.getFlow(flowName),
TestFlow.getInputs(flowName),
TestFlow.getCode(flowName));
should work, provided that all of these are of the same type (String).

.getJSON 404 Error with ModelAndView

I am trying to retrieve some JSON data in my javascript by making a call to the controller. The controller returns a MappingJacksonJsonView ModelandView, but the .getJSON is always reporting a 404 at .../handhygiene.json.
Is there a problem with the way I am returning the ModelandView from the controller?
Controller
#RequestMapping(value = "/{room}/handhygiene.json", method = RequestMethod.GET)
public ModelAndView getHandHygienePageAsync(
#PathVariable(value = "room") String roomCode) {
ModelAndView mav = new ModelAndView(new MappingJacksonJsonView());
mav.getModelMap().addAttribute(blahblahblah); //adds some attributes
...
return mav;
}
Javascript
var currentURL = window.location;
$.getJSON(currentURL + ".json",
function(data) {
... //does stuff with data
}
If you're trying to get only an JSON object from Ajax request, you need to add #ResponseBody to your method, and make you result object as return from your method.
The #ResponseBody tells to Spring that he need to serialize your object to return to the client as content-type. By default, Spring uses JSON Serialization. ModelAndView will try to return an .JSP page. Maybe you don't have this jsp page on your resources so, the server return 404 error.
I Think this code should work for you:
#RequestMapping(value = "/{room}/handhygiene.json", method = RequestMethod.GET)
public #ResponseBody Room getHandHygienePageAsync(#PathVariable(value = "room") String roomCode) {
Room room = myService.findRoomByRoomCode(roomCode);
return room;
}
I'm assuming you're using the Room as your result object, but it may be another object or ArrayList, for example.
You cant take a look here for Spring example, and here for example and configuration.

spring mvc - How to retrieve values from controller without creating a view

I have a problem here and I need your help.
Im trying to retrieve an integer value from the controller to the jsp.
In my jsp I have an ajax call:
$("#hdnCustomerSize").load(contextPath+"/customer/size", function() {
// some codes
});
In my controller:
#RequestMapping(method = RequestMethod.GET, value="/size")
public void getCustomerSize(Model model) {
model.addAttribute("customerSize", customerService.getCustomers().size());
}
My problem is Im getting an exception:
javax.servlet.ServletException: Could not resolve view with name 'customer/size' in servlet with name 'tombuyandsell'.
I know Im getting this exception because I intentionally did not map this in views.properties. The reason is I only want to get the integer value size and not a whole jsp page. Please help.
Use the #ResponseBody annotation and return the int as a String. #ResponseBody will cause the return type to be written to the response HTTP body.
#RequestMapping(method = RequestMethod.GET, value="/size")
#ResponseBody
public String getGroupChatSize(Model model) {
return Integer.toString(customerService.getCustomers().size());
}
Documentation
Try with #ResponseBody:
#ResponseBody
#RequestMapping(method = RequestMethod.GET, value="/size")
public int getGroupChatSize() {
return customerService.getCustomers().size();
}

Can #PathVariable return null if it's not found?

Is it possible to make the #PathVariable to return null if the path variable is not in the url? Otherwise I need to make two handlers. One for /simple and another for /simple/{game}, but both do the same just if there is no game defined i pick first one from a list however if there is a game param defined then i use it.
#RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
public ModelAndView gameHandler(#PathVariable("example") String example,
HttpServletRequest request) {
And this is what I get when trying to open page /simple:
Caused by: java.lang.IllegalStateException: Could not find #PathVariable [example] in #RequestMapping
They cannot be optional, no. If you need that, you need two methods to handle them.
This reflects the nature of path variables - it doesn't really make sense for them to be null. REST-style URLs always need the full URL path. If you have an optional component, consider making it a request parameter instead (i.e. using #RequestParam). This is much better suited to optional arguments.
As others have already mentioned No you cannot expect them to be null when you have explicitly mentioned the path parameters. However you can do something like below as a workaround -
#RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
public ModelAndView gameHandler(#PathVariable Map<String, String> pathVariablesMap,
HttpServletRequest request) {
if (pathVariablesMap.containsKey("game")) {
//corresponds to path "/simple/{game}"
} else {
//corresponds to path "/simple"
}
}
If you are using Spring 4.1 and Java 8 you can use java.util.Optional which is supported in #RequestParam, #PathVariable, #RequestHeader and #MatrixVariable in Spring MVC
#RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
public ModelAndView gameHandler(#PathVariable Optional<String> game,
HttpServletRequest request) {
if (game.isPresent()) {
//game.get()
//corresponds to path "/simple/{game}"
} else {
//corresponds to path "/simple"
}
}
You could always just do this:
#RequestMapping(value = "/simple", method = RequestMethod.GET)
public ModelAndView gameHandler(HttpServletRequest request) {
gameHandler2(null, request)
}
#RequestMapping(value = "/simple/{game}", method = RequestMethod.GET)
public ModelAndView gameHandler2(#PathVariable("game") String game,
HttpServletRequest request) {
#RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
public ModelAndView gameHandler(#PathVariable(value="example",required = false) final String example)
Try this approach, it worked for me.
I just tested this just now, but by combining the above solution i got this:
#RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
public ModelAndView gameHandler(#PathVariable(value = "game", required = false) String example,
HttpServletRequest request) {
if (example != null) {
//...
} else {
//pick first, ...
}
}
Now when you use "/simple", String example will be null instead of throwing Exception.
Short solution, no fancy Optional<> or Map<>
We can write multiple methods in controllers with explicit mapping with the path variable combination to exclude the optional variables (if using old version of Spring)
In my scenario wanted to develop an API to get recycle value for old device where parameters could be brand, model and network however network is an option one.
One option to handle this was use network as a request parameter instead of pathVariable.
for e.g. /value/LG/g3?network=vodafone however I didn't like this approach.
for me the more cleaner one was to use below
/refurbValue/LG/g3
/refurbValue/LG/g3/vodafone
#RequestMapping(value = "/refurbValue/{make}/{model}/{network}", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
#ResponseBody
def getRefurbValueByMakeAndModelAndNetwork(#PathVariable String make, #PathVariable String model, #PathVariable String network ) throws Exception {
//logic here
}
#RequestMapping(value = "/refurbValue/{make}/{model}", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
#ResponseBody
def getRefurbValueByMakeAndModel(#PathVariable String make, #PathVariable String model) throws Exception {
//logic here
}
In the above example, both controller can use the same service method and handling of the parameter can be done. In my case I was using Groovy so it was easy to use with optional parameter like
Map getRefurbValue(String brand, String model, String network="")

Categories