肝作业时候看见要求,需要使用原生访问数据库增删改查,把以前写的翻出来,怕忘记了,记录一下。
Dao层
封装工具类BaseDao.java
public class BaseDao {
public static String driver;
public static String url;
public static String username;
public static String password;
static {
Properties properties = new Properties();
InputStream input = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
try {
properties.load(input);
} catch (IOException e) {
e.printStackTrace();
}
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
}
public static Connection getConnection() {
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return connection;
}
//查
public static ResultSet execute(Connection connection, ResultSet rs, PreparedStatement preparedStatement, String sql, Object[] params) throws SQLException {
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
preparedStatement.setObject(i + 1, params[i]);
}
rs = preparedStatement.executeQuery();
return rs;
}
//增删改
public static int execute(Connection connection, PreparedStatement pstm,String sql, Object[] params) throws SQLException {
pstm = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pstm.setObject(i + 1, params[i]);
}
int updateRows = pstm.executeUpdate();
return updateRows;
}
public static boolean CloseResource(Connection connection, PreparedStatement preparedStatement, ResultSet rs) {
boolean flag = true;
try {
if (rs != null) {
rs.close();
// GC回收
rs = null;
}
if (preparedStatement != null) {
preparedStatement.close();
preparedStatement = null;
}
if (connection != null) {
connection.close();
connection = null;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
flag = false;
}
return flag;
}
}
UserDao.java
没写全,因为作业就这俩功能
public interface UserDao {
User login(String name);
int register(User user);
}
UserDaoImpl.java
public class UserDaoImpl implements UserDao {
@Override
public User login(Connection connection, String name) throws SQLException {
PreparedStatement pst = null;
ResultSet rs = null;
User user = null;
if (connection != null) {
String sql = "SELECT * FROM users where name=?";
Object[] params = {name};
rs = BaseDao.execute(connection, rs, pst, sql, params);
if (rs.next()) {
user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setBirthday(rs.getString("birthday"));
}
BaseDao.CloseResource(connection, pst, rs);
}
return user;
}
@Override
public int register(Connection connection, User user) throws SQLException {
PreparedStatement pstm = null;
int updateNum = 0;
if (connection != null) {
String sql = "insert into users (id,name,password," +
"email,birthday) " +
"values(?,?,?,?,?)";
Object[] params = {user.getId(), user.getName(), user.getPassword(), user.getEmail(), user.getEmail()};
updateNum = BaseDao.execute(connection, pstm, sql, params);
BaseDao.CloseResource(null, pstm, null);
}
return updateNum;
}
}
Service层
UserService.java
public interface UserService {
User Login(String name);
Boolean Register(User user);
}
UserServiceImpl.java
public class UserServiceImpl implements UserService {
private UserDao userDao;
public UserServiceImpl() {
userDao = new UserDaoImpl();
}
@Override
public User Login(String name) {
Connection connection = null;
User user = null;
connection = BaseDao.getConnection();
try {
user = userDao.login(connection, name);
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
BaseDao.CloseResource(connection, null, null);
}
return user;
}
@Override
public Boolean Register(User user) {
Boolean flag = false;
Connection connection = null;
try {
//获得连接
connection = BaseDao.getConnection();
//开启JDBC事务管理
connection.setAutoCommit(false);
int updateRows = userDao.register(connection, user);
connection.commit();
if (updateRows > 0) {
flag = true;
System.out.println("add success!");
} else {
System.out.println("add failed!");
}
} catch (Exception e) {
e.printStackTrace();
try {
System.out.println("rollback==");
//失败就回滚
connection.rollback();
} catch (SQLException exception) {
exception.printStackTrace();
}
} finally {
//在service层进行connection连接的关闭
BaseDao.CloseResource(connection, null, null);
}
return flag;
}
}
原生写的真麻烦,果然还是框架好用。
Controller层
扛不住了,浅用一下注解,省的写web.xml了
LoginServlet.java
@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
UserService userImpl = new UserServiceImpl();
User user = userImpl.Login(username);
if (!user.getName().isEmpty()) {
String ps = user.getPassword();
if (ps.equals(password)) {
req.getRequestDispatcher("/success.jsp").forward(req, resp);
} else {
req.getRequestDispatcher("/error.jsp").forward(req, resp);
}
} else {
req.getRequestDispatcher("/error.jsp").forward(req, resp);
}
}
}
RegisterServlet.java
@WebServlet(name = "RegisterServlet", value = "/register")
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
String email = req.getParameter("email");
String birthday = req.getParameter("birthday");
UserService userService = new UserServiceImpl();
Boolean isRegister = userService.Register(new User(10, username, password, email, birthday));
if (isRegister) {
req.getRequestDispatcher("/registerSuccess.jsp").forward(req,resp);
} else {
req.getRequestDispatcher("/registerFailed.jsp").forward(req,resp);
}
}
}
差不多了,jsp就不贴了,很简陋。