首页 > 编程语言 > 详细

springmvc学习日志四

时间:2019-09-05 19:59:00      阅读:89      评论:0      收藏:0      [点我收藏+]

一、restful风格

设置restful风格无需在添加jar包,只需在之前示例的基础上设置请求处理方式

建立实体类

public class User {
      private String name;
      private String password;
      private String phone;
}

建立jsp页面,向控制层传输数据和提交方式

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="/springmvc4/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
     $.ajax({
        url:"user/1",
        type:"post",
        data:{
            _method:"delete",
            "name":"张三",
            "password":"123456",
            "phone":"15295730918"
        },
        success:function(result){
            //alert(result);
            location.href="/springmvc4/index.jsp";
        }
     });
</script>
</head>
<body>

</body>
</html>

1.当请求提交方式为get时,建立Controller类,并根据请求的方式调用相应的方法

@Controller
@RequestMapping("user")
public class UserController {
        
    //restFul---->user/1
    //method:表示方法处理get请求
    //把1赋值给{uid}了,uid可自定义 
    @RequestMapping(value="{uid}", method=RequestMethod.GET) //查询操作
    public String findById(@PathVariable("uid") int id) {//@PathVariable把uid的值赋值给形参数
        System.out.println("====findId===="+id);
        return "index";
    }
}

2.当请求提交的方式为post、put和delete时

首先在web.xml中配置过滤器

<!-- 
          把post请求转化为PUT和DELETE请求
          使用_method表示真正的提交方式
   -->
  <filter>
         <filter-name>hiddenHttpMethodFilte</filter-name>
         <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>hiddenHttpMethodFilte</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

再建立Controller类,在类中根据不同的方式调用不同的方法

@Controller
@RequestMapping("user")
public class UserController {
    
    @RequestMapping( method=RequestMethod.POST) //添加操作
    public String insertUser(User user) {
        System.out.println("1==="+user);
        return "index";
    }
    //springmvc提供了一个过滤,该过滤器可以把post请求转化为put和delete请求
    @RequestMapping( method=RequestMethod.PUT) //修改操作
    //用于返回Ajax对象,一定要加,当使用springmvc提供的可以把post请求转化为put和delete请求的过滤器时
    @ResponseBody  
    public String updateUser(User user) {
        System.out.println(user+"update");
        return "index";//也可返回json对象
    }

    //如果web.xml中配置为*.do,那么只在url地址栏中加.do,这里的value中不需要加.do
    @RequestMapping(value="{id}" ,method=RequestMethod.DELETE) //删除操作
    @ResponseBody 
    public String deleteUser(@PathVariable int id) {
        System.out.println(id+"=====delete");
        return "index";
    }
    
}

 

springmvc学习日志四

原文:https://www.cnblogs.com/sitian2050/p/11469181.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!