SpringMVC 通过RESTFUL风格进行CRUD

xiaoxiao2021-02-28  5

jsp页面:

   <form action="${pageContext.request.contextPath}/login/checkeRestFull.do" method="post">      <input type="submit" value="测试post">     </form>        <form action="${pageContext.request.contextPath}/login/checkeRestFull/1.do" method="get">      <input type="submit" value="测试get">     </form> controller页面:

@Controller @RequestMapping("/login") //@SessionAttributes(value="username",types=String.class) public class LoginController { @RequestMapping(value="/checkeRestFull",method=RequestMethod.POST) //增 public String testPost(){ System.out.println("this is testPost"); return "users/ok"; } @RequestMapping(value="/checkeRestFull/{id}",method=RequestMethod.GET) //查 public String testGet(@PathVariable(value="id")int id) { System.out.println("this is testGet and id="+id); return "users/ok"; }

修改、删除稍加复杂:

需在web.xml中配置过滤器:

    <filter>       <filter-name>hiddenHttpMethodFilter</filter-name>       <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>     </filter>     <filter-mapping>       <filter-name>hiddenHttpMethodFilter</filter-name>       <url-pattern>/*</url-pattern>     </filter-mapping>   另外在表单域中添加隐藏域:

<form action="${pageContext.request.contextPath}/login/checkeRestFull/1.do" method="post"> <input type="hidden" name="_method" value="put"> <input type="submit" value="测试put"> </form> <form action="${pageContext.request.contextPath}/login/checkeRestFull/1.do" method="post"> <input type="hidden" name="_method" value="delete"> <input type="submit" value="测试delete"> </form> controller代码:

@RequestMapping(value="/checkeRestFull/{id}",method=RequestMethod.PUT) //修改 public String testPut(@PathVariable(value="id") int id){ System.out.println("this is testPut id="+id); return "users/ok"; } @RequestMapping(value="/checkeRestFull/{id}",method=RequestMethod.DELETE) //删除 public String testDelete(@PathVariable(value="id") int id) { System.out.println("this is testDelete id="+id); return "users/ok"; }

转载请注明原文地址: https://www.6miu.com/read-1400380.html

最新回复(0)