1.修改学生信息
1.1实现jsp文件
类似添加下学生信息,需要一个跳转页面和修改页面,具体代码如下:
stu_list.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import ="java.util.*,student.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Stu_list</title>
</head>
<body>
<table border = "1">
<tr> <th>No.</th> <th>name</th> <th>sex</th><th>age</th><th>operation</th></tr>
<c:forEach items="${requestScope.stus}" var="stu">
<tr>
<td>${ stu.id }</td>
<td>${ stu.name }</td>
<td>${ stu.sex }</td>
<td>${ stu.age }</td>
<td><a href="${request.contextPath}/StuCour/StuUpdServlet?id=${stu.id}"> update</a> <a href="${request.contextPath}/StuCour/StuDelServlet?id=${stu.id}"> delete</a></td>
</tr>
</c:forEach>
</table>
<a href="${request.contextPath}/StuCour/StuAddServlet">insert student</a>
</body>
</html>
在新页面中,需要包含原本信息的显示,所以需要加上默认值,而对于单选框radio,还需要利用El表达式中的if语句进行判断默认值。
因为id是不可修改的,所以在新页面中,应该将id隐藏,注意不可将id信息删除,否则传递到Servlet文件中无id信息,就修改不了学生信息。
注意代码格式规范,多打或少打符号或空格,会导致代码语句的执行异常,例如<c:if test="${requestScope.stu.sex eq 'w'}">与<c:if test="${requestScope.stu.sex eq 'w'} ">只差了'w'}后的一个空格,但是后者是不执行的。
具体stu_upd.jsp代码如下:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Stu_upd</title>
</head>
<body>
<form action="${request.contextPath}/StuCour/StuUpdServlet" method="post">
<input type="hidden" name = "id" value ="${requestScope.stu.id}" >
name:<input type="text" name="name" value ="${requestScope.stu.name}"> <br>
sex:<input type="radio" name="sex" value="m" <c:if test="${requestScope.stu.sex eq 'm'}">checked</c:if> />m
<input type="radio" name="sex" value="w" <c:if test="${requestScope.stu.sex eq 'w'}">checked</c:if>>w <br>
age:<input type="text" name="age" value ="${requestScope.stu.age}"> <br>
<input type="submit">
<input type="reset">
</form>
</body>
</html>
1.2实现StuDaoImp文件中的listById()方法及update()方法
因为要想修改某一学生信息,就需要先得到该学生的信息,因此需要先写listById方法进行搜索,然后再实现修改,具体代码如下:
package student.dao.imp;
import java.util.ArrayList;
import java.util.List;
import java.sql.*;
import student.dao.StuDao;
import student.model.*;
public class StuDaoImp implements StuDao{
@Override
public List<Student> listAll() {
// TODO Auto-generated method stub
Connection con = null;
ArrayList <Student> stus = new ArrayList <Student> ();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/stucour" ,"root" ,"");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from student");
while(rs.next())
{
Student stu = new Student();
stu.setId(rs.getInt("id"));
stu.setName(rs.getString("name"));
stu.setSex(rs.getString("sex"));
stu.setAge(rs.getInt("age"));
stus.add(stu);
}
}catch(Exception e)
{
e.printStackTrace();
}
try {
con.close();
}catch (Exception e1) {
e1.printStackTrace();
}
return stus;
}
@Override
public Student listById(int id) {
// TODO Auto-generated method stub
Student stu = new Student();
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/stucour" ,"root" ,"");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from student where id="+id);
rs.next();
stu.setId(rs.getInt("id"));
stu.setName(rs.getString("name"));
stu.setSex(rs.getString("sex"));
stu.setAge(rs.getInt("age"));
}catch(Exception e)
{
e.printStackTrace();
}
try {
con.close();
}catch (Exception e1) {
e1.printStackTrace();
}
return stu;
}
@Override
public boolean save(Student stu) {
// TODO Auto-generated method stub
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/stucour" ,"root" ,"");
String sql = "insert into student values(?,?,?,?)";
PreparedStatement pst = con.prepareStatement(sql);
pst.setInt(1,stu.getId());
pst.setString(2,stu.getName());
pst.setString(3,stu.getSex());
pst.setInt(4,stu.getAge());
pst.execute();
return true;
}catch(Exception e)
{
e.printStackTrace();
return false;
}finally {
try{con.close();}
catch(Exception e1)
{
e1.printStackTrace();
}
}
}
@Override
public boolean update(Student stu) {
// TODO Auto-generated method stub
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/stucour" ,"root" ,"");
String sql = "update student set name=?,sex=?,age=? where id = ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setInt(4,stu.getId());
pst.setString(1,stu.getName());
pst.setString(2,stu.getSex());
pst.setInt(3,stu.getAge());
return pst.execute(); //不应该直接返回true,因为execute可能会返回false
}catch(Exception e)
{
e.printStackTrace();
return false;
}finally {
try{con.close();}
catch(Exception e1)
{
e1.printStackTrace();
}
}
}
@Override
public boolean del(int id) {
// TODO Auto-generated method stub
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/stucour" ,"root" ,"");
Statement st = con.createStatement();
st.execute("delete from student where id ="+id);
return true;
}catch(Exception e)
{
e.printStackTrace();
return false;
}finally {
try{con.close();}
catch(Exception e1)
{
e1.printStackTrace();
}
}
}
}
1.3实现StuService中的listById()方法及update()方法
调用StuDao的方法
具体代码如下:
package student.service.imp;
import java.util.List;
import student.dao.imp.StuDaoImp;
import student.dao.StuDao;
import student.model.Student;
import student.service.StuService;
public class StuServiceImp implements StuService{
StuDao stuDao = new StuDaoImp();
@Override
public List<Student> listAll() {
// TODO Auto-generated method stub
return stuDao.listAll();
}
@Override
public Student listById(int id) {
// TODO Auto-generated method stub
return stuDao.listById(id);
}
@Override
public boolean save(Student stu) {
// TODO Auto-generated method stub
return stuDao.save(stu);
}
@Override
public boolean update(Student stu) {
// TODO Auto-generated method stub
return stuDao.update(stu);
}
@Override
public boolean del(int id) {
// TODO Auto-generated method stub
return stuDao.del(id);
}
}
1.4实现StuDelServlet代码
doGet
读取id信息
按id查询信息
传递学生信息
实现页面的跳转
doPost
读取修改后的信息
实现信息修改
返回主界面
具体代码如下:
package student.controller;
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 student.model.Student;
import student.service.StuService;
import student.service.imp.StuServiceImp;
/**
* Servlet implementation class StuUpdateServlet
*/
@WebServlet("/StuUpdServlet")
public class StuUpdServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String id = request.getParameter("id");
StuService stuService = new StuServiceImp();
Student stu = stuService.listById(Integer.parseInt(id));
request.setAttribute("stu",stu);
request.getRequestDispatcher("student/stu_upd.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String id = req.getParameter("id");
String name = req.getParameter("name");
String sex = req.getParameter("sex");
String age = req.getParameter("age");
Student stu = new Student();
stu.setId(Integer.parseInt(id));
stu.setName(name);
stu.setSex(sex);
stu.setAge(Integer.parseInt(age));
StuService stuService = new StuServiceImp();
stuService.update(stu);
resp.sendRedirect("StuListServlet");
}
}
1.5执行结果
主界面:
进入update默认信息:
修改信息:
修改完成:
2.按条件查询
2.1查询要求
按输入学生信息查询,不输入即为默认值
具体形式如下:
2.2实现jsp文件
stu_list.jsp具体代码如下:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import ="java.util.*,student.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Stu_list</title>
</head>
<body>
<form action="${ request.contextPath }/StuCour/StuListServlet" method="post">
id:<input type="text" name="id" <c:if test="${ requestScope.stu.id ne -1}"> value="${ requestScope.stu.id }"</c:if> /><br />
name:<input type="text" name="name" value="${ requestScope.stu.name }"><br />
sex:<select name=sex>
<option value="" selected></option>
<option value="m" <c:if test="${ requestScope.stu.sex eq 'm'}">selected</c:if> >m</option>
<option value="w" <c:if test="${ requestScope.stu.sex eq 'w'}">selected </c:if> >w</option>
</select>
age:<input type="text" name="age" <c:if test="${ requestScope.stu.age ne -1}"> value="${ requestScope.stu.age }"</c:if>"><br />
<input type="submit" value="serach"/><input type="reset" />
</form>
<table border = "1">
<tr> <th>No.</th> <th>name</th> <th>sex</th><th>age</th><th>operation</th></tr>
<c:forEach items="${requestScope.stus}" var="stu">
<tr>
<td>${ stu.id }</td>
<td>${ stu.name }</td>
<td>${ stu.sex }</td>
<td>${ stu.age }</td>
<td><a href="${request.contextPath}/StuCour/StuUpdServlet?id=${stu.id}"> update</a> <a href="${request.contextPath}/StuCour/StuDelServlet?id=${stu.id}"> delete</a></td>
</tr>
</c:forEach>
</table>
<a href="${request.contextPath}/StuCour/StuAddServlet">insert student</a>
</body>
</html>
2.3实现StuDaoImp文件中的list()方法
先前并没写该方法,需要在StuDao接口中自行添加,StuDaoImp‘内list方法具体代码如下:
@Override
public List<Student> list(Student stu) {
// TODO Auto-generated method stub
Connection con = null;
ArrayList <Student> stus = new ArrayList <Student> ();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/stucour" , "root" , "");
Statement st = con.createStatement();
String sql = "select * from student where 1=1";
int id = stu.getId();
String name = stu.getName();
String sex = stu.getSex();
int age = stu.getAge();
if( id != -1 ) {
sql = sql + " and id=" + id;
}
if(name != null && !name.equals("")) {
sql = sql + " and name like '%" + name + "%'";
}
if(sex != null && !sex.equals("")) {
sql = sql + " and sex ='" + sex + "'";
}
if( age != -1 ) {
sql = sql + " and age=" + age;
}
ResultSet rs = st.executeQuery(sql);
while( rs.next() ) {
Student stu1 = new Student();
stu1.setId( rs.getInt("id") );
stu1.setName( rs.getString("name") );
stu1.setSex( rs.getString("sex") );
stu1.setAge( rs.getInt("age") );
stus.add(stu1);
}
}catch(Exception e) {
e.printStackTrace();
}
try {
con.close();
}
catch(Exception e1) {
e1.printStackTrace();
}
return stus;
}
2.4实现StuServiceImp文件中的list()方法
具体代码如下:
@Override
public List<Student> list(Student stu) {
// TODO Auto-generated method stub
return stuDao.list(stu);
}
2.5实现StuListServlet代码
doPost
接收填写的学生数据
执行list方法
传回数据
具体代码如下:
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String id = request.getParameter("id").trim();
String name = request.getParameter("name").trim();
String sex = request.getParameter("sex").trim();
String age = request.getParameter("age").trim();
Student stu = new Student();
if(id != null && !id.equals(""))stu.setId( Integer.parseInt(id) );
if(name != null && !name.equals(""))stu.setName( name );
if(sex != null && !sex.equals(""))stu.setSex( sex );
if(age != null && !age.equals(""))stu.setAge( Integer.parseInt(age) );
StuService stuService = new StuServiceImp();
List <Student> stus = stuService.list(stu);
request.setAttribute("stu", stu);
request.setAttribute("stus", stus);
request.getRequestDispatcher("student/stu_list.jsp").forward(request, response);
}
3.debug注意事项
在发现运行结果不理想时,应注意是哪块的异常,通过System.out.println()打印信息,观察打印信息是否异常,可以大致判断是哪块的异常,然后再进行仔细修改。
4.作业
实现Course模块,功能与Student模块类似,包含属性为id,name,teacher