1.导入依赖包
2.basedao包
servlet:
package com.test.homework;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
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 com.alibaba.fastjson.JSON;
import com.test.dao.BaseDao;
import com.test.pojo.User;
import com.test.userdao.UserDao;
@WebServlet("/HwServlet")
public class HwServlet extends HttpServlet {
UserDao userdao = new UserDao();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
String method = req.getParameter("method");
try {
if ("toAjax".equals(method)) {
toAjax(req, resp);
} else if ("refresh".equals(method)) {
refresh(req, resp);
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void toAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException,
ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
// TODO Auto-generated method stub
List<User> list = userdao.selectAll();
req.setAttribute("list", list);
req.getRequestDispatcher("/WEB-INF/page/indexAJAX.jsp").forward(req, resp);
}
private void refresh(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
// TODO Auto-generated method stub
PrintWriter printWriter = resp.getWriter();
String id = req.getParameter("id");
User user = userdao.selectById(Integer.parseInt(id));
printWriter.append(JSON.toJSONString(user));
}
}
Ajax.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<<