文档章节

SpringMVC实现RESTful服务

o
 osc_x4h57ch8
发布于 2018/04/24 16:19
字数 742
阅读 11
收藏 0

精选30+云产品,助力企业轻松上云!>>>

          SpringMVC实现RESTful服务

  

这里只说service,controller层的代码。Mapper层则直接继承Mapper<T>则可以,记住mybatis-config.xml一定要配置分页插件和mapper类的插件。

  1.查询所有用户

  service:

 

 1     @Autowired
 2     private IUserMapper userMapper;
 3 
 4     @Override
 5     public EasyUIResult getAllUser(Integer page, Integer rows) {
 6         // TODO Auto-generated method stub
 7 
 8         // 后台帮我们封装了一个page并且直接存到本地线程
 9         PageHelper.startPage(page, rows);
10         Example example = new Example(User.class);
11         example.setOrderByClause("updated desc");
12         List<User> list = userMapper.selectByExample(example);
13         PageInfo<User> pageInfo = new PageInfo<>(list);
14         return new EasyUIResult(pageInfo.getTotal(), pageInfo.getList());
15     }

  controller:

 

 1     /**
 2      * 查询所有用户 返回数据类型为:json格式
 3      * 
 4      * @param page
 5      * @param rows
 6      * @return
 7      */
 8     @RequestMapping(value = "list", method = { RequestMethod.POST })
 9     public @ResponseBody EasyUIResult finAllUser(@RequestParam(value = "page", defaultValue = "1") Integer page,
10             @RequestParam(value = "rows", defaultValue = "5") Integer rows) {
11         return userService.getAllUser(page, rows);
12     }

 

    2.根据用户id查询用户信息

  service:

1     @Override
2     public User queryUserById(Long id) {
3         // TODO Auto-generated method stub
4         return userMapper.selectByPrimaryKey(id);
5     }

 

  cotroller:

 1 @Controller
 2 @RequestMapping("user/rest")
 3 public class RestUserController {
 4 
 5     @Autowired
 6     private IUserService userService;
 7 
 8     /**
 9      * 根据id查询用户信息
10      * 
11      * @param id
12      * @return
13      */
14     @RequestMapping(value = "{userId}", method = RequestMethod.GET)
15     public ResponseEntity<User> queryUserById(@PathVariable(value = "userId") Long id) {
16         try {
17             User user = userService.queryUserById(id);
18             if (user == null) {
19                 return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
20             }
21             // return ResponseEntity.ok(user);
22         } catch (Exception e) {
23             // TODO: handle exception
24             e.printStackTrace();
25         }
26         // return ResponseEntity.status(500).body(null);
27         // 系统内部异常
28         return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
29     }

    3.添加一个用户

  service:

1 @Override
2     public Boolean saveUser(User user) {
3         // TODO Auto-generated method stub
4         return userMapper.insertSelective(user) == 1;
5     }

  controller:

 1     /**
 2      * 添加一个用户
 3      * 
 4      * @param user
 5      * @return
 6      */
 7     @RequestMapping(method = RequestMethod.POST)
 8     public ResponseEntity<Void> addUser(User user) {
 9         try {
10             userService.saveUser(user);
11             return ResponseEntity.status(HttpStatus.CREATED).build();
12             // return ResponseEntity.ok(user);
13         } catch (Exception e) {
14             // TODO: handle exception
15             e.printStackTrace();
16         }
17         return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
18     }

 

  4.修改用户

  service:

1 @Override
2     public boolean updateUsers(User user) {
3         // TODO Auto-generated method stub
4         // 修改用户所有信息
5         // userMapper.updateByPrimaryKey(User);
6         // 修改不为空的字段
7         // userMapper.updateByPrimaryKeySelective(record);
8         return userMapper.updateByPrimaryKey(user) == 1;
9     }

  controller:

/**
     * 跟新用户
     * 
     * @param user
     * @return
     */
    @RequestMapping(method = RequestMethod.PUT)
    public ResponseEntity<Void> updateUser(User user) {
        try {
            boolean b = userService.updateUsers(user);
            if (b) {
                return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
            }
            // return ResponseEntity.ok(user);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

 

  5.删除

  service:

1     @Override
2     public boolean deleteUser(Long id) {
3         // TODO Auto-generated method stub
4         return userMapper.deleteByPrimaryKey(id) == 1;
5     }

  controller:

 1     /**
 2      * 删除一个用户
 3      * 
 4      * @param id
 5      * @return
 6      */
 7     @RequestMapping(method = RequestMethod.DELETE)
 8     public ResponseEntity<Void> deleteUser(@RequestParam(value = "id", defaultValue = "0") Long id) {
 9         try {
10             if (id == 0) {
11                 return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
12             }
13             boolean b = userService.deleteUser(id);
14             if (b) {
15                 return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
16             }
17             // return ResponseEntity.ok(user);
18         } catch (Exception e) {
19             // TODO: handle exception
20             e.printStackTrace();
21         }
22         return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
23     }

 

  delete删除时比较特殊:一定要注意

 

  

  进行删除和修改时,要在web.xml中配置过滤器(补充):

 1 <!-- 
 2         将POST请求转化为DELETE或者是PUT
 3         要用_method指定真正的请求参数
 4      -->
 5     <filter>
 6         <filter-name>HiddenHttpMethodFilter</filter-name>
 7         <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
 8     </filter>
 9     <filter-mapping>
10         <filter-name>HiddenHttpMethodFilter</filter-name>
11         <url-pattern>/*</url-pattern>
12     </filter-mapping>

 

1 <!-- 解决PUT请求无法提交表单数据的问题 -->
2     <filter>
3         <filter-name>HttpMethodFilter</filter-name>
4         <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
5     </filter>
6     <filter-mapping>
7         <filter-name>HttpMethodFilter</filter-name>
8         <url-pattern>/*</url-pattern>
9     </filter-mapping>

 

  大功告成!!

 

o
粉丝 0
博文 500
码字总数 0
作品 0
私信 提问
加载中
请先登录后再评论。

暂无文章

salesforce community cloud 1

NO.1 Universal Containers has a Community for their partners. They would like to add a new partner company and grant their users access to the Community. What is the first step ......

jinzongyu
8分钟前
11
0
如何使用PHP计算两个日期之间的差异? - How to calculate the difference between two dates using PHP?

问题: I have two dates of the form: 我有两个日期格式: Start Date: 2007-03-24 End Date: 2009-06-26 Now I need to find the difference between these two in the following form:......

技术盛宴
17分钟前
14
0
SkyWalking 采样率设置

版本:7.0.0 描述 在默认情况下,SkyWalking会采集所有追踪的数据。但是如果系统比较复杂,采集的端点比较多的时候,可能存储压力比较大,这个时候我们可以修改配置,只存储部分的调用链路信...

zm123321
33分钟前
14
0
FusionInsight环境的安装部署(FI的安装部署)

FusionInsight环境的安装部署 FusionInsight的介绍    FusionInsight简称FI,是华为基于大数据平台开发的一个大数据集成软件。使用FI能快速安装部署各种开源hadoop生态系统的大数据开发环境...

xintaiideas
34分钟前
16
0
Akka 网络编程-小黄鸡客服

需求分析 程序网络拓扑图 程序框架图 功能实现 YellowChickenServer.scala package com.akka.yellowchicken.serverimport akka.actor.{Actor, ActorRef, ActorSystem, Props}import com.......

hexiaoming123
38分钟前
9
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部