首先说明这次代码是个人备注怕忘记!
直接先上代码:
public class DBManager {
// 数据库连接常量
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String USER = "root";
public static final String PASS = "lk018900";
public static final String URL = "jdbc:mysql://localhost:3306/er";
// 静态成员,支持单态模式
private Connection conn = null;
private Statement stmt = null;
// 单态模式-懒汉模式
public DBManager() {
connectDB();
}
// 连接数据库,获取句柄+对象
public void connectDB() {
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, USER, PASS);
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 关闭数据库 关闭对象,释放句柄
public void closeDB() {
try {
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 查询
public ResultSet executeQuery(String sql) {
ResultSet rs = null;
try {
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
// 增添/删除/修改
public int executeUpdate(String sql) {
int ret = 0;
try {
ret = stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return ret;
}
}
获取收到的参数:
// 接收信息
name = request.getParameter("username");
pass = request.getParameter("password");
if (name == null && pass == null) {
Bean gson = new Gson().fromJson(
GsonReceive.getRequestBody(request), Bean.class);
name = gson.getUsername();
pass = gson.getPassword();
}
// //在服务器端解决中文乱码问题
// name = NewString.getNewString(name);
// pass = NewString.getNewString(pass);
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("UTF-8");转化
转换Gson 格式(因为上传时分Gson 和 RequestParams 格式)
所以:public static String getRequestBody(HttpServletRequest req)
throws IOException {
BufferedReader reader = req.getReader();
String input = null;
StringBuffer requestBody = new StringBuffer();
while ((input = reader.readLine()) != null) {
requestBody.append(input);
}
return requestBody.toString();
}
剩下的就是:
public void login1(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String logSql = "select * FROM usertable where username='" + name
+ "' and password='" + pass + "'";
// 获取DB对象
DBManager sql = new DBManager();
ResultSet rs = sql.executeQuery(logSql);
try {
if (rs.next()) {
data = "恭喜您,登录成功!";
} else {
data = "对不起,用户名、密码不符合!";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}