Java后台接口开发初步实战教程

网友投稿 288 2023-02-21


Java后台接口开发初步实战教程

上图是查询列表的接口,get方式

上图是用户注册的接口,同样是get,post方式也很简单

开发工具:IntelliJ IDEA 2016.3.5

ORM框架:MyBatis

数据库:mysql

服务器:tomcat7.0

公司使用的的orm框架是Hibernate,使用起来感觉比mybatis好用多了,毕竟经过了公司这么多项目的考验,总比自己用mybatis写的项目可靠,但以下分享的还是mybatis的代码

注册接口方法:http://192.168.1.116:8080/register?username=111&password=222

@RequestMapping(value = "register", method = RequestMethod.GET)

@ResponseBody

public Map register(@RequestParam("username") String username, @RequestParam("password") String password) {

out.println("welcome to register,username=" + username + ";password=" + password);

Map map = new HashMap<>();

ResultBean result = onRegister(username, password);

out.println("result==>" + result);

map.put("code", result.getCode());

map.put("reason", result.getReason());

map.put("success", result.isSuccess());

return map;

}

具体的注册方法,获取session基本和Hibernate差不多

private ResultBean onRegister(String username, String password) {

Reshttp://ultBean resultBean = new ResultBean();

SqlSession session = null;

try {

session = sqlSessionFactory.openSession();

LoginMapper loginMapper = session.getMapper(LoginMapper.class);

Map map = new HashMap<>();

map.put("name", username);

map.put("password", password);

LoginBean bean = new LoginBean();

bean.setName(username);

bean.setPassword(password);

// 查询用户是否存在

LoginBean userExist = loginMapper.findUserByName(map);

if (userExist != null) {

// 存在后无法注册

resultBean.setCode("001");

resultBean.setSuccess(false);

resultBean.setReason("用户已存在");

} else {

loginMapper.addUser(bean);

session.commit();// 重要,一定要commit,否则无法insert

System.out.println("当前增加的用户id为:" + bean.getId());

resultBean.setCode("200");

resultBean.setSuccess(true);

resultBean.setReason("注册成功");

}

} catch (Exception e) {

e.printStackTrace();

out.println("注册异常==>" + e.getMessage());

resultBean.setCode("001");

resultBean.setSuccess(false);

resultBean.setReason("注册异常");

} finally {

session.close();

}

return resultBean;

}

这个Mapper需要在配置文件中指定

public interface LoginMapper {

public LoginBean findUserByName(Map map) throws Exception;

public void addUser(LoginBean bean) throws Exception;

}

这是对应的LoginMapper.xml

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-config.dtd">

ceTVZ select * from run

select * from user where name = #{name} and password = #{password}

select * from user where name = #{name}

insert into user(id,name,password) values(#{id},#{name},#{password})


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:新闻详情api接口文档(新闻api开放接口)
下一篇:支付功能的接口测试用例(支付接口自动化测试)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~