servlet jsp一套完整的增删查改思路

来源:互联网 发布:死寂木偶比利淘宝 编辑:程序博客网 时间:2024/05/22 06:55

小弟刚刚学了servlet.然后就用servlet写了一套小的增删查改,写出来做一个笔记,当然能帮助更多初学者解惑更好,由于是初学,肯定还有很多地方不足和缺陷,希望大家帮我指出来,一起讨论,牛大哥请多指教!

写增查删改步骤:
注:很多servlet我都改映射了 mapping
写之前的连接数据库准备以及如何创建项目:
1:先设计需求(学号,姓名,性别,....)学号一般用序列;
设计数据库
2:创建eclipse的Dynamic Web Project项目(动态Web项目);
3:导入oracle的JDBC jar包(存放目录:D:\app\Administrator\product\11.2.0\dbhome_1\jdbc\lib下的


ojdbc6.jar)然后放在刚才创建的动态Web项目下的WebContent文件夹下的WEB-INF下的lib文件夹里,放进去后Web 


App Libraries会自动生成一个ojdbc6.jar的jar包;
4:以上步骤进行完后开始写代码.


1):增加:
1:先在WebContent文件夹下创建jsp文件,用来写一个显示表单以便于录入信息
如下:
<body>
<form action="StudentAddServlet" method="post">
<table>
<tr>
<td>姓名</td>
<td><input type="text" name="STUNAME"></td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" name="sex" value="0">女
<input type="radio" name="sex" value="1">男
</td>
</tr>
<tr>
<td>生日</td>
<td><input type="type" name="birth"></td>
</tr>
<tr>
<td>专业</td>
<td><select name="PROFESSIONAL">
<option value="1">11111111</option>
<option value="2">22222222</option>
<option value="3">33333333</option>
</select>

</td>
</tr>
<tr>
<td>爱好</td>
<td>
<input type="checkbox" name="love" value="上刀山">上刀山
<input type="checkbox" name="love" value="下火海">下火海
</td>
</tr>
<tr>
<td>个人说明</td>
<td><textarea rows="5" cols="30"  name="memo"></textarea></td>
</tr>
<tr >
<td colspan="2">
<input type="submit" value="提交">
<input type="reset" value="重置">
</td>
</tr>

</table>
</form>
2:再写一个Student类,然后封装,(set,get方法),
3连接数据库DBUtil
4:写一个增方法,传参,传入一个对象,(因为下一步要用servlet获得的数据往Student类里面set数据,然后传入对象,


直接get出来就是jsp传过来的数据);
代码如下:
public Integer Add(Student stu){
DBUtil dbu=new DBUtil();
String sql="insert into SERSTUDENT(STUID,STUNAME,SEX,BIRTH,PROFESSIONAL,LOVE,MEMO) 


values(SER_STU.NEXTVAL,?,?,?,?,?,?)";
try {
PreparedStatement pstmt=dbu.getConn().prepareStatement(sql);
pstmt.setString(1, stu.getStuName());
pstmt.setInt(2, stu.getSex());
pstmt.setString(3, null);
pstmt.setString(4, stu.getProfessional());
pstmt.setString(5, stu.getLove());
pstmt.setString(6, stu.getMemo());
return pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
5:写一个Servlet类,用servlet把jsp写的name用request.parameter("name")方法获取出来:如:String 


stuName=request.getParameter("STUNAME");
然后先实例化一个Student对象stu,用stu.setXXX方法往对应的变量里set值,然后把这个对象传到增方法里


studentdao.Add(stu),上一步Add方法是需要传参数的,所以这里直接传入一个对象,这样set进去的值就传到add方法


里了,add直接get出来就可以用,具体代码如下:protected void doPost(HttpServletRequest request, 


HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String stuName=request.getParameter("STUNAME");
String Sex=request.getParameter("sex");
String Birth=request.getParameter("birth");
String Professional=request.getParameter("PROFESSIONAL");
String[] Love=request.getParameterValues("love");//love是爱好,由于爱好的值是CheckBox,


复选框,所以要获取一个数组;
String Memo=request.getParameter("memo");
Student stu=new Student();
stu.setStuName(stuName);
stu.setSex(Integer.parseInt(Sex));
stu.setBirth(Birth);
stu.setProfessional(Professional);
StringBuffer stringbuffer=new StringBuffer();
for (String string : Love) {//把这个数组用StringBuffer遍历出来;
stringbuffer.append(string).append(",");
}
stu.setLove(stringbuffer.toString());
stu.setMemo(Memo);
StudentDao studentdao=new StudentDao();//这是类的名字,先实例化对象;
studentdao.Add(stu);//然后调用实例化的方法.Add;
response.sendRedirect("StudentListServlet");//代码执行完后会跳转到查询详细信息的列



}
注:response.sendRedirect("StudentListServlet");是一个跳转方法,就是执行完后会跳转到StudentListServlet,


由于现在暂时还没有写到查询表,所以这个时候会404,也就是找不到页面.
一个增的功能基本实现了.接下来就是实现查询的功能.


2):查询,查询就是把值从数据库里取出来,在一个table表格里面显示出来,思路:把从数据库里遍历出来,然后


把"Student" new一个对象,这个对象也得放在ResultSet.next()方法里遍历,这时候每完成一个学生的遍历就会把一


个学生new一个对象,把这些对象放到一个List里面,然后把这个List放到jsp页面写好的table里面遍历出来,然后一


个查询表格就展出来了.具体如下:
1:先写一个查询的方法,返回一个数组,以便于下面用数组接收这个方法返回的数组,具体代码如下:
public List<Student> list(Student student){
List<Student> list=new ArrayList<Student>();
DBUtil dbu=new DBUtil();
String sql="select * from SERSTUDENT";
try {
PreparedStatement pstate=dbu.getConn().prepareStatement(sql);
ResultSet rs = pstate.executeQuery();

while(rs.next()){
Student stu =new Student();
try {
stu.setStuId(rs.getString(1));
stu.setStuName(rs.getString(2));
stu.setSex(rs.getInt(3));
stu.setBirth(rs.getString(4));
stu.setProfessional(rs.getString(5));
stu.setLove(rs.getString(6));
stu.setMemo(rs.getString(7));
list.add(stu);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;

}
2:然后写一个Servlet,先把上面的对象实例化,然后调用list方法,由于我们的list方法是返回一个List数组,所以我


们调用这个方法的时候需要写new一个list接收,然后把接收到的list用request.setAtttibute("list",list) name


为"list",value为list,然后我们把这个list用getRequestDispatcher("index.jsp")跳转到需要展示的jsp页面,(暂


时没有写,下一步就写)用forward方法转发(request, response).代码如下:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws 


ServletException, IOException {
StudentDao studentdao=new StudentDao();
List<Student> list=studentdao.list(null);//因为上一步我写的list方法需要传参,但是现在


用不到传参,就传个null;
request.setAttribute("list", list);
request.getRequestDispatcher("index.jsp").forward(request, response);
}


3:写一个展示页面,index.jsp把刚才setAttribute的list用list接收出来List<Student> list=(List<Student>)


request.getAttribute("list"),然后遍历出来foreach for(Student Student:list),具体代码如下:
<body>
<a href="Students.jsp">添加</a>
<table border="1">


<tr>
<th>学号</th>
<th>姓名</th>
<th>性别</th>
<th>生日</th>
<th>专业</th>
<th>爱好</th>
<th>个人说明</th>
</tr>
<%
List <Student> list=(List <Student>)request.getAttribute("list");
for(Student student:list){
%>
<tr>
<td><%=student.getStuId() %></td>
<td><%=student.getStuName() %></td> 
<td><%=student.getSex() %></td>
<td><%=student.getBirth()%></td>
<td><%=student.getProfessional()%></td>
<td><%=student.getLove() %></td>
<td><%=student.getMemo() %></td>
</tr>
<% }%>
</table>
</body>




3)删,
1:删除就是在数据查询出来后,根据数据的唯一键的value进行删除,因为SQL语句结构是:"selete 表 where 唯一键


=?"又因为学号是序列,所以把学号设置成唯一键,删的时候就where学号
2:因为上一步已经把学号遍历出来了,所以在后面加一个往sevelet传stuId的值的跳转链接就能顺利取到我们SQL需


要用到where唯一键=?,也就是where stuId=? 
3:先写一个删除方法:传入一个对象参数,主要是用这个对象的getStuId的值;
public Integer delete(Student student){
DBUtil dbu=new DBUtil();

String sql="delete SERSTUDENT where stuId=?";
try {
PreparedStatement pstmt=dbu.getConn().prepareStatement(sql);
pstmt.setString(1,student.getStuId());
return pstmt.executeUpdate();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
4:这时候我们还得从表格里把stuId传到删除方法里面然后就能正常删除了,也就是在刚才的查询的表里加一个操作,


删除和修改,点击删除的时候就传到servlet里stuId值
5:也就是在后面加一个<td><a href="Delete?stuId=student.getStuId()">删除</a></td>
6:写一个servlet 先把stuId的值接收过来,用request.getAttribute("stuId");方法接收,然后先实例化对


象,StudentDao studentdao=new StudentDao();然后把获得的stuId的值set到Student类里面,
然后调用studentdao.delete("Student类"),就能删除了
7:但是这样操作不太友好,没有提示,不能防止误操作,所以我们写一个小脚本,在脚本里传参进行删除:
<Script type="text/javascript">
function del(stuId){
if(confirm("确定要删除吗?")){
Window.location.href="Delete?stuId"+stuId//重定向到"Delete"传值为 "stuId" 值为传入的产参数


stuId
}
}
</Script>
然后下面直接调用函数<a JavaScript:del(<%=student.getStuId()%>)">
6:具体代码如下:
<html>


<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>详细信息</title>
<script type="text/javascript">
function del(stuId){
if(confirm("确定要删除吗?")){//这个是提示窗口,确定要删除吗?点击是就删除了,点击否就取消了.
window.location.href="Delect?stuId="+stuId;
}
}
</script>
</head>
<body>
<a href="Students.jsp">添加</a>
<table border="1">


<tr>
<th>学号</th>
<th>姓名</th>
<th>性别</th>
<th>生日</th>
<th>专业</th>
<th>爱好</th>
<th>个人说明</th>
<th>操作</th>
</tr>
<%/* StudentDao studentdao=new StudentDao();
List<Student> list=studentdao.list(null); */
List <Student> list=(List <Student>)request.getAttribute("list");
for(Student student:list){
%>
<tr>
<td><%=student.getStuId() %></td>
<td><%=student.getStuName() %></td> 
<td><%=student.getSex() %></td>
<td><%=student.getBirth()%></td>
<td><%=student.getProfessional()%></td>
<td><%=student.getLove() %></td>
<td><%=student.getMemo() %></td>
<td><a href="Javascript:del(<%=student.getStuId()%>)">删除</a>|<a href="Update?stuId=<


%=student.getStuId()%>&method=select">修改</td>
</tr>
<% }%>
</table>
</body>
</html>




4):修改:

1:修改也是先在查询的jsp表格里插入一个操作,上面的代码里已经插入了.
2:我们得写一个修改的页面表单,跟添加数据的表单页面差不多,但是得用value把表单都赋值,赋需要修改的所有属


性,也就是单条查询数据,然后把查询到的数据传到到Update.jsp的修改表单里.
jsp表单代码如下:
<form action="" method=post>
<table>
<tr>
<td>姓名</td>
<td>
<input type="hidden" name="stuId" value="<%=stu.getStuId()%>">
<input type="text" name="STUNAME" value="<%=stu.getStuName() %>" >
</td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" name="sex" value="0" <%if(0==stu.getSex())


{out.print("checked"); } %>>女
<input type="radio" name="sex" value="1" <%if(1==stu.getSex())


{out.print("checked"); } %>>男
</td>
</tr>
<tr>
<td>生日</td>
<td><input type="text" name="birth"></td>
</tr>
<tr>
<td>专业</td>
<td><select name="PROFESSIONAL">
<option value="1" <%if("1".equals(stu.getProfessional()))


{out.print("checked");} %>>11111111</option>
<option value="2" <%if("2".equals(stu.getProfessional()))


{out.print("checked");} %>>22222222</option>
<option value="3" <%if("3".equals(stu.getProfessional()))


{out.print("checked");} %>>33333333</option>
</select>

</td>
</tr>
<tr>
<td>爱好</td>
<td>
<input type="checkbox" name="love" value="上刀山">上刀山
<input type="checkbox" name="love" value="下火海">下火海
</td>
</tr>
<tr>
<td>个人说明</td>
<td><textarea rows="5" cols="30"  name="memo"></textarea></td>
</tr>
<tr >
<td colspan="2">
<input type="submit" value="提交">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
3:再写一个单条查询的方法queryById(String stuId);
代码如下:
public Student queryById(String stuId){
DBUtil dbu=new DBUtil();
Student stu =new Student();
String sql="select * from SERSTUDENT where stuId=?";
try {
PreparedStatement pstate=dbu.getConn().prepareStatement(sql);
pstate.setString(1, stuId);
ResultSet rs = pstate.executeQuery();
while(rs.next()){
try {
stu.setStuId(rs.getString(1));
stu.setStuName(rs.getString(2));
stu.setSex(rs.getInt(3));
stu.setBirth(rs.getString(4));
stu.setProfessional(rs.getString(5));
stu.setLove(rs.getString(6));
stu.setMemo(rs.getString(7));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stu;

}
4:再写一个servletUpdate类
{
String stuId=request.getParameter("stuId");


StudentDao studao=new StudentDao();
Student stu= studao.queryById(stuId);
request.setAttribute("stu", stu);
request.getRequestDispatcher("Update.jsp").forward(request,response);
}
5:上面的修改按钮已经写过了"<a href="Update?stuId=<%=student.getStuId()%>&method=select">"然后点击查询


表的修改按钮就会把stuId的值传到单条查询方法里,然后request.getRequestDispatcher("Update.jsp").forward


(request,response)就会跳转到Update.jsp即把值传到了表里,然后可以重新写表单的值,点提交再提交到


action="Update?method=update"处理,这个处理就是修改数据库查出来的单条数据,action="Update?


method=update" 这句是往Updateservlet再传入一个名字为method,值为update的变量,然后在servlet里if


("update".equals(method))就执行修改,else if("select".equals(method))就执行查询方法
6:修改方法:
public Integer Update(Student stu){
DBUtil dbu=new DBUtil();
String sql="update SERSTUDENT set 


STUNAME=?,SEX=?,BIRTH=?,PROFESSIONAL=?,LOVE=?,MEMO=? where STUID=?" ;
try {
PreparedStatement pstmt=dbu.getConn().prepareStatement(sql);
pstmt.setString(1, stu.getStuName());
pstmt.setInt(2, stu.getSex());
pstmt.setString(3, null);
pstmt.setString(4, stu.getProfessional());
pstmt.setString(5, stu.getLove());
pstmt.setString(6, stu.getMemo());
pstmt.setString(7, stu.getStuId());
return pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
7:servlet代码如下:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws 


ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String method=request.getParameter("method");
if("update".equals(method)){

String stuId=request.getParameter("stuId");
String stuName=request.getParameter("STUNAME");
String Sex=request.getParameter("sex");
String Birth=request.getParameter("birth");
String Professional=request.getParameter("PROFESSIONAL");
String[] Love=request.getParameterValues("love");
String Memo=request.getParameter("memo");
System.out.println("if"+stuId);
Student stu=new Student();
stu.setStuId(stuId);
stu.setStuName(stuName);
stu.setSex(Integer.parseInt(Sex));
stu.setBirth(Birth);
stu.setProfessional(Professional);
StringBuffer stringbuffer=new StringBuffer();
for (String string : Love) {
stringbuffer.append(string).append(",");
}
stu.setLove(stringbuffer.toString());
stu.setMemo(Memo);
StudentDao studentdao=new StudentDao();
studentdao.Update(stu);
response.sendRedirect("StudentListServlet");
}
else if("select".equals(method)){
String stuId=request.getParameter("stuId");


StudentDao studao=new StudentDao();
Student stu= studao.queryById(stuId);
request.setAttribute("stu", stu);
request.getRequestDispatcher("Update.jsp").forward(request,response);
}
}
}