本篇以数据库添加为例(本例中数据库名为“xinxi”表单名字为“stud”)
准备---实体层:
packageentity;
public classStudent {
privateString name;
privateString adress;
privateString qq;
public voidsetName(String name) {
this.name=name;
}
publicString getName() {
returnname;
}
public voidsetAdress(String adress) {
this.adress=adress;
}
publicString getAdress() {
returnadress;
}
public voidsetQq(String qq) {
this.qq=qq;
}
publicString getQq() {
returnqq;
}
publicStudent() {
}
publicStudent(String n,String a,String q) {
name=n;
adress=a;
qq=q;
}
}
准备---连接数据库:
packageutil;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;public classShujuku {public staticConnection 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连接失败!");
}returnconnection;
}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()方法)
packageservlet;import service.*;importjava.io.IOException;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;import entity.*;
@WebServlet("/StuServlet")public class StuServlet extendsHttpServlet {private static final long serialVersionUID = 1L;protected void service(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {//TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String method= request.getParameter("method");if(method.equals("add"))
{
add(request,response);
}
}
StuService ts=newStuService();private void add(HttpServletRequest req, HttpServletResponse resp)throwsServletException, 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的Booleanadd(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层方法)
packageservice;importdao.StuDao;importentity.Student;public classStuService {
StuDao sdao=newStuDao();public intadd(Student stu) {int f=0;if(!sdao.rename(stu.getName())) {
f=1;if(sdao.add(stu))
f=2;
}returnf;
}
}
①创建 add(Student stu){}方法,检验添加的准确性
②调用dao层后台程序方法rename()检验是否重名
if(!sdao.rename(stu.getName())) {//如果没有重复
sdao.add(stu);//添加
f=true;//返回真值
}
如图,直接在提示错误中点击创建方法即可
3. Dao(后台程序)
在这里编写所需的底层程序:
rename()//验证名字是否唯一
Add()//添加
public classStuDao {public booleanrename(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);
}returnf;
}public booleanadd(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;
}returnf;
}
}
4. Add.jsp
编写前端页面;
应用javascript验证客户端表单合法性。
Insert title hereObjectmessage=request.getAttribute("message");if(message!=null &&!"".equals(message)){%>
alert("");
信息录入
返回主页
保 存