Java后台接⼝开发初步实战教程
上图是查询列表的接⼝,get⽅式
上图是⽤户注册的接⼝,同样是get,post⽅式也很简单
开发⼯具:IntelliJ IDEA 2016.3.5
ORM框架:MyBatis
数据库:MySql
服务器:tomcat7.0
公司使⽤的的orm框架是Hibernate,使⽤起来感觉⽐mybatis好⽤多了,毕竟经过了公司这么多项⽬的考验,总⽐⾃⼰⽤mybatis写的项⽬可靠,但以下分享的还是mybatis的代码
@RequestMapping(value = "register", method = RequestMethod.GET)
@ResponseBody
public Map<String, Object> register(@RequestParam("username") String username, @RequestParam("password") String password) {
out.println("welcome to register,username=" + username + ";password=" + password);
Map<String, Object> map = new HashMap<>();
ResultBean result = onRegister(username, password);
out.println("result==>" + result);
map.put("code", Code());
map.put("reason", Reason());
map.put("success", result.isSuccess());
return map;
}
具体的注册⽅法,获取session基本和Hibernate差不多
private ResultBean onRegister(String username, String password) {
ResultBean resultBean = new ResultBean();
SqlSession session = null;
try {
session = sqlSessionFactory.openSession();
LoginMapper loginMapper = Mapper(LoginMapper.class);
Map<String, Object> 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);
sessionmit();// 重要,⼀定要commit,否则⽆法insert
System.out.println("当前增加的⽤户id为:" + Id());
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<String,Object> map) throws Exception;
public void addUser(LoginBean bean) throws Exception;
}
这是对应的l
安卓开发教程 pdf<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-////DTD Mapper 3.0//EN"
"/dtd/mybatis-3-config.dtd">
<mapper namespace="avel.LoginMapper">
<select id="loadRunList" parameterType="java.util.Map" resultType="avel.RunBean">
select * from run
</select>
<select id="loginUser" parameterType="java.util.Map" resultType="avel.LoginBean">
select * from user where name = #{name} and password = #{password}
</select>
<select id="findUserByName" parameterType="java.util.Map" resultType="avel.LoginBean">
select * from user where name = #{name}
</select>
<insert id="addUser" useGeneratedKeys="true" keyProperty="id" >
insert into user(id,name,password) values(#{id},#{name},#{password})
</insert>
</mapper>
以上这篇 Java后台接⼝开发初步实战教程就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论