问题
I've been thinking if it is possible to handle Multipart request that is not an Action request. There is a reason why it seems impossible to me :
Only ActionRequest implements getFile() kind of methods. I can't find any easy way how to get the file out of request other than Action request
What if I don't use a html form to upload a file and I don't want a view to be rendered after action request - render phase happens always after the action phase.
What if I want to create a post request (with file(s)) by ajax and use @ResourceMapping handler. How do I get it out of ResourceRequest ?
Thank you very much for your thoughts.
回答1:
This is the "pattern" that is afaik the best way of handling Multipart requests
Action request from view layer goes to this method:
@ActionMapping(params = "javax.portlet.action=sample")
public void response(MultipartActionRequest request, ActionResponse response) {
response.setRenderParameter("javax.portlet.action", "success");
List<MultipartFile> fileList = request.getFiles("file");
}
render phase follows :
@RequestMapping(params = "javax.portlet.action=success")
public ModelAndView process(RenderRequest request, Model model) throws IOException {
Map map = new HashMap();
map.put("test", new Integer(1));
return new ModelAndView("someView", map);
}
You create a "bean" view :
@Component("someView")
public class SomeView extends AbstractView {
private Logger logger = Logger.getLogger(SomeView.class);
@Override
protected void renderMergedOutputModel(Map map, HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.info("Resolving ajax request view - " + map);
JSONObject jsonObj = new JSONObject(map);
logger.info("content Type = " + getContentType());
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonObj.toString());
response.getWriter().flush();
}
}
You add BeanNameViewResolver into your servlet/portlet context:
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="1" />
来源:https://stackoverflow.com/questions/4796420/handling-multipart-request-that-is-not-an-action-request