0

Hi help me please with Spring RequestMapping. I have page like this:

<form action="/add_photo" enctype="multipart/form-data" method="POST">
                Photo: <input type="file" name="photo">
                <input type="submit" />
     </form>

and controller like this:

@Controller
@RequestMapping("/")
public class MyController {

    private Map<Long, byte[]> photos = new HashMap<>();


    @RequestMapping("/")
    public String onIndex() {
        return "index";
    }

    @RequestMapping(value = "/add_photo", method = RequestMethod.POST)
    public ModelAndView onAddPhoto(@RequestParam MultipartFile photo) {
        if (photo.isEmpty()) {
            throw new PhotoErrorException();            
        }

        try {
            long id = System.currentTimeMillis();
            photos.put(id, photo.getBytes());

            ModelAndView model = new ModelAndView();
            model.addObject("photo_id", id);
            model.setViewName("result");
            return model;
        } catch (IOException e) {
            throw new PhotoErrorException();
        }
    }
}

method "onIndex" is working but onAddPhoto seems not and when I click button whith URL "/add_photo" it gives me 404 instead page "result"

  • What is the URL displayed in the address bar when displaying your form? What is the URL displayed in the address bar after you've submitted the form? – JB Nizet Jan 28 '18 at 17:36
  • after submitting form it's displays "/add_photo" – Mr._Rodman Jan 28 '18 at 17:39
  • And before submitting? – JB Nizet Jan 28 '18 at 17:40
  • before "http://localhost:8080/photos/" and after "http://localhost:8080/add_photo" – Mr._Rodman Jan 28 '18 at 17:51
  • So, if the full path for `@RequestMapping("/")` is `/photos/`, what should be the full url for `@RequestMapping(value = "/add_photo"`? Should it be `/add_photo`, or should it rather be `/photos/add_photo`? What do you think this `/photos`prefix is, and where does it come from? – JB Nizet Jan 28 '18 at 17:54
  • /photos prefix is come from deploing .war file on Tomcat server. That's a name of the project. – Mr._Rodman Jan 28 '18 at 18:07
  • So you need to add this prefix to every URL pointing to a resource of your application (as Suraj's answer explains). – JB Nizet Jan 28 '18 at 18:09
  • should I add it only in jsp page or in jsp and controller? – Mr._Rodman Jan 28 '18 at 18:30

1 Answers1

1

Use pageContext in your jsp page as:

<form action="${pageContext.request.contextPath}/add_photo" enctype="multipart/form-data" method="POST">
Photo: <input type="file" name="photo">
            <input type="submit" />
 </form>

For more details: Check this

Suraj Gautam
  • 1,524
  • 12
  • 21
  • it's just deleted message [before](https://github.com/mrRodman/hello-world/blob/master/photos/errors/123.PNG) and [after](https://github.com/mrRodman/hello-world/blob/master/photos/errors/1234.PNG) – Mr._Rodman Jan 28 '18 at 18:27