在java web开发过程中,不可避免的会使用Get请求,url特点是:http://A.B.com/hiArticle/get_article_detail?article_id=1121
那么对于这类的url应该如何在Spring mvc中获取到article_id参数的值呢?
为了表达清晰,我直接来一段代码表示:
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ArticleController {
@RequestMapping(value = "/get_article_detail", method = RequestMethod.GET)
public ModelAndView getArticle(
@RequestParam(value = "article_id", required = true, defaultValue = "0") String article_id) {
ModelAndView mv = new ModelAndView("ArticleDetails");
try {
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();
ArticleMapper mapper = session.getMapper(ArticleMapper.class);
ArticleModel article_model = mapper.selectArticle(Integer.parseInt(article_id));
session.close();
// 指定视图
// 向视图中添加所要展示或使用的内容,将在页面中使用
mv.addObject("article_id", article_id);
mv.addObject("title", article_model.getTitle());
mv.addObject("content", article_model.getContent());
} catch (Exception e) {
e.printStackTrace();
}
return mv;
}
public ModelAndView getArticle(@RequestParam(value ="article_id", required =true, defaultValue ="0") String article_id){
代码中的这一段,表明我们要接收的参数名字为article_id,是一个必须的字段。
在代码中我们直接使用article_id即是该参数的值了。