2021SC@SDUSC
一、项目结构
(1)在web 目录下创建META-INF目录,在目录下创建文件context.xml 地址构成
jdbc:mysql://minichat@localhost:3306/mini_chat?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
context.xml:
<?xml version="1.0" encoding="utf-8"?>
<Context reloadable="true">
<Resource
name="jdbc/minichat"
type="javax.sql.DataSource"
maxTotal="100"
maxIdle="50"
driverClassName="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://minichat@localhost:3306/mini_chat?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8"
userName="root"
password="root"
maxWaitMillis="5000"/>
</Context>
第(2)WEB-INF目录下创建目录lib
2.数据库 Dao
所有的实体dao都应该继承于Dao接口
package DB.Base;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public interface Dao {
static DataSource getDataSource(){
DataSource dataSource=null;
try{
Context context=new InitialContext();
dataSource=(DataSource)context.lookup("java:comp/env/jdbc/minichat");
}catch (NamingException ne){
ne.printStackTrace();
}
return dataSource;
}
default Connection getConnection() throws DaoException{
DataSource dataSource=getDataSource();
Connection connection=null;
try{
connection=dataSource.getConnection();
}catch (SQLException se){
se.printStackTrace();
}
return connection;
}
}
DaoException:
package DB.Base;
import java.io.Serializable;
public class DaoException extends Exception implements Serializable {
private static final long serialVersionUID=19192L;
private String message;
public DaoException(){}
public DaoException(String message){
this.message=message;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "DaoException{" +
"message='" + message + '\'' +
'}';
}
}
FriendDao和UserDao都继承dao接口
package DB.Dao;
import DB.Base.Dao;
import Model.Response.FriendAddResponse;
import Model.Response.FriendResponse;
import java.util.List;
public interface FriendDao extends Dao {
List<FriendResponse> getFriendsById(String uid);
FriendAddResponse addFriend(String uid,String fid);
}
package DB.Dao;
import DB.Base.Dao;
import DB.Base.DaoException;
import DB.model.User;
import Model.Response.LoginResponse;
public interface UserDao extends Dao {
boolean signup(String uid,String uname,String password) throws DaoException;
LoginResponse login(String uid,String password);
}
FriendDaoImpl和UserDaoImpl分别实现各自的Dao接口
package DB.Impl;
import DB.Base.DaoException;
import DB.Dao.FriendDao;
import Model.Response.FriendAddResponse;
import Model.Response.FriendResponse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class FriendDaoImpl implements FriendDao {
@Override
public List<FriendResponse> getFriendsById(String uid) {
List<FriendResponse> friendResponses=new ArrayList<>();
System.out.println(uid);
try(Connection connection=getConnection()){
PreparedStatement pst=connection.prepareStatement("select * from friend where uid=?");
pst.setString(1,uid);
ResultSet rst=pst.executeQuery();
while (rst.next()){
friendResponses.add(new FriendResponse(1,null,rst.getString("fid"),
uid,rst.getString("f_name"),rst.getString("nick_name")));
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
} catch (DaoException e) {
e.printStackTrace();
}
return friendResponses;
}
@Override
public FriendAddResponse addFriend(String uid, String fid) {
FriendAddResponse response=new FriendAddResponse(-1,null);
try(Connection connection=getConnection()){
String f_name=null;
String uname=null;
PreparedStatement pst=connection.prepareStatement("select uname from user where uid=?");
pst.setString(1,fid);
ResultSet rst=pst.executeQuery();
if(rst.next()){
f_name=rst.getString("uname");
}else {
response.setMessage("id 不存在");
}
pst.setString(1,uid);
rst=pst.executeQuery();
if(rst.next()){
uname=rst.getString("uname");
}else {
response.setMessage("id 不存在");
}
if(f_name!=null&&uname!=null){
PreparedStatement pst2=connection.prepareStatement("insert into friend(fid,uid,f_name) VALUES (?,?,?)");
pst2.setString(1,fid);
pst2.setString(2,uid);
pst2.setString(3,f_name);
int result0=pst2.executeUpdate();
if(result0>0){
pst2.setString(1,uid);
pst2.setString(2,fid);
pst2.setString(3,uname);
int result1=pst2.executeUpdate();
if(result1>0){
response.setCode(1);
response.setMessage("add friend success");
response.setId(fid);
response.setName(f_name);
}else {
response.setMessage("已添加");
}
}else {
response.setMessage("已添加");
}
}
} catch (SQLException | DaoException sqlException) {
sqlException.printStackTrace();
}
return response;
}
}
package DB.Impl;
import DB.Base.Dao;
import DB.Base.DaoException;
import DB.Dao.UserDao;
import Model.Response.LoginResponse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDaoImpl implements UserDao {
@Override
public boolean signup(String uid, String uname, String password) throws DaoException{
try(Connection connection=getConnection()){
PreparedStatement pst=connection.prepareStatement("insert into user(uid,uname,password) values (?,?,?)");
pst.setString(1,uid);
pst.setString(2,uname);
pst.setString(3,password);
int result=pst.executeUpdate();
return result>0;
} catch (SQLException sqlException) {
sqlException.printStackTrace();
} catch (DaoException e) {
e.printStackTrace();
}
return false;
}
@Override
public LoginResponse login(String uid, String password) {
System.out.println(uid+password);
LoginResponse loginResponse=new LoginResponse();
loginResponse.setCode(-1);
try(Connection connection=getConnection()){
PreparedStatement pst=connection.prepareStatement("select * from user where uid=?");
pst.setString(1,uid);
ResultSet rst=pst.executeQuery();
while (rst.next()){
if(rst.getString("password").equals(password)){
loginResponse.setCode(1);
loginResponse.setMessage("login ok");
loginResponse.setUid(uid);
loginResponse.setName(rst.getString("uname"));
}else {
loginResponse.setCode(-1);
loginResponse.setMessage("login in password failed");
}
}
}catch (DaoException daoException){
daoException.printStackTrace();
loginResponse.setMessage("login in dao failed");
} catch (SQLException sqlException) {
sqlException.printStackTrace();
loginResponse.setMessage("login in sql failed");
}
return loginResponse;
}
}
消息以及请求,相应的实现:
消息:message:
package Model.Base;
import java.io.Serializable;
public class Message implements Serializable {
//@param: code 1成功 0未初始化 -1错误
//@param: message 错误信息提示或其他信息
private int code;
private String message;
public Message() {
code=0;
message=null;
}
public Message(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
各种请求:request:这里以FriendAddRequest为例:
package Model.Request;
public class FriendAddRequest {
String uid;
String f_id;
public FriendAddRequest(String uid, String f_id) {
this.uid = uid;
this.f_id = f_id;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getF_id() {
return f_id;
}
public void setF_id(String f_id) {
this.f_id = f_id;
}
}
各种响应:Response这里以FriendAddResponse为例
package Model.Response;
import Model.Base.Message;
public class FriendAddResponse extends Message {
String id;
String name;
public FriendAddResponse() {
}
public FriendAddResponse(int code, String message) {
super(code, message);
}
public FriendAddResponse(int code, String message, String id, String name) {
super(code, message);
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
三、servelet
最后是各种servelet,以FriendAddServlet为例
package Servlet;
import DB.Dao.FriendDao;
import DB.Impl.FriendDaoImpl;
import Model.Request.FriendAddRequest;
import Model.Response.FriendAddResponse;
import com.google.gson.Gson;
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 java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "FriendAddServlet",urlPatterns ={"/addFriend"})
public class FriendAddServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
FriendAddRequest friendAddRequest=new Gson().fromJson(request.getReader(),FriendAddRequest.class);
FriendAddResponse friendAddResponse=new FriendDaoImpl().addFriend(friendAddRequest.getUid(),friendAddRequest.getF_id());
String rp=new Gson().toJson(friendAddResponse);
response.setContentType("txt/html;charset=utf-8");
PrintWriter writer=response.getWriter();
writer.print(rp);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}