不用框架写一个web后端Demo(>.<)
2019-10-23 本文已影响0人
HeloWxl
前言
使用的是比较原始的方法写一个web后端Demo.
简单介绍一下:
后端操作数据库使用的是BaseDao,后端接口用的是Servlet。
基本功能:增删改查
工具:IDEA、MySQL、Jdk1.8、Postman
项目结构截图
项目结构.png数据库
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(10) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`sex` varchar(10) DEFAULT NULL COMMENT '性别',
`school` varchar(20) DEFAULT NULL COMMENT '学校',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COMMENT='学生信息表--测试';
BaseDao
BaseDao代码稍微有点长....
public abstract class BaseDao<T> {
public final String dirver = "com.mysql.jdbc.Driver";
public final String name = "root";
public final String pass = "123456";
public final String url = "jdbc:mysql://localhost:3306/student";
Class<T> clazz;
//反射获得clazz
@SuppressWarnings("unchecked")
public BaseDao() {
clazz = (Class<T>) ((ParameterizedType) this.getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
// DQL 带参数的查询
public List<T> executeQuery(String sql, Object[] obj) {
Connection conn = null;
PreparedStatement stat = null;
ResultSet rs = null;
List<T> list = new ArrayList<T>();
try {
conn = createConn();
// 3、创建传输对象statmemnt
stat = conn.prepareStatement(sql);// ?不确定:类型、数量
// 3+、绑定替换数据
for (int i = 0; i < obj.length; i++) {
stat.setObject(i + 1, obj[i]);
}
// 4、发送sql语句,并且接收返回结果 : DML -> executeUpdate ; DQL -> executeQuery
rs = stat.executeQuery();
// 5、如果返回rs类型的数据,需要将数据转换成list
ResultSetMetaData rsmd = rs.getMetaData();//列名信息
int columuCount = rsmd.getColumnCount();//列的数量
while (rs.next()) {
T t = (T) clazz.newInstance();//创建对象
for (int i = 0; i < columuCount; i++) {//封装数据
Field f = clazz.getDeclaredField(rsmd.getColumnName(i + 1));//列名->属性名->属性对象
f.setAccessible(true);
f.set(t, rs.getObject(i + 1));//将rs列中的值赋给属性
}
list.add(t);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAll(rs, stat, conn);
}
return list;
}
// 关闭一切
public void closeAll(ResultSet rs, Statement stat, Connection conn) {
// 6、关闭一切
try {
if (rs != null)
rs.close();
if (stat != null)
stat.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// DML 增删改
public int executeUpdate(String sql, Object[] obj) {
Connection conn = null;
PreparedStatement stat = null;
int ret = 0;
try {
conn = createConn();
// 3、创建传输对象statmemnt
stat = conn.prepareStatement(sql);// ?不确定:类型、数量
// 3+、绑定替换数据
for (int i = 0; i < obj.length; i++) {
stat.setObject(i + 1, obj[i]);
}
// 4、发送sql语句,并且接收返回结果 : DML -> executeUpdate ; DQL -> executeQuery
ret = stat.executeUpdate();
// 5、如果返回rs类型的数据,需要将数据转换成list
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAll(stat, conn);
}
return ret;
}
// 创建连接
public Connection createConn() {
Connection conn = null;
try {
// 1、加载驱动
Class.forName(dirver);
// 2、创建连接connection
conn = DriverManager.getConnection(url, name, pass);
System.out.println("数据库连接成功!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("数据库连接失败!");
}
return conn;
}
// 关闭一切
public void closeAll(Statement stat, Connection conn) {
// 6、关闭一切
try {
if (stat != null)
stat.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// DQL 不带参数查询
protected List<T> executeQuery(String sql) {
Connection conn = null;
PreparedStatement stat = null;
ResultSet rs = null;
List<T> list = new ArrayList<T>();
try {
conn = createConn();
// 3、创建传输对象statmemnt
stat = conn.prepareStatement(sql);// ?不确定:类型、数量
// 3+、绑定替换数据
// 4、发送sql语句,并且接收返回结果 : DML -> executeUpdate ; DQL -> executeQuery
rs = stat.executeQuery();
// 5、如果返回rs类型的数据,需要将数据转换成list
ResultSetMetaData rsmd = rs.getMetaData();//列名信息
int columuCount = rsmd.getColumnCount();//列的数量
while (rs.next()) {
T t = (T) clazz.newInstance();//创建对象
for (int i = 0; i < columuCount; i++) {//封装数据
try {
Field f = clazz.getDeclaredField(rsmd.getColumnName(i + 1));//列名->属性名->属性对象
f.setAccessible(true);
f.set(t, rs.getObject(i + 1));//将rs列中的值赋给属性
} catch (Exception e) {
System.out.println("对象中没有该属性:" + rsmd.getColumnName(i + 1));
}
}
list.add(t);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAll(rs, stat, conn);
}
return list;
}
// DQL
protected int getRecordCount(String sql) {//select count(*) from msg;
Connection conn = null;
PreparedStatement stat = null;
ResultSet rs = null;
int count = 0;
try {
conn = createConn();
// 3、创建传输对象statmemnt
stat = conn.prepareStatement(sql);// ?不确定:类型、数量
// 3+、绑定替换数据
// 4、发送sql语句,并且接收返回结果 : DML -> executeUpdate ; DQL -> executeQuery
rs = stat.executeQuery();
// 5、如果返回rs类型的数据,需要将数据转换成list
if (rs.next()) {
count = rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAll(rs, stat, conn);
}
return count;
}
}
StudentDao
public interface StudentDao {
/**
* 获取所有的学生
* @return
*/
List<Student> getAllStudent();
/**
* 添加学生
* @param student
* @return
*/
int insertStudent(Student student);
/**
* 根据id删除学生
* @param id
* @return
*/
int deleteStudentById(Integer id);
/**
* 根据id修改学生信息
* @param student
* @return
*/
int updateStudentById(Student student);
/**
* 获取学生总数
* @return
*/
int getStudentCount();
}
StudentDaoImpl
/**
* @author wangxl
* @ClassName StudentDaoImpl
* @Description TODO
* @date 2019/10/23 10:50
*/
public class StudentDaoImpl extends BaseDao<Student> implements StudentDao {
@Override
public List<Student> getAllStudent() {
String sql = "select * from student";
return executeQuery(sql);
}
@Override
public int insertStudent(Student student) {
String sql = "insert into student(name,age,sex,school) values(?,?,?,?)";
return executeUpdate(sql,new Object[]{student.getName(),student.getAge(),student.getSex(),student.getSchool()});
}
@Override
public int deleteStudentById(Integer id) {
String sql = "delete from student where id = ?";
return executeUpdate(sql,new Object[]{id});
}
@Override
public int updateStudentById(Student student) {
String sql = "update student set name = ? , age = ? ,sex = ? ,school = ? where id = ?";
return executeUpdate(sql,new Object[]{student.getName(),student.getAge(),student.getSex(),student.getSchool(),student.getId()});
}
@Override
public int getStudentCount() {
String sql = "select count(*) from student";
return getRecordCount(sql);
}
}
查询 GetAllStudentServlet
@WebServlet("/getAllStudent")
public class GetAllStudentServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//返回结果
Map<String,Object> map = new HashMap<>();
StudentDao studentDao = new StudentDaoImpl();
List<Student> list = studentDao.getAllStudent();
if(list.size()>=0){
map.put("code",200);
map.put("msg","返回结果成功");
map.put("data",list);
map.put("count",studentDao.getStudentCount());
}else{
map.put("code",500);
map.put("msg","返回结果成失败");
map.put("data",null);
}
JSONObject json = JSONObject.fromObject(map);
PrintWriter out = response.getWriter();
out.print(json.toString());
out.flush();
out.close();
}
}
第一次查询结果.png
出现了乱码???
别慌!
我们在GetAllStudentServlet.java里面加上这一句,就OK了。或者写一个字符过滤器就好了。
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
再查询一次!
第二次查询结果.png
删除 DeleteStudentByIdServlet
@WebServlet("/deleteStudentById")
public class DeleteStudentByIdServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//字符过滤
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//返回结果
Map<String,Object> map = new HashMap<>();
//获取传入的参数
String id = request.getParameter("id");
StudentDao studentDao = new StudentDaoImpl();
int result = studentDao.deleteStudentById(Integer.parseInt(id));
if(result==1){
map.put("code",200);
map.put("msg","删除成功");
map.put("data",result);
}else{
map.put("code",500);
map.put("msg","删除失败");
map.put("data",result);
}
JSONObject json = JSONObject.fromObject(map);
PrintWriter out = response.getWriter();
out.print(json);
out.flush();
out.close();
}
}
删除.png
修改 UpdateStudentServlet
@WebServlet("/updateStudent")
public class UpdateStudentServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//字符过滤
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//返回结果
Map<String,Object> map = new HashMap<>();
Student student = new Student();
//获取传入的参数
String id =request.getParameter("id");
String name =request.getParameter("name");
String age =request.getParameter("age");
String sex =request.getParameter("sex");
String school =request.getParameter("school");
//给对象赋值
student.setAge(Integer.parseInt(age));
student.setName(name);
student.setSchool(school);
student.setSex(sex);
student.setId(Integer.parseInt(id));
StudentDao studentDao = new StudentDaoImpl();
int result = studentDao.updateStudentById(student);
if(result==1){
map.put("code",200);
map.put("msg","修改成功");
map.put("data",result);
}else{
map.put("code",500);
map.put("msg","修改失败");
map.put("data",result);
}
//封装成json
JSONObject json = JSONObject.fromObject(map);
PrintWriter out = response.getWriter();
out.print(json);
out.flush();
out.close();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doPost(request,response);
}
}
修改.png
修改完后,去数据库瞄了一眼,结果:哦吼,完蛋!!
修改后的数据库.png
解决办法:
就是在你的tomcat的conf下面的server.xml修改即可。
useBodyEncodingForURI="true" URIEncoding="UTF-8"
修改位置.png
添加 insertStudenServlet
@WebServlet("/insertStudent")
public class insertStudenServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//字符过滤
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//返回结果
Map<String,Object> map = new HashMap<>();
Student student = new Student();
//获取传入的参数
String name =request.getParameter("name");
String age =request.getParameter("age");
String sex =request.getParameter("sex");
String school =request.getParameter("school");
//给对象赋值
student.setAge(Integer.parseInt(age));
student.setName(name);
student.setSchool(school);
student.setSex(sex);
StudentDao studentDao = new StudentDaoImpl();
int result = studentDao.insertStudent(student);
if(result==1){
map.put("code",200);
map.put("msg","添加成功");
map.put("data",result);
}else{
map.put("code",500);
map.put("msg","添加失败");
map.put("data",result);
}
//封装成json
JSONObject json = JSONObject.fromObject(map);
PrintWriter out = response.getWriter();
out.print(json);
out.flush();
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doPost(request,response);
}
}
添加.png