本篇以数据库添加为例(本例中数据库名为“xinxi”表单名字为“stud”)
准备---实体层:
package entity; public class Student { private String name; private String adress; private String qq; public void setName(String name) { this.name=name; } public String getName() { return name; } public void setAdress(String adress) { this.adress=adress; } public String getAdress() { return adress; } public void setQq(String qq) { this.qq=qq; } public String getQq() { return qq; } public Student() { } public Student(String n,String a,String q) { name=n; adress=a; qq=q; } }
准备---连接数据库:
package util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Shujuku { public static Connection conn(){ String url="jdbc:sqlserver://localhost:1433;DatabaseName=xinxi";//填写你的数据库名 String userName="sa";//填写你的用户名,我的是sa String userPwd="********";//填写你的密码 Connection connection=null; try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); System.out.println("加载驱动成功!"); }catch(Exception e){ e.printStackTrace(); System.out.println("加载驱动失败!"); } try{ connection=DriverManager.getConnection(url,userName,userPwd); System.out.println("连接数据库成功!"); }catch(Exception e){ e.printStackTrace(); System.out.print("SQL Server连接失败!"); } return connection; } public static void close (Statement state, Connection conn) {//关闭 if (state != null) { try { state.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close (ResultSet rs, Statement state, Connection conn) {//关闭 if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (state != null) { try { state.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
1.servlet(首先StuService ts=new StuService();//新建service实体对象,以便后来调用service中add()方法)
package servlet; import service.*; import java.io.IOException; 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 entity.*; @WebServlet("/StuServlet") public class StuServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); String method = request.getParameter("method"); if(method.equals("add")) { add(request,response); } } StuService ts=new StuService(); private void add(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException { req.setCharacterEncoding("utf-8"); String name = req.getParameter("name");//从jsp中获取参数name String adress=req.getParameter("adress"); String qq=req.getParameter("qq"); Student stu=new Student(name,adress,qq);//新建 int k=ts.add(stu); if(k==2) { req.setAttribute("message", "添加成功");//setAttribute方法用于将内容保存在对象中,传到add.jsp中 req.getRequestDispatcher("add.jsp").forward(req,resp);//getRequestDispatcher方法用于进入下一个页面 } if(k==0) { req.setAttribute("message", "重复,请重新录入"); req.getRequestDispatcher("add.jsp").forward(req,resp); } if(k==1) { req.setAttribute("message", "数据库添加失败"); req.getRequestDispatcher("add.jsp").forward(req,resp); } } }
①创建方法add(),Servlet从jsp中获取参数,新建实体对象Student stu=new Student(name,adress,qq);
②调用service层,检验添加的准确性
StuService ts=new StuService();//新建service对象
if(ts.add(stu)){
//如果service对象ts的Boolean add(stu)方法返回真值true,页面要显示添加成功
//req.setAttribute("message", "添加成功");将"添加成功"内容保存在req对象参数message中,传递给add.jsp
//req.getRequestDispatcher("add.jsp").forward(req,resp);进入下一个界面(这里是add.jsp)
}
else{
//收到返回值为false,添加失败
//将 "重复,请重新录入"内容保存在req对象参数message中,传递给add.jsp
//进入下一个界面(这里是add.jsp)
}
2. Service(新建dao实体对象,后面要调用dao层方法)
package service; import dao.StuDao; import entity.Student; public class StuService { StuDao sdao=new StuDao(); public int add(Student stu) { int f=0; if(!sdao.rename(stu.getName())) { f=1; if(sdao.add(stu)) f=2; } return f; } }
①创建 add(Student stu){}方法,检验添加的准确性
②调用dao层后台程序方法rename()检验是否重名
if(!sdao.rename(stu.getName())) {//如果没有重复
sdao.add(stu);//添加
f=true;//返回真值
}
如图,直接在提示错误中点击创建方法即可
3. Dao(后台程序)
在这里编写所需的底层程序:
rename()//验证名字是否唯一
Add()//添加
public class StuDao { public boolean rename(String name) { // 检验名字是否重复 boolean f=false; String sql="select name from stud where name=‘"+name+"‘";//数据库语句,查询界面输入和表stud中name是否重复 Connection conn = Shujuku.conn();//创建连接 Statement state = null;//建立Statement对象,执行静态SQL语句 ResultSet rs = null;//ResultSet对象 是查询数据库时的返回对象,读取返回结果集 try { state = conn.createStatement(); rs = state.executeQuery(sql); while (rs.next()) {//不重复,返回true f = true; } } catch (SQLException e) { e.printStackTrace(); } finally { Shujuku.close(rs, state, conn); } return f; } public boolean add(Student stu) { //添加 String sql = "insert into stud(name,adress,qq) values(‘" +stu.getName() + "‘,‘" + stu.getAdress() + "‘,‘" + stu.getQq() + "‘)"; Connection conn = Shujuku.conn(); Statement state = null; boolean f = false; int a=0; try { state = conn.createStatement(); a=state.executeUpdate(sql);//添加 } catch (Exception e) { e.printStackTrace(); } finally { Shujuku.close(state, conn); } if (a > 0) { f = true; } return f; } }
4. Add.jsp
编写前端页面;
应用javascript验证客户端表单合法性。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% Object message = request.getAttribute("message"); if(message!=null && !"".equals(message)){ %> <script type="text/javascript"> alert("<%=request.getAttribute("message")%>"); </script> <%} %> <div align="center"> <h1 style="color: red;">信息录入</h1> <a href="index.jsp">返回主页</a> <form action="StuServlet?method=add" method="post" onsubmit="return check()"> <div > 姓名<input type="text" id="name" name="name"/> </div> <div > 联系方式<input type="text" id="qq" name="qq" /> </div> <div > 地址<input type="text" id="adress" name="adress" /> </div> <div > <button type="submit" >保 存</button> </div> </form> </div> <script type="text/javascript"> function check() { var name = document.getElementById("name");; var qq = document.getElementById("qq"); var adress = document.getElementById("adress"); //非空 if(name.value == ‘‘) { alert(‘名字为空‘); name.focus(); return false; } if(qq.value == ‘‘) { alert(‘联系方式为空‘); qq.focus(); return false; } if(adress.value == ‘‘) { alert(‘地址为空‘); adress.focus(); return false; } } </script> </body> </html>
原文地址:https://www.cnblogs.com/sengzhao666/p/10181806.html