这章主要讲解JDBC与web层的嵌套,后台与前台的结合。后台依旧使用JDBC进行详细描述,前台主要是基本的显示界面问题。结合servlet请求回应完成测试系统的编写。
1 普通的表单提交就是单纯的字段提交,这个可以直接采用普通的表单提交方式;也就是:
<form action="...." method="post">
名字:
年龄:
学号:
</form>
2 但是如果表单中加入了某些图片提交,这就需要多段提交方式。如下是案例代码:
<form action="...." method="post" enctype="multipart/form-data" >
名字:
年龄:
学号:
图片:<img src="../a.jpg">
</form>
j普通表单提交和多段表单提交:
2:如下是一些基本的学生管理系统代码:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h3>学生管理系统</h3>
<ul>
<li><a href="<c:url value="/smsMgr"/>?act=toReg">新生注册登记</a></li>
<li><a href="<c:url value="/smsMgr"/>?act=loadall">学生列表</a></li>
</ul>
</body>
</html>
Student.java 类
/**
* 工 程 名:TagDemoPrj-20180221 <br>
* 文 件 名:Student.java <br>
* 工具包名:edu.fjnu.domain <br>
* 功能描述:TODO <br>
* 创建时间:2018年5月21日 下午2:00:49 <br>
* 版本信息:V1.0
* @创建人:周开伦
*/
package edu.fjnu.training.domain;
import java.util.Arrays;
/**
* 类名:Student <br>
* 功能描述: <br>
* 创建日期:2018年5月21日 下午2:00:49 <br>
* 修改备注:
* @作者信息:Zhou kailun <br>
*/
public class Student {
/**学生学号*/
private String stuNo;
/**学生姓名*/
private String stuName;
/**学生性别*/
private String stuSex;
/**学生爱好*/
private String[] stuHobbies;
/**学生籍贯*/
private String stuOrigin;
/**学生成绩*/
private Integer stuMark;
/**学生备注*/
private String stuMemo;
/**学生照片*/
private byte[] stuPic;
public Student()
{
super();
this.stuNo="请定义";
this.stuName="请定义";
this.stuMark=0;
}
public Student(String stuNo,String stuName,int stuMark)
{
super();
this.stuNo=stuNo;
this.stuName=stuName;
this.stuMark=stuMark;
}
@Override
public String toString() {
return "Student [stuNo=" + stuNo + ", stuName=" + stuName + ", stuSex="
+ stuSex + ", stuHobbies=" + Arrays.toString(stuHobbies)
+ ", stuOrigin=" + stuOrigin + ", stuMark=" + stuMark
+ ", stuMemo=" + stuMemo + ", stuPic="
+ Arrays.toString(stuPic) + "]";
}
public String getStuNo() {
return stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public Integer getStuMark() {
return stuMark;
}
public void setStuMark(Integer stuMark) {
this.stuMark = stuMark;
}
public String getStuSex() {
return stuSex;
}
public void setStuSex(String stuSex) {
this.stuSex = stuSex;
}
public String[] getStuHobbies() {
return stuHobbies;
}
public void setStuHobbies(String[] stuHobbies) {
this.stuHobbies = stuHobbies;
}
public String getStuOrigin() {
return stuOrigin;
}
public void setStuOrigin(String stuOrigin) {
this.stuOrigin = stuOrigin;
}
public String getStuMemo() {
return stuMemo;
}
public void setStuMemo(String stuMemo) {
this.stuMemo = stuMemo;
}
public byte[] getStuPic() {
return stuPic;
}
public void setStuPic(byte[] stuPic) {
this.stuPic = stuPic;
}
}
DBUtils.java 类:
/**
* 工 程 名:JDBCDemoPrj-20180221 <br>
* 文 件 名:DBUtils.java <br>
* 工具包名:edu.fjnu.training.utils <br>
* 功能描述:TODO <br>
* 创建时间:2018年5月21日 下午7:27:45 <br>
* 版本信息:V1.0
* @创建人:周开伦
*/
package edu.fjnu.training.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 类名:DBUtils 数据库连接类<br>
* 功能描述: <br>
* 创建日期:2018年5月21日 下午7:27:45 <br>
* 修改备注:
* @作者信息:Zhou kailun <br>
*/
public class DBUtils {
/**连接串,说明数据库所在位置,,连接方式jdbc 数据库名字:testdb*/
private static final String CONN_URL="jdbc:mysql://localhost:3306/test";
/**数据库连接用户账号*/
private static final String USER="root";
/**数据库连接密码*/
private static final String PASSWORD="xxxx";
private static final DBUtils utils=new DBUtils();
private DBUtils()
{
}
/**
* 方法名:获得DBUtils实例对象(单例模式) <br>
* 功能描述:获得数据库操作DBUtils实例对象(单例模式) <br>
* @return : DBUtils对象
* @throws:
* @see :
*/
public static DBUtils getInstance()
{
return utils;
}
/**
* 方法名:获得数据库连接 <br>
* 功能描述:取得数据的连接实例 <br>
* @return :
* @throws:
* @see :
*/
public Connection getConn()
{
Connection conn=null;
try{
//在程序中以com.mysql.jdbc.Driver去查找类,看是否能够找到,找不到抛出异常,
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(CONN_URL,USER,PASSWORD);
}catch(ClassNotFoundException e){
e.printStackTrace();
//抛出驱动异常
System.out.println("MySql驱动没找到或者型号不对,请检查驱动是否导入....");
}catch(SQLException e){
//抛出数据库连接异常
e.printStackTrace();
System.out.println("MySQL数据连接异常,请检查数据库是否存在或者数据库登录账号密码是否正确....");
}
return conn;
}
/**
* 方法名:释放数据库连接资源 <br>
* 功能描述:将获得的数据库连接资源,准备语句,结果集进行释放 <br>
* @param connect
* @param pstmt
* @param rset :
* @throws:
* @see :
*/
public void releaseResource(Connection connect,PreparedStatement pstmt,ResultSet rset)
{
try{
if(rset!=null)
{
rset.close();
}
if(pstmt!=null)
{
pstmt.close();
}
if(connect!=null)
{
connect.close();
}
}catch(SQLException e){
e.printStackTrace();
System.out.println("数据库资源连接释放资源失败,请检查连接和资源释放....");
}catch(Exception e)
{
e.printStackTrace();
System.out.println("异常产生在数据库资源释放模块,请检查操作是否正确....");
}
}
}
StudentDao.java 接口interface
/**
* 工 程 名:JDBCDemoPrj-20180221 <br>
* 文 件 名:StudentDao.java <br>
* 工具包名:edu.fjnu.training.dao <br>
* 功能描述:TODO <br>
* 创建时间:2018年5月21日 下午8:03:53 <br>
* 版本信息:V1.0
* @创建人:周开伦
*/
package edu.fjnu.training.dao;
import java.util.List;
import edu.fjnu.training.domain.Student;
/**
* 类名:StudentDao <br>
* 功能描述: <br>
* 创建日期:2018年5月21日 下午8:03:53 <br>
* 修改备注:
* @作者信息:Zhou kailun <br>
*/
public interface StudentDao {
/**
* 方法名:保存学生信息 <br>
* 功能描述:将学生信息保存到数据库中去 <br>
* @param stu : 学生信息
* @throws:
* @see :
*/
public void addStudent(Student stu);
/**
* 方法名:删除学生信息 <br>
* 功能描述:从数据库中将学号为:stuNo的学生信息删除 <br>
* @param stuNo : 学生学号
* @throws:
* @see :
*/
public void removeStudent(String stuNo);
/**
* 方法名:加载所有学生信息 <br>
* 功能描述:将所有学生信息从数据库中取出来 <br>
* @return : 学生信息列表
* @throws:
* @see :
*/
public List<Student> loadAllStudent();
/**
* 方法名:获取学生信息 <br>
* 功能描述:通过学生学号获取学生信息 <br>
* @param stuNo 学生学号
* @return : 学生对象信息
* @throws:
* @see :
*/
public Student getStudentByStuNo(String stuNo);
/**
* 方法名:修改学生信息 <br>
* 功能描述:修改数据库中学生信息 <br>
* @param stu : 学生对象信息
* @throws:
* @see :
*/
public void updateStudent(Student stu);
/**
* 方法名:加载学生照片信息 <br>
* 功能描述:根据学生学号获取学生照片 <br>
* @param stuNo 学生学号
* @return : 学生照片信息 bytes
* @throws:
* @see :
*/
public byte[] loadStuPicByNo(String stuNo);
}
StudentDaoJDBCImpl.java 实现类:
/**
* 工 程 名:JDBCDemoPrj-20180221 <br>
* 文 件 名:StudentDaoImpl.java <br>
* 工具包名:edu.fjnu.training.dao <br>
* 功能描述:TODO <br>
* 创建时间:2018年5月21日 下午8:04:18 <br>
* 版本信息:V1.0
* @创建人:周开伦
*/
package edu.fjnu.training.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import edu.fjnu.training.domain.Student;
import edu.fjnu.training.utils.DBUtils;
/**
* 类名:StudentDaoImpl <br>
* 功能描述: <br>
* 创建日期:2018年5月21日 下午8:04:18 <br>
* 修改备注:
* @作者信息:Zhou kailun <br>
*/
public class StudentDaoJDBCImpl implements StudentDao {
// stu_no | stu_name | stu_mark | stu_sex | stu_hobbies | stu_origin | stu_memo
/**插入学生信息数据库语句*/
private static final String ADD_STU="insert into tbl_student(stu_no,stu_name,stu_mark,stu_sex,stu_hobbies,"
+ "stu_origin,stu_memo,stu_pic) values(?,?,?,?,?,"
+ "?,?,?);";
/**删除学生信息数据库语句*/
private static final String DEL_STU="delete from tbl_student where stu_no=?;";
/**查询所有学生信息数据库语句*/
private static final String LOAD_STU="select * from tbl_student;";
/**(根据学号)查询学生信息数据库语句*/
private static final String GET_STU_BY_STUNO="select * from tbl_student where stu_no=?";
/**更新学生信息数据库语句*/
private static final String UPDATE_STU="update tbl_student set stu_name=?,stu_mark=?,stu_sex=?,stu_hobbies=?,stu_origin=?,"
+ "stu_memo=? where stu_no=?";
/**查询学生图片信息SQL语句(根据学号)*/
private static final String LOAD_STU_PIC_BY_NO="select stu_pic from tbl_student where stu_no=?";
@Override
public void addStudent(Student stu) {
// TODO Auto-generated method stub
DBUtils utils=DBUtils.getInstance();
Connection conn=null;///声明数据库连接
PreparedStatement pstmt=null;//声明数据库准备语句、
try {
//对象变成记录
conn=utils.getConn();
pstmt=conn.prepareStatement(ADD_STU);
pstmt.setString(1, stu.getStuNo());
pstmt.setString(2, stu.getStuName());
pstmt.setInt(3, stu.getStuMark());
pstmt.setString(4, stu.getStuSex());
//[a,b,c]->a|b|c
StringBuffer sb=new StringBuffer();
for(String hobby:stu.getStuHobbies())
{
sb.append(hobby).append("|");
}
sb.deleteCharAt(sb.length()-1);//去掉最后一个竖线
pstmt.setString(5, sb.toString());
pstmt.setString(6, stu.getStuOrigin());
pstmt.setString(7, stu.getStuMemo());
pstmt.setBytes(8, stu.getStuPic());
pstmt.executeUpdate();
} catch (SQLException e) {
//e.printStackTrace();
if(e.getMessage().contains("Duplicate entry"))
{
throw new RuntimeException("该信息已经存在,不能重复录入...");
}
}finally{
//释放资源
utils.releaseResource(conn, pstmt, null);
}
}
@Override
public void removeStudent(String stuNo) {
// TODO Auto-generated method stub
DBUtils utils=DBUtils.getInstance();
Connection connect=null;
PreparedStatement pstmt=null;
try{
//获得连接和准备语句
connect=utils.getConn();
pstmt=connect.prepareStatement(DEL_STU);
//补全pstmt参数
pstmt.setString(1, stuNo);
//执行更新删除操作
int cnt=pstmt.executeUpdate();
if(cnt!=1)
{
throw new RuntimeException("学生信息删除失败!");
}
}catch(SQLException e){
e.printStackTrace();
System.out.println("删除学生信息执行语句失败,请检查数据库状态或者SQL语句...");
}catch(Exception e){
e.printStackTrace();
System.out.println("异常位置:删除学生信息.....");
}finally{
utils.releaseResource(connect, pstmt, null);
}
}
@Override
public List<Student> loadAllStudent() {
DBUtils utils=DBUtils.getInstance();
Connection connect=null;
PreparedStatement pstmt=null;
ResultSet rset=null;
List<Student> stuList=new ArrayList<Student>();
try{
//获得数据库连接,准备语句
connect=utils.getConn();
pstmt=connect.prepareStatement(LOAD_STU);
//执行数据库查询语句,获得结果集
rset=pstmt.executeQuery();
//记录集读写指针乡下移动一行,如果所移动的行是存在的,也就是说是记录行,那么就返回true,否则如果到达记录末尾,将返回false
while(rset.next())
{
//记录变成对象
Student stu=new Student();
stu.setStuNo(rset.getString("stu_no"));
stu.setStuName(rset.getString("stu_name"));
stu.setStuMark(rset.getInt("stu_mark"));
stu.setStuSex(rset.getString("stu_sex"));
String stuHobbies=rset.getString("stu_hobbies");
if(stuHobbies!=null)
{//防止stuHobbies为空情况异常
stu.setStuHobbies(stuHobbies.split("\\|"));
}
stu.setStuOrigin(rset.getString("stu_origin"));
stu.setStuMemo(rset.getString("stu_memo"));
stuList.add(stu);
}
}catch(SQLException e){
e.printStackTrace();
System.out.println("查询学生信息失败,请检查SQL语句或者数据库状态....");
}
return stuList;
}
@Override
public Student getStudentByStuNo(String stuNo) {
DBUtils utils=DBUtils.getInstance();
Connection connect=null;
PreparedStatement pstmt=null;
ResultSet rset=null;
Student stu=null;
try{
//获得数据库连接,准备语句
connect=utils.getConn();
pstmt=connect.prepareStatement(GET_STU_BY_STUNO);
//补全准备语句
pstmt.setString(1, stuNo);
//执行数据库查询语句,获得结果集
rset=pstmt.executeQuery();
//记录集读写指针乡下移动一行,如果所移动的行是存在的,也就是说是记录行,那么就返回true,否则如果到达记录末尾,将返回false
if(rset.next())
{
//记录变成对象
stu=new Student();
stu.setStuNo(rset.getString("stu_no"));
stu.setStuName(rset.getString("stu_name"));
stu.setStuMark(rset.getInt("stu_mark"));
stu.setStuSex(rset.getString("stu_sex"));
String stuHobbies=rset.getString("stu_hobbies");
if(stuHobbies!=null)
{//防止stuHobbies为空情况异常
stu.setStuHobbies(stuHobbies.split("\\|"));
}
stu.setStuOrigin(rset.getString("stu_origin"));
stu.setStuMemo(rset.getString("stu_memo"));
}
}catch(SQLException e){
e.printStackTrace();
System.out.println("查询学生信息失败,请检查SQL语句或者数据库状态....");
}
return stu;
}
@Override
public void updateStudent(Student stu) {
DBUtils utils=DBUtils.getInstance();
Connection conn=null;///声明数据库连接
PreparedStatement pstmt=null;//声明数据库准备语句、
conn=utils.getConn();
try {
//对象变成记录
pstmt=conn.prepareStatement(UPDATE_STU);
pstmt.setString(1, stu.getStuName());
pstmt.setInt(2, stu.getStuMark());
pstmt.setString(3, stu.getStuSex());
//[a,b,c]->a|b|c
String stuHobby=null; //存储目标字符串
String[] stuHobbies=stu.getStuHobbies();//获取stuHobbies信息
if(stuHobbies!=null){
StringBuffer sb=new StringBuffer();
for(int i=0;i<stuHobbies.length;i++)
{
sb.append(stuHobbies[i]).append("|");
}
sb.deleteCharAt(sb.length()-1);//去掉最后一个竖线
stuHobby=sb.toString();
}
pstmt.setString(4, stuHobby);
pstmt.setString(5, stu.getStuOrigin());
pstmt.setString(6, stu.getStuMemo());
pstmt.setString(7, stu.getStuNo());
pstmt.executeUpdate();
} catch (SQLException e) {
//e.printStackTrace();
e.printStackTrace();
}finally{
//释放资源
utils.releaseResource(conn, pstmt, null);
}
}
@Override
public byte[] loadStuPicByNo(String stuNo) {
DBUtils utils=DBUtils.getInstance();
Connection connect=null;
PreparedStatement pstmt=null;
ResultSet rset=null;
byte[] stuPic=null;
try{
//获得数据库连接,准备语句
connect=utils.getConn();
pstmt=connect.prepareStatement(LOAD_STU_PIC_BY_NO);
//补全准备语句
pstmt.setString(1, stuNo);
//执行数据库查询语句,获得结果集
rset=pstmt.executeQuery();
//记录集读写指针乡下移动一行,如果所移动的行是存在的,也就是说是记录行,那么就返回true,否则如果到达记录末尾,将返回false
if(rset.next())
{
stuPic=rset.getBytes("stu_pic");
}
}catch(SQLException e){
e.printStackTrace();
System.out.println("查询学生信息失败,请检查SQL语句或者数据库状态....");
}
return stuPic;
}
}
StudentMgrServlet.java 控制类servlet
package edu.fjnu.training.conrtoller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import edu.fjnu.training.dao.StudentDao;
import edu.fjnu.training.dao.StudentDaoJDBCImpl;
import edu.fjnu.training.domain.Student;
public class StudentMgrServlet extends HttpServlet {
/**设置编码方式,默认为utf-8*/
public static final String ENCODE="UTF-8";
/**
* Constructor of the object.
*/
public StudentMgrServlet() {
super();
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置请求编码为UTF-8
request.setCharacterEncoding("utf-8");
/**多段提交理解*/
//得到当前临时文件夹的位置
File tempFile=new File(System.getProperty("java.io.tmpdir"));
//任何文件提交域都是磁盘文件项
DiskFileItemFactory factory=new DiskFileItemFactory();
//文件项的数量门槛4096个文件
factory.setSizeThreshold(4095);
//设置临时存储位置
factory.setRepository(tempFile);
//构建sfu对象来解析多段提交的request数据流
ServletFileUpload sfu=new ServletFileUpload(factory);
//设置了单个文件大小的门槛5G大小
sfu.setSizeMax(5000000);
List<FileItem> fileItems=null;
String act=null;
//获取请求参数信息
if(sfu.isMultipartContent(request))//判断request是否是多段提交
{
try{
//使用SFU解析request流,得到磁盘文件项列表(普通提交域/文件提交域)
fileItems=sfu.parseRequest(request);
for(FileItem item:fileItems)
{
if(item.isFormField()&&item.getFieldName().equals("act"))
{
act=item.getString("utf-8");
break;
}
}
}catch(FileUploadException e){
e.printStackTrace();
}
}
else
act=request.getParameter("act");
//请求注册toReg
if("toReg".equals(act))
{
request.getRequestDispatcher("/jsps/student/reg_student.jsp").forward(request,response);;
}
//请求执行存储操作
else if("reg".equals(act))
{
Student stu=new Student();
List<String> hobbyList=new ArrayList<String>();
//循环遍历磁盘文件项
for(FileItem item:fileItems){
if(item.isFormField()&&item.getFieldName().equals("stuNo")){
stu.setStuNo(item.getString(ENCODE));
}
else if(item.isFormField()&&item.getFieldName().equals("stuName")){
stu.setStuName(item.getString(ENCODE));
}
else if(item.isFormField()&&item.getFieldName().equals("stuMark")){
stu.setStuMark(Integer.parseInt(item.getString(ENCODE)));
}
else if(item.isFormField()&&item.getFieldName().equals("stuSex")){
stu.setStuSex(item.getString(ENCODE));
}
else if(item.isFormField()&&item.getFieldName().equals("stuHobby")){
String hobby=item.getString(ENCODE);
hobbyList.add(hobby);
stu.setStuHobbies(hobbyList.toArray(new String[]{}));
}
else if(item.isFormField()&&item.getFieldName().equals("stuOrigin")){
stu.setStuOrigin(item.getString(ENCODE));
}
else if(item.isFormField()&&item.getFieldName().equals("stuMemo")){
stu.setStuMemo(item.getString(ENCODE));
}
else if(!item.isFormField()&&item.getFieldName().equals("stuPic")){
byte[] pic=new byte[(int)item.getSize()];
item.getInputStream().read(pic, 0, (int)item.getSize());
stu.setStuPic(pic);
}
}
// stu.setStuNo(request.getParameter("stuNo"));
// stu.setStuName(request.getParameter("stuName"));
// stu.setStuMark(Integer.parseInt(request.getParameter("stuMark")));
// stu.setStuSex(request.getParameter("stuSex"));
// stu.setStuHobbies(request.getParameterValues("stuHobby"));
// stu.setStuOrigin(request.getParameter("stuOrigin"));
// stu.setStuMemo(request.getParameter("stuMemo"));
//
StudentDao stuDao=new StudentDaoJDBCImpl();
stuDao.addStudent(stu);
response.sendRedirect("smsMgr?act=loadall");
}
//加载所有学生信息
else if("loadall".equals(act))
{
StudentDao stuDao=new StudentDaoJDBCImpl();
request.setAttribute("stuList", stuDao.loadAllStudent());
request.getRequestDispatcher("./jsps/student/list_student.jsp").forward(request, response);
}
//删除学生信息
else if("remove".equals(act))
{
String stuNo=request.getParameter("stuNo");
StudentDao stuDao=new StudentDaoJDBCImpl();
stuDao.removeStudent(stuNo);
response.sendRedirect("smsMgr?act=loadall");
}
//预更新操作准备
else if("preUpdate".equals(act))
{
String stuNo=request.getParameter("stuNo");
StudentDao stuDao=new StudentDaoJDBCImpl();
Student stu=stuDao.getStudentByStuNo(stuNo);
request.setAttribute("stu", stu);
request.getRequestDispatcher("/jsps/student/update_student.jsp").forward(request, response);
}
else if("update".equals(act))
{
Student stu=new Student();
stu.setStuNo(request.getParameter("stuNo"));
stu.setStuName(request.getParameter("stuName"));
stu.setStuMark(Integer.parseInt(request.getParameter("stuMark")));
stu.setStuSex(request.getParameter("stuSex"));
stu.setStuHobbies(request.getParameterValues("stuHobby"));
stu.setStuOrigin(request.getParameter("stuOrigin"));
stu.setStuMemo(request.getParameter("stuMemo"));
StudentDao stuDao=new StudentDaoJDBCImpl();
stuDao.updateStudent(stu);
response.sendRedirect("smsMgr?act=loadall");
}
else if("loadPic".equals(act)){
String stuNo=request.getParameter("stuNo");
StudentDao stuDao=new StudentDaoJDBCImpl();
byte[] stuPic=stuDao.loadStuPicByNo(stuNo);
if(stuPic==null){
String path=request.getRealPath("/pics/default.jpg");
FileInputStream fis=new FileInputStream(new File(path));
stuPic=new byte[fis.available()];
fis.read(stuPic);
}
//向浏览器发送通知,我要发送的是图片
response.setContentType("image/jpeg");
ServletOutputStream sos=response.getOutputStream();
sos.write(stuPic);
sos.flush();
sos.close();
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
前台显示:
reg_student.jsp 注册界面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'reg_student.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<%-- <link rel="stylesheet" type="text/css" href="../../../css/style.css"> --%>
<%-- <link rel="stylesheet" type="text/css" href="/sms/css/style.css"> --%>
<%-- <link rel="stylesheet" type="text/css" href="<%=basePath%>/css/style.css">--%>
<link rel="stylesheet" type="text/css" href="<c:url value="/css/style.css"/>">
<script type="text/javascript" src="<c:url value="/js/common.js"></c:url>"></script>
</head>
<body>
<h3>新生登记(2018年5月22日08:02:55)</h3>
<form action="<c:url value="/smsMgr"/>" method="post" enctype="multipart/form-data">
<input type="hidden" name="act" value="reg">
<img id="stuPhoto"
style="float:right;"
alt="学生图片"
src="<c:url value="/pics/default.jpg"/>"
width="160px"
height="160px"
/>
<div>
<span>学号:</span>
<input type="text" name="stuNo">
</div>
<div>
<span>姓名:</span>
<input type="text" name="stuName">
</div>
<div>
<span>相片:</span>
<input type="file" name="stuPic" οnchange="$('stuPhoto').src=this.value;">
</div>
<div>
<span>成绩:</span>
<input type="text" name="stuMark">
</div>
<div>
<span>性别:</span>
<input type="radio" name="stuSex" value="m" checked>男
<input type="radio" name="stuSex" value="f">女
</div>
<div>
<span>爱好:</span>
<input type="checkbox" name="stuHobby" value="cm" checked>爬山
<input type="checkbox" name="stuHobby" value="rd" checked>阅读
<input type="checkbox" name="stuHobby" value="rn">跑步
<input type="checkbox" name="stuHobby" value="sw">游泳
</div>
<div>
<span>籍贯:</span>
<select name="stuOrigin">
<option value="xm">厦门</option>
<option value="fz" selected>福州</option>
<option value="nd">宁德</option>
<option value="pt">莆田</option>
</select>
</div>
<div>
<span>备注:</span>
<textarea rows="6" cols="60" name="stuMemo"></textarea>
</div>
<div>
<input type="submit" value="注册登记">
</div>
</form>
<a href="<c:url value="/" />">首页</a>
<%-- <jsp:include page="../../css/footer.jsp"></jsp:include>--%>
</body>
</html>
list_student.jsp: 显示界面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8" isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>学生列表</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<link rel="stylesheet" type="text/css" href="<c:url value="/css/style.css"/>">
<style>
</style>
<script>
function removeStudent(stuNo,stuName){
if(confirm("您确定要删除(学号:"+stuNo+" 姓名:"+stuName+")的学生信息吗?"))
{
location.href="<c:url value="/smsMgr"/>?act=remove&stuNo="+stuNo;
}
}
//修改学生信息
function updateStudent(stuNo){
location.href="<c:url value="/smsMgr"/>?act=preUpdate&stuNo="+stuNo;
}
</script>
</head>
<body>
<h3>学生列表</h3>
<table border="1" cellspacing="0" cellpadding="3px">
<caption>学生信息列表</caption>
<thead>
<tr>
<th>序号</th>
<th>学号</th>
<th>姓名</th>
<th>成绩</th>
<th>性别</th>
<th>爱好</th>
<th>籍贯</th>
<th>备注</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="stu" varStatus="index" items="${requestScope.stuList }">
<tr>
<td>${index.index+1 }</td>
<td>${stu.stuNo }</td>
<td>
<img width="100px" height="80px" alt="学生图片" src="<c:url value="/smsMgr?act=loadPic&stuNo=${stu.stuNo }"></c:url>">
<br>${stu.stuName }
</td>
<td>${stu.stuMark }</td>
<td>
<c:choose>
<c:when test="${stu.stuSex=='m'}">男</c:when>
<c:when test="${stu.stuSex=='f'}">女</c:when>
<c:when test="${stu.stuSex!='m' && stu.stuSex!='f'}">请完善信息</c:when>
</c:choose>
</td>
<td>
<c:forEach var="hobby" items="${stu.stuHobbies }">
<c:choose>
<c:when test="${hobby=='cm'}"><label class='hobbyStyle'>爬山</label></c:when>
<c:when test="${hobby=='rd'}"><label class='hobbyStyle'>阅读</label></c:when>
<c:when test="${hobby=='rn'}"><label class='hobbyStyle'>跑步</label></c:when>
<c:when test="${hobby=='sw'}"><label class='hobbyStyle'>游泳</label></c:when>
</c:choose>
</c:forEach>
</td>
<td>
<c:choose>
<c:when test="${stu.stuOrigin=='xm'}">厦门</c:when>
<c:when test="${stu.stuOrigin=='fz'}">福州</c:when>
<c:when test="${stu.stuOrigin=='nd'}">宁德</c:when>
<c:when test="${stu.stuOrigin=='pt'}">莆田</c:when>
</c:choose>
</td>
<td>${stu.stuMemo }</td>
<td>
<button οnclick="updateStudent('${stu.stuNo}');">修改</button>
<button οnclick="removeStudent('${stu.stuNo}','${stu.stuName }');">删除</button>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<hr>
<a href="<c:url value="/" />">首页</a>
</body>
</html>
update_student.jsp 更新界面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>学生信息修改</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<%-- <link rel="stylesheet" type="text/css" href="../../../css/style.css"> --%>
<%-- <link rel="stylesheet" type="text/css" href="/sms/css/style.css"> --%>
<%-- <link rel="stylesheet" type="text/css" href="<%=basePath%>/css/style.css">--%>
<link rel="stylesheet" type="text/css" href="<c:url value="/css/style.css"/>">
</head>
<body>
<h3>学生[${stu.stuName }]信息修改</h3>
<form action="<c:url value="/smsMgr"/>?act=update" method="post">
<div>
<span>学号:</span>${stu.stuNo }
<%-- <input type="text" name="stuNo" value="${stu.stuNo }" hidden> --%>
<input type="hidden" name="stuNo" value="${stu.stuNo }">
</div>
<div>
<span>姓名:</span>
<input type="text" name="stuName" value="${stu.stuName }">
</div>
<div>
<span>成绩:</span>
<input type="text" name="stuMark" value="${stu.stuMark }">
</div>
<div>
<span>性别:</span>
<input type="radio" name="stuSex" value="m"
<c:if test="${stu.stuSex=='m'}">checked</c:if>
>男
<input type="radio" name="stuSex" value="f"
<c:if test="${stu.stuSex=='f'}">checked</c:if>
>女
</div>
<div>
<span>爱好:</span>
<input type="checkbox" name="stuHobby" value="cm"
<c:forEach var="stuHobby" items="${stu.stuHobbies }">
<c:if test="${stuHobby=='cm' }">checked</c:if>
</c:forEach>
>爬山
<input type="checkbox" name="stuHobby" value="rd"
<c:forEach var="stuHobby" items="${stu.stuHobbies }">
<c:if test="${stuHobby=='rd' }">checked</c:if>
</c:forEach>
>阅读
<input type="checkbox" name="stuHobby" value="rn"
<c:forEach var="stuHobby" items="${stu.stuHobbies }">
<c:if test="${stuHobby=='rn' }">checked</c:if>
</c:forEach>
>跑步
<input type="checkbox" name="stuHobby" value="sw"
<c:forEach var="stuHobby" items="${stu.stuHobbies }">
<c:if test="${stuHobby=='sw' }">checked</c:if>
</c:forEach>
>游泳
</div>
<div>
<span>籍贯:</span>
<select name="stuOrigin">
<option value="">==请选择==</option>
<option value="xm"
<c:if test="${stu.stuOrigin=='xm'}">selected</c:if>
>厦门</option>
<option value="fz"
<c:if test="${stu.stuOrigin=='fz'}">selected</c:if>
>福州</option>
<option value="nd"
<c:if test="${stu.stuOrigin=='nd'}">selected</c:if>
>宁德</option>
<option value="pt"
<c:if test="${stu.stuOrigin=='pt'}">selected</c:if>
>莆田</option>
</select>
</div>
<div>
<span>备注:</span>
<textarea rows="6" cols="60" name="stuMemo"></textarea>
</div>
<div>
<input type="submit" value="确定修改">
</div>
</form>
<a href="<c:url value="/" />">首页</a>
<%-- <jsp:include page="../../css/footer.jsp"></jsp:include>--%>
</body>
</html>