为restful开发的话,一定要设计到URL,struts正好是管理URL的
所以在struts的项目中用restful,要遵守struts的规则
rest在struts中对应的方法
上面是官方给出的帮助文档(默认情况下)
- get,不带id参数——index
- get,带id——show
- post,不带id——create
- put,带id——update
- delete,带id——destroy
- get,带id且访问edit资源——edit
- get,不带id访问edit资源——editNew
rest的相关常量
struts.mapper.idParameterName
- If set, this value will be the name of the parameter under which the id is stored. The id will then be removed from the action name. Whether or not the method is specified, the mapper will try to truncate the identifier from the url and store it as a parameter.struts.mapper.indexMethodName
- The method name to call for a GET request with no id parameter. Defaults to index.struts.mapper.getMethodName
- The method name to call for a GET request with an id parameter. Defaults to show.struts.mapper.postMethodName
- The method name to call for a POST request with no id parameter. Defaults to create.struts.mapper.putMethodName
- The method name to call for a PUT request with an id parameter. Defaults to update.struts.mapper.deleteMethodName
- The method name to call for a DELETE request with an id parameter. Defaults to destroy.struts.mapper.editMethodName
- The method name to call for a GET request with an id parameter and the edit view specified. Defaults to edit.struts.mapper.newMethodName
- The method name to call for a GET request with no id parameter and the new view specified. Defaults to editNew.
在struts.xml里面设置这些常量可以改变访问的method以及id参数在action中的的变量名
配置
- 使用restful开发action的package要继承自rest-default
- 在struts.xml中配置
<constant name="struts.mapper.class" value="rest" />
为了让struts根据rest的约定解析URL且映射到具体的action - 将struts2-convention-plugin-2.1.6.jar、struts2-rest-plugin-2.1.6.jar导入项目
- 将 xstream-1.2.2.jar、json-lib-2.1.jar、ezmorph-1.0.3.jar导入项目
注意
- jsp只支持get、post、head方法访问,所以put和delete就返回json数据给前台
- 要返回json数据的话,需要在package继承"json-default"
- 带id参数,是指在url中直接加入id,而不是parameter中,也不需要key,只用value 比如/123,123就是id,/haha,haha也是个id
- ?id=123这种不是带id参数的访问
- id和edit结合的话,id在edit前面 比如/123;edit或者/123/edit