Have written a spring controller Get method and trying to call that with postman but getting error
Could not get any response
There was an error connecting to https://localhost:8081/MyPortal/shared?video0=14&video1=15.
Even when I try to debug, the call is not going to the controller method. Not sure what is happening.
Here is the controller code:
#Controller
public class SharedLinkController {
#Autowired
VideoService videoService;
#RequestMapping("/shared")
public ModelAndView getSharedVideo(HttpServletRequest request, HttpServletResponse response,
#RequestParam(value="video0", required=false) Long video0,
#RequestParam(value="video1", required=false) Long video1,
#RequestParam(value="video2", required=false) Long video2,
#RequestParam(value="video3", required=false) Long video3){
List<Lab> videos = new ArrayList<Lab>();
// some processing with video0, video1 etc....
ModelAndView model = new ModelAndView("index");
model.addObject("videos", videos);
return model;
}
}
And this is how am trying to call the API:
https://localhost:8081/MyPortal/shared?video0=14&video1=15
Am not trying to make it a RestController as I need to redirect the call to a webpage. Is there anything wrong with the code?
Please suggest.
Do you have a class that scans basepackages and registers your controller as a bean, like the following?
#SpringBootApplication(scanBasePackages= "se.yourpackage.src")
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
Nevermind the RestController, but you need to add the requestmapping
#RequestMapping("/MyPortal")
public class SharedLinkController {
You might also need to add the path of the view files in your file called
application.properties
for example:
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
I suggest to check your url and your view name.
You try to connect url : connecting to http://localhost:8081/yourPortal/shared?video0=14&video1=15
#Controller
public class SharedLinkController {
#Autowired
VideoService videoService;
#RequestMapping("/shared")
public ModelAndView getSharedVideo(ModelAndView mav,
#RequestParam(value="video0", required=false) Long video0,
#RequestParam(value="video1", required=false) Long video1,
#RequestParam(value="video2", required=false) Long video2,
#RequestParam(value="video3", required=false) Long video3){
List<Lab> videos = new ArrayList<Lab>();
// ...
mav.addObject("videos", videos);
mav.setViewName("index");
return mav;
}
}
You need to set the context to youe spring boot application,
try setting
server.context-path=/MyPortal
This way you can define the root context to your application as
http:localhost:8081/MyPortal/
Related
With AngularJS, I knew that Spring Boot can use model.attribute to return many objects or list object same below:
#Controller
public class TestController {
private Logger logger = LoggerFactory.getLogger(getClass());
#RequestMapping(value="/hello")
public String home(HttpServletRequest httpRequest, Model model) {
model.addAttribute("Authorization", "test string");
return "/index";
}
}
But don't know how to make the same in Spring Boot and Angular 8???
Spring Boot + Angular 8 and Spring Boot + AngularJS are the same?
Anyone can help me??? Thank you?
When you using angular then you get JSON response when to do HTTP request so please try this,
and Also add Cross Origin at your rest controller to communication between cross-server
#RestController
public class TestController {
private Logger logger = LoggerFactory.getLogger(getClass());
#RequestMapping(value="/hello")
public PayloadRespons home(HttpServletRequest httpRequest, Model model) {
PayloadRespons payload = new PayloadRespons();
payload.setAuthorization = "test string"
// model.addAttribute("Authorization", "test string");
return payload;
}
}
class PayloadRespons{
private String Authorization;
.... some more which you have
.... Getter and Settter
}
I use Spring Data Rest and I can not understand why my RepositoryRestController does not work. Its code:
#RepositoryRestController
public class Cntrl {
#Autowired
private UserDao userDao;
#RequestMapping(name = "/users/{id}/nameOne",method =
RequestMethod.GET)
#ResponseBody
public PersistentEntityResource setNameOne(#PathVariable("id") Long id, PersistentEntityResourceAssembler persistentEntityResourceAssembler){
User user = userDao.findById(id).orElseThrow(()->{
throw new ServerException("Wrong id");
});
user.setLogin("One");
userDao.save(user);
return persistentEntityResourceAssembler.toFullResource(user);
}
}
And Spring Boot start class:
#SpringBootApplication
#EnableWebMvc
#EnableScheduling
#EnableJpaRepositories
#EnableSpringDataWebSupport
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
When i go to base path (localhost:8080/api) everything is fine, but when send GET to request to localhost:8080/api/users/1/nameOne I get empty response, i dont have other controllers and I have user with id 1, so why it is not working ?
It doesn't work because the URL structure you are using has already a meaning in Spring Data Rest context.
/{repository}/{id}/{column} URL is handled at RepositoryPropertyReferenceController.followPropertyReference method.
/api/users/1/nameOne means: get the nameOne column of the user with the id of 1. An important note is that: this column should reference another #Entity. This means if you have a String column named "surname" and you hit the URL /api/users/1/name you will get 404 because this column is not referencing another entity. If you have a column named school which references to a School entity and you hit the URL /api/users/1/school you will get the referenced school entity for that user. If the user does not have a school then you will get 404 again.
Also, #RepositoryRestController can be used for #RequestMapping if the URL you are giving isn't colliding with Spring Data Rest.
You can test that with the following example:
#RepositoryRestController
public class CustomRepositoryRestController {
#RequestMapping(path = "/repositoryRestControllerTest", method = RequestMethod.GET)
#ResponseBody
public String nameOne() {
return "test";
}
}
Visit http://localhost:8080/repositoryRestControllerTest
I hope this explanation clarifies things for you.
If localhost:8080/api is your root context, then localhost:8080/api/users/1/nameOne should be the url you are using for the user GET.
I am writing a Spring Boot application. I have written a simple controller that gets invoked whenever the endpoint is hit, but it still returns status 404 and not the specified return value.
HelloController
#Controller
public class MessageRequestController {
#RequestMapping(method = RequestMethod.GET, value = "/hello", produces = "application/json")
public String hello() {
System.out.println("Hit me!");
return "Hello, you!";
}
}
Now whenever I call localhost:8080/hello, I see the console log "Hit me!", but "Hello, you!" is never returned. Postman outputs:
{
"timestamp": 1516953147719,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/hello"
}
Application.java
#SpringBootApplication
#ComponentScan({"com.sergialmar.wschat"}) // this is the root package of everything
#EntityScan("com.sergialmar.wschat")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Change your method return a ResponseEntity<T>
#RequestMapping(method = RequestMethod.GET, value = "/hello", produces = "application/json")
public ResponseEntity<String> hello() {
System.out.println("Hit me!");
return new ResponseEntity<String>("Hello, you!", HttpStatus.OK);
}
or change the controller to RestController
#RestController
public class MessageRequestController {...}
CURL
ubuntu:~$ curl -X GET localhost:8080/hello
Hello, you!
Short version:
Annotate your endpoint method with ResponseBody to bind the return value to the response body.
#Controller
public class MessageRequestController {
#RequestMapping(method = RequestMethod.GET, value = "/hello", produces = "application/json")
#ResponseBody
public String hello() {
System.out.println("Hit me!");
return "Hello, you!";
}
}
You can instead annotate your class with RestController instead of Controller to apply ResponseBody to each method of the class.
#RestController
public class MessageRequestController {
#RequestMapping(method = RequestMethod.GET, value = "/hello", produces = "application/json")
public String hello() {
System.out.println("Hit me!");
return "Hello, you!";
}
}
With #Controller, you use the default model-view from Spring Web MVC, and you're actually telling spring to render the view called Hello, you!.tml from your resources directory (src/main/resources/templates for a Spring Boot project, if I remember correctly).
You can read this article for more information about the Spring MVC REST Workflow.
Once you're more familiar with those concepts, you can even further customize your endpoint method using ResponseEntity.
As you see the "hit me", there's no mapping issue, but in your #RequestMapping annotation you specifie a produce type to "application/json" and you return a simple poor String not formatted and without any header('Content-Type: application/json').
Add the header and format the outpout.
When everything seems ok but receive 404, check this answer:
As you know:
In the Spring MVC you can return view as a String or ModelAndView object.
IMPORTANT NOTE:
In both cases you have to pay attention to relative/absolute path:
If you declare / in the beginning of the view name, you are using absolute path.
Namely it does not matter class level #RequestMapping and directly introduce itself as the final view name.
If you do not declare / in the beginning of the view name, you are using relative path (relative to the class path) and therefore it appends to the class level #RequestMapping to construct final view name.
So, you have to consider the above notes when use the Spring MVC.
Example:
1. create two HTML file test1.html and test2.html in the static folder of spring (boot) structure:
Please note that the class level #RequestMapping behaves as a folder path in the case of relative path.
--- resources
--- static
--- classLevelPath //behaves as a folder when we use relative path scenario in view names
--- test2.html //this will be used for relative path [case (2)]
--- test1.html //this will be used for absolute path [case (1)]
create a controller class like as the below. This example shows different cases with return String and ModelAndView in both relative and absolute path.
#Controller
#RequestMapping("/classLevelPath")
public class TestController {
//case(1)
#RequestMapping("/methodLevelAbsolutePath1")
public String absolutePath1(Model model){
//model.addAttribute();
//...
return "/test1.html";
}
//case(1)
#RequestMapping("/methodLevelAbsolutePath2")
public ModelAndView absolutePath2(Model model){
ModelAndView modelAndView = new ModelAndView("/test1.html");
//modelAndView.addObject()
//....
return modelAndView;
}
//case(2)
#RequestMapping("/methodLevelRelativePath1")
public String relativePath1(Model model){
//model.addAttribute();
//...
return "test2.html";
}
//case(2)
#RequestMapping("/methodLevelRelativePath2")
public ModelAndView relativePath2(Model model){
ModelAndView modelAndView = new ModelAndView("test2.html");
//modelAndView.addObject()
//....
return modelAndView;
}
}
Note:
You can specify the suffix of your view files by a ViewResolver (for example InternalResourceViewResolver or spring.mvc.view.suffix=.html in the appliction.properties file of Spring Boot and do not declare .html suffix in the above code.
Best Regard
I'm using Spring MVC as a rest controller and I've integrated Swagger-ui with my controller using Springfox. I'd like to have a method that is able to upload a file via the Swagger-ui interface. I only need two parameters, a long acting for an object id and the file to be uploaded.
#RestController
public class controller{
#RequestMapping(value="/upload", method=RequestMethod.POST)
public void uploadFile(#RequestParam Long id,
#RequestParam MultipartFile file){
//do some stuff
}
}
I've tried almost everything and I can't get a file upload button to appear. However, if I do:
#RestController
public class Controller{
#RequestMapping(value="/upload", method=RequestMethod.POST)
public void uploadFile(#RequestParam Long id,
#RequestPart File file){
//do some stuff
}
}
The file upload button appears, but it always throws http code 415 when trying to upload a file. Besides, I need the input to be a MultipartFile, not a regular File. Even if I use the #RequestPart annotation with Multipart File, the choose file to upload button does not appear. How can I get this to work???? Even:
#RestController
public class Controller{
#RequestMapping(value="/upload", method=RequestMethod.POST)
public void uploadFile(#RequestPart String metaData,
#RequestPart MultipartFile file){
//do some stuff
}
}
Won't work. If someone could give a walkthrough of how to get this button to appear for MultipartFile? I'd be forever grateful.
I think you are missing the consumes attribute of the #RequestMapping in your second snippet. See the following example
#RequestMapping(
path = "/upload",
method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> handleUpload(
#RequestPart("file") MultipartFile file,
#RequestParam("someId") Long someId,
#RequestParam("someOtherId") Long someOtherId) {
return new ResponseEntity<>();
}
Use
#RequestPart(required = true) MultipartFile file
And use the version number 2.1.0 or latest, there is a bug with previous versions.
https://github.com/springfox/springfox/issues/786
In my situation, there were two things I needed to do
My MultipartFile request param had to be named 'file', otherwise, swagger-ui wouldn't display the file upload input control
#RequestParam("file") MultipartFile file
I had to register the following bean
#Bean(name = "multipartResolver")
public CommonsMultipartResolver commonsMultipartResolver(){
return new CommonsMultipartResolver();
}
Try using #RequestPart for MultipartFile instead of #RequestParam
#RestController
public class controller {
#RequestMapping(value="/upload", method=RequestMethod.POST)
public void uploadFile(#RequestParam Long id,
#RequestPart MultipartFile file) {
//do some stuff
}
}
Two things...
Value of consumes should should be "multipart/form-data". consumes="multipart/form-data"
#RequestPart("file") #ApiParam(value="File", required=true) MultipartFile file
I have the following class:
public class MyDTO {
#NotEmpty
private String isKiosk;
...
}
and following url:
http://localhost:1234/mvc/controllerUrl?isKiosk=false
and following controller method:
#RequestMapping(method = RequestMethod.GET, produces = APPLICATION_JSON)
#ResponseBody
public ResponseEntity<List<?>> getRequestSupportKludge(#Valid final MyDTO myDTO, BindingResult bindingResult) {
...
}
When I stop in debug at getRequestSupportKludge method I see that myDTO.isKiosk equals null.
I cannot change the request url.
Where can I configure mapping for my request parameter ?
it is working after adding following binder:
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, "isKiosk", new PropertyEditorSupport() {
public void setAsText(String name) {
setValue(name);
}
});
}
You need to use #QueryParam to fetch the value in controller. What is binding isKiosk to myDTO? Nothing when you are requesting the URL like above. If you are using some view technology and form to submit data then it is important to bind the form variables to the object.
The other way is you can expose myDTO as a ModelAttribute and use
public xxxx controllerMethod(#ModelAttribute("myDTO") MyDTO myDTO, ...) {}