星期二
import java.sql.*; public class Dao { public void add(User user) throws Exception { String url = "jdbc:mysql://localhost:3306/db2?characterEncoding=utf-8"; String username = "root"; String password = "1234"; Connection conn = DriverManager.getConnection(url, username, password); String sql = "INSERT INTO t_class(name,teachername,palce) values('" + user.getName() + "','" + user.getTeachername() + "','" + user.getPlace() + "')"; Statement stmt = conn.createStatement(); int count = stmt.executeUpdate(sql); System.out.println(count); stmt.close(); conn.close(); } public boolean check(User user) throws Exception { String url = "jdbc:mysql://localhost:3306/db2?characterEncoding=utf-8"; String username = "root"; String password = "1234"; Connection conn = DriverManager.getConnection(url, username, password); String sql= "select * from t_class"; boolean y=false; Statement stmt = conn.createStatement(); ResultSet rs=stmt.executeQuery(sql); while (rs.next()) { if((user.getTeachername()).equals(rs.getString(2))) y=true; } return y; } }
定义Dao类用JDBC连接数据库
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; @WebServlet("/Servlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; public LoginServlet() { super(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException{ req.setCharacterEncoding("utf-8"); String name = req.getParameter("name"); String teachername = req.getParameter("teachername"); String place = req.getParameter("place"); System.out.println(name); //调用用户属性类 User user = new User(name,teachername,place); //接受判断函数返回值 Dao dao =new Dao(); try { if(!dao.check(user)) try { dao.add(user); } catch (Exception e) { throw new RuntimeException(e); } else { resp.sendRedirect("/nosubmit.jsp"); } } catch (Exception e) { throw new RuntimeException(e); } resp.setContentType("text/html;charset=UTF-8"); resp.getWriter().println("<html>"); resp.getWriter().println("<head>"); resp.getWriter().println("<title>提交信息</title>"); resp.getWriter().println("</head>"); resp.getWriter().println("<body>"); resp.getWriter().println("成功"); resp.getWriter().println("</body>"); resp.getWriter().println("</html>"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
定义一个servlet用来处理jsp页面传来的数据
还有个User类和一个提交的jsp和提交失败的jsp
完成了用jsp页面导入数据到数据库了