@requestmapping和ModelAndView

时间:2018-01-28 17:31:38

标签: spring spring-mvc request-mapping modelandview

嗨帮我请Spring SpringMapping。我有这样的页面:

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

和这样的控制器:

@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();
        }
    }
}

方法&#34; onIndex&#34;正在工作,但onAddPhoto似乎没有,当我点击按钮whith URL&#34; / add_photo&#34;它给了我404而不是页面&#34;结果&#34;

1 个答案:

答案 0 :(得分:1)

在jsp页面中使用pageContext:

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

有关详情:Check this