我们在提交较大的数据块时,会使用post的方式,避免url过长,如我们在知乎提交这篇稿子,那么这篇稿子的正文就是通过post打到zhihu的服务器上。
那么在spring mvc中是如何获取post参数的呢?我用代码先表达一下,然后解释:
@RequestMapping(value = "/update_article", method = RequestMethod.POST)
public ModelAndView updateArticle(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("ArticleUpdateResult");
try {
String article_id = new String(request.getParameter("article_id").getBytes("UTF-8"), "UTF-8");
String textareastr = new String(request.getParameter("textareastr").getBytes("UTF-8"), "UTF-8");
ArticleModel articlemodel = new ArticleModel();
articlemodel.setId(Integer.parseInt(article_id));
articlemodel.setContent(textareastr);
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSessionFactory.getConfiguration().addMapper(ArticleMapper.class);
SqlSession session = sqlSessionFactory.openSession();
try {
ArticleMapper mapper = session.getMapper(ArticleMapper.class);
int op_num = mapper.updateArticle(articlemodel);
session.commit();
mv.addObject("article_id", article_id);
mv.addObject("result", op_num);
} finally {
session.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return mv;
}
可以看到,我们在RequestMapping处指定了我们要处理的patten,然后请求方式是post.
接下来,我们在函数中就可以使用:
request.getParameter("textareastr").getBytes("UTF-8"),"UTF-8"
拿到需要的字段了。