温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

springMVC rest风格

发布时间:2020-07-12 08:50:32 来源:网络 阅读:293 作者:乾坤刀 栏目:开发技术

1.dispatcherServlet的配置

	<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-mvc-ftl.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
注:<url-pattern>/</url-pattern>不能指定后缀名


2. 使servlet可以操作PUT和DELETE

    <!-- 支持http的PUT和DELTE操作 --> 
    <filter>
        <filter-name>httpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>httpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


3.controller示例

@Controller
@RequestMapping("/user/")
public class UserController 
{

	@RequestMapping(value="index", method=RequestMethod.GET, produces={"application/json;charset=UTF-8"})
	public ModelAndView index()
	{
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("home");
		return modelAndView;
	}
	
	@RequestMapping(value="user/{id}", method=RequestMethod.GET, produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public User getUser(@PathVariable("id") String userId)
	{
		System.err.println("查询用户信息:" + userId);
		return new UserBuilder().setUserId(userId).setUserName("测试").toUser();
	}
	
	@RequestMapping(value="user", method=RequestMethod.POST, produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public User addUser(String userId, String userName, int userAge)
	{
		System.err.println("新增用户信息:" + userId);
		return new UserBuilder().setUserId(userId).setUserName(userName).setUserAge(userAge).toUser();
	}
	
	@RequestMapping(value="user", method=RequestMethod.PUT, produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public User editUser(String userId, String userName, int userAge)
	{
		System.err.println("修改用户信息:" + userId);
		return new UserBuilder().setUserId(userId).setUserName(userName).setUserAge(userAge).toUser();
	}
	
	@RequestMapping(value="user/{id}", method=RequestMethod.DELETE, produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public User deleteUser(@PathVariable("id") String userId)
	{
		System.err.println("删除用户信息:" + userId);
		return new UserBuilder().setUserId(userId).toUser();
	}
}


4.js示例

   <script type="text/javascript">	
   		function fnQuery(){
   		    $.ajax({
	             type: 'GET',
	             url: '${request.contextPath}/user/user/111',
	             async: true,
	             data: {},
	             dataType: "json",
	             success: function(data){
	                alert(JSON.stringify(data));
	             },
	             error:function(msg){
	                alert(JSON.stringify(msg));
	             }
	         });
	     }
   		function fnAdd(){
   		    $.ajax({
	             type: 'POST',
	             url: '${request.contextPath}/user/user',
	             async: true,
	             data: {
	                'userId':'123',
	                'userName':'测试测试测试测试',
	                'userAge':88,
	             },
	             dataType: "json",
	             success: function(data){
	                alert(JSON.stringify(data));
	             },
	             error:function(msg){
	                alert(JSON.stringify(msg));
	             }
	         });
	     }
   		function fnEdit(){
   		    $.ajax({
	             type: 'POST',
	             url: '${request.contextPath}/user/user',
	             async: true,
	             data: {
	                _method:'PUT',
	                'userId':'55555',
	                'userName':'修改试测试测试',
	                'userAge':48,
	             },
	             dataType: "json",
	             success: function(data){
	                alert(JSON.stringify(data));
	             },
	             error:function(msg){
	                alert(JSON.stringify(msg));
	             }
	         });
	     }
	     
   		function fnDelete(){
   		    $.ajax({
	             type: 'POST',
	             url: '${request.contextPath}/user/user/111',
	             async: true,
	             data: {
	                _method:'DELETE',
	             },
	             dataType: "json",
	             success: function(data){
	                alert(JSON.stringify(data));
	             },
	             error:function(msg){
	                alert(JSON.stringify(msg));
	             }
	         });
	     }
	</script>


注:PUT与DELETE的特殊处理,需要在参数中增加_method.


参考地址:http://www.cnblogs.com/qixiaoyizhan/p/5864233.html


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI