util 连接jdbc工具和返回json工具
选择自底向上的模式进行开发登录接口。首先创建数据库和对应用户表
CREATE datebase teach_demo;
USE teach_demo;
CREATE TABLE `user`(
`id` INT(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`username` VARCHAR(64) NOT NULL COMMENT '用户名',
`password` VARCHAR(64) NOT NULL COMMENT '密码',
PRIMARY KEY(`id`),
UNIQUE KEY(`username`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES(NULL,'zhangsan','123456');
第二,创建参数接受对象在domain下
package cn.homyit.domain;
public class User {
private Long id;
private String username;
private String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
第三,创建UserDao接口,并且实现方法
package cn.homyit.dao;
import cn.homyit.domain.User;
public interface UserDao {
boolean login(User user) throws Exception;
}
package cn.homyit.dao.impl;
import cn.homyit.dao.UserDao;
import cn.homyit.domain.User;
import cn.homyit.util.JDBCUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class UserDaoImpl implements UserDao {
@Override
public boolean login(User user) throws Exception {
boolean flag = false;
Connection conn = JDBCUtil.getConnection();
String sql = "select * from user where username =? and password=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
ResultSet rs = ps.executeQuery();
if(rs.next()){
flag = true;
}
return flag;
}
}
连接数据库时我们使用JDBCUtil
package cn.homyit.util;
import java.sql.*;
public class JDBCUtil {
private static String URL = "jdbc:mysql://localhost:3306/teach_demo?" +
"useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimeZone=Asia/Shanghai";
private static String USERNAME = "root";
private static String PASSWORD = "123456";
private static Connection connection = null;
private static PreparedStatement statement = null;
private static ResultSet resultSet = null;
public static Connection getConnection() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
第四,测试我们的实现方法是否符合我们的预期,在src下创建一个test文件夹,创建对应的包和类
import cn.homyit.domain.User;
import org.junit.Test;
public class UserDaoTest {
@Test
public void testLogin() throws Exception {
UserDao userDao = new UserDaoImpl();
boolean flag = userDao.login(new User("zhangsan", "123456"));
System.out.println(flag);
}
}
第五,创建service类和实现
package cn.homyit.service;
import cn.homyit.domain.User;
public interface UserService {
boolean login(User user) throws Exception;
}
package cn.homyit.service.impl;
import cn.homyit.dao.UserDao;
import cn.homyit.dao.impl.UserDaoImpl;
import cn.homyit.domain.User;
import cn.homyit.service.UserService;
public class UserServiceImpl implements UserService {
private UserDao userDao = new UserDaoImpl();
@Override
public boolean login(User user) throws Exception {
return userDao.login(user);
}
}
第六,创建cotroller,我们导入的依赖为javax.servlet-api,其中有注解的实现,我们选择注解来注册访问路径而不是再使用web.xml。登录为了安全我们使用的是dopost方法。我这里还做了简单的异常处理,这是需要做的,为了给用户更好的体验。
package cn.homyit.controller;
import cn.homyit.domain.Result;
import cn.homyit.domain.User;
import cn.homyit.service.UserService;
import cn.homyit.service.impl.UserServiceImpl;
import cn.homyit.util.JSONUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/user/login")
public class LoginServlet extends HttpServlet {
private UserService userService = new UserServiceImpl();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
User user = new User(username, password);
Result result = new Result();
try {
boolean flag = userService.login(user);
if(flag ==true){
result.setCode(200);
result.setMsg("登录成功");
HttpSession session = req.getSession();
session.setAttribute("USER",user);
}else {
result.setCode(201);
result.setMsg("登录失败,用户名或密码错误");
}
JSONUtil.returnJSON(resp,result);
} catch (Exception e) {
result.setCode(500);
result.setMsg("服务器出错,请联系管理员");
JSONUtil.returnJSON(resp,result);
e.printStackTrace();
}
}
}
其中前后端交互中,后端返回数据以json格式返回,我们使用下面这个工具类
package cn.homyit.util;
import cn.homyit.domain.Result;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class JSONUtil {
public static void returnJSON(HttpServletResponse resp, Result result) throws IOException {
PrintWriter writer = resp.getWriter();
JSONObject jsonObject = new JSONObject();
jsonObject.put("code",result.getCode());
jsonObject.put("msg",result.getMsg());
jsonObject.put("data",result.getData());
writer.print(jsonObject);
writer.close();
}
}
但是呢,响应有时候需要一个返回的数据对象而不是只有状态码和提示信息,因此我们创建一个返回对象,对象中使用一个数据对象的泛型。
package cn.homyit.domain;
public class Result<T> {
private int code;
private String msg;
private T data;
public Result() {
}
public Result(int code, String msg) {
this.code = code;
this.msg = msg;
}
public Result(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
第七,配置tomcat和默认项目路径,使用postman测试该接口