一、设计思想
界面构思:
先按照图片要求,写一个addInput的界面,实现要保存信息的输入。在后台数据库中建立相应的表course 存储课程信息。保存新信息即是数据库的增操作,所以再写一个add1.jsp 页面操作从addInput传过来的参数信息。因为参数有相应要求:任课教师为王建民、刘立嘉、刘丹、王辉、杨子光五位教师的其中一位。 要求上课地点开头为“一教、二教、三教、基教”中的一种,即判断参数是否等于要求,若不等,让它跳转回原来的addInput的界面,并给addInput页面返回一个错误信息,重新输入参数。若满足要求,则将参数各个信息设置给一个User对象,将这个对象添加到数据库中,在此只判断输入信息是否有效,如输入信息与数据库中出现重复的情况,在add操作中有相应判断。list.jsp用于显示所有课程信息。
数据库连接:
因为增删改查都是要调数据库操作的,所以不妨将数据库的连接写入一个包中分装,com.jaovo.msg.Util包中DBUtil类,设置加载数据库和释放资源的方法,在增删改查操作,即可直接调用,UserDaoImpl类中放着所有的操作方法,每执行一个操作,既然是对数据库操作,即要连接数据库。
方法实现:
其实方法都大同小异,例如增加:1. 获得连接对象 2. 准备sql语句 3.创建语句传输对象 4. 接收结果集 5.遍历结果集 结果集不为空 ( 即该课程名称已存在)则抛出异常:该课程信息已存在;若为空,调用SQL中插入语句,将添加信息插入表中即可。6.关闭资源。
异常抛出:
定义一个自己的UserException类,继承Exception即可,抛出相关信息。
错误信息捕捉:
1. ValidateUtil类中放着Map容器,通过 map对象用来装载不同错误信息 没有错误信息时返回true (错误信息为空),否则返回false。1. Map<String,String> errorMsg=new HashMap();//<>泛型(map 装载错误信息,返回这个容器信息)2. 通过request.getParameter(filed);//获取对应参数 3.然后将错误信息装载:errorMsg.put(filed, filed+"不能为空");//键和值 4.request.setAttribute("errormsg",errorMsg);//map装进将容器中,在界面设置boolean validate=ValidateUtil.validateNull(request, new String[]{"class","teacher","address"});//使用的同一个request对象,判断它是否为真,若非真,则跳转原添加页面,在页面显示调用showError(request,"teacher")方法显示即可。若真,则执行添加操作。
2.也可根据这种方法 ; 在add1.jsp页面,设置request.setAttribute("loginError","任课老师不存在");,然后在输入参数界面即addInput界面,request.getAttribute("loginError"),接收这个错误信息,判断是否有错误,若无,则赋值给“ ”即可,让它在页面输出即可。
二、源程序代码
addInput.jsp
<%@ page import="com.jaovo.msg.Util.ValidateUtil" %> <%@ 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> <h1 style="color:blue ; ">课程信息添加页面</h1> </head> <body> <% String loginError = (String)request.getAttribute("loginError"); if(loginError == null){ loginError = ""; } %> <h4 style="color:red ;"><%=loginError %></h4> <form action="add1.jsp" method="post"> <tr> <td>课程名称 : </td> <td> <input type="text" name="class" /> <%=ValidateUtil.showError(request,"class") %> </td><br> </tr> <tr> <td>任课教师 : </td> <td> <input type="text" name="teacher" /> <%= ValidateUtil.showError(request,"teacher") %> </td><br> </tr> <tr> <td>上课地点 : </td> <td> <input type="text" name="address" /> <%=ValidateUtil.showError(request,"address")%> </td><br> <tr align="center"> <td colspan="2"> <input type="submit" value="保存" /> <input type="reset" value="重置" /> </td> </tr> </form> </body> </html>
add1.jsp
<%@page import="com.jaovo.msg.Util.UserException"%> <%@page import="com.jaovo.msg.dao.UserDaoImpl"%> <%@page import="com.jaovo.msg.model.User"%> <%@page import="com.jaovo.msg.Util.ValidateUtil"%> <%@ 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> <% //接收客户端传递过来的参数 String Class = request.getParameter("class"); String teacher = request.getParameter("teacher"); String address = request.getParameter("address"); boolean validate=ValidateUtil.validateNull(request, new String[]{"class","teacher","address"});//使用的同一个request对象 if(!validate){ %> <jsp:forward page="addInput.jsp"></jsp:forward> <% } User user = new User(); user.setCourse(Class); user.setTeacher(teacher); user.setAddress(address); UserDaoImpl userDao = new UserDaoImpl(); try{ if((!("王建民".equals(teacher)))&&(!("刘立嘉".equals(teacher)))&&(!("王辉".equals(teacher)))&&(!("刘丹".equals(teacher)))) { request.setAttribute("loginError","任课老师不存在"); %> <jsp:forward page="addInput.jsp"></jsp:forward> <% } else if(!(address.startsWith("一教"))&&!(address.startsWith("二教"))&&!(address.startsWith("三教"))&&!(address.startsWith("基教"))) { request.setAttribute("loginError","上课地点有误"); %> <jsp:forward page="addInput.jsp"></jsp:forward> <% } else{ userDao.add(user); //重定向response.sendRedirect("List.jsp"); %> 用户保存成功!!<br> <a href="addInput.jsp">继续添加</a><br> <a href="list.jsp">用户列表</a> <% } }catch(UserException e){ %> <h2 style="color:red ; font-size:50px">发生错误 : <%=e.getMessage() %></h2> <% } %> </html>
list.jsp
<%@page import="com.jaovo.msg.model.User"%> <%@page import="java.util.List"%> <%@page import="com.jaovo.msg.dao.UserDaoImpl"%> <%@ 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>用户展示界面</title> </head> <% UserDaoImpl userDao = new UserDaoImpl(); List<User> users = userDao.load(); %> <body> <table align="center" border="1" width="500"> <tr> <td>课程编号</td> <td>课程名称</td> <td>任课教师</td> <td>上课地点</td> </tr> <% for( User user : users ){ %> <tr> <td> <%=user.getId() %></td> <td> <%=user.getCourse() %></td> <td> <%=user.getTeacher() %></td> <td> <%=user.getAddress() %></td> </tr> <% } %> </table> </body> </html>
DBUtil.java--连接数据库
package com.jaovo.msg.Util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DBUtil { public static Connection getConnection() { //1 加载驱动 try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (InstantiationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String user = "root"; String password = "root"; String url = "jdbc:mysql://localhost:3306/course"; Connection connection = null; try { //2 创建链接对象connection connection = DriverManager.getConnection(url,user,password); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return connection; } //关闭资源的方法 public static void close(Connection connection ) { try { if (connection != null) { connection.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void close(PreparedStatement preparedStatement ) { try { if (preparedStatement != null) { preparedStatement.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void close(ResultSet resultSet ) { try { if (resultSet != null) { resultSet.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
User.java--基本信息(属性)
package com.jaovo.msg.model; public class User { private int id; private String course; private String teacher; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCourse() { return course; } public void setCourse(String course) { this.course = course; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTeacher() { return teacher; } public void setTeacher(String teacher) { this.teacher = teacher; } }
IUserDao.java----方法接口
package com.jaovo.msg.dao; import java.util.List; import com.jaovo.msg.model.User; public interface IUserDao { public void add(User user); public void delete(int id); public void update(User user); public User load(int id); public User load(String Class); public User load(String Class,String teacher); public List<User> load(); }
UserDaoImpl.java---方法实现(增删改查)
package com.jaovo.msg.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 com.jaovo.msg.Util.DBUtil; import com.jaovo.msg.Util.UserException; import com.jaovo.msg.model.User; import sun.net.www.content.text.plain; public class UserDaoImpl implements IUserDao { @Override public void add(User user) { //获得连接对象 Connection connection=DBUtil.getConnection(); //准备sql语句 String sql="select count(*)from t_user where Class= ?"; //创建语句传输对象 PreparedStatement preparedStatement=null; ResultSet resultSet=null; try { preparedStatement=connection.prepareStatement(sql); preparedStatement.setString(1, user.getCourse()); //接收结果集 resultSet=preparedStatement.executeQuery(); //遍历结果集 while(resultSet.next()) { if(resultSet.getInt(1)>0) throw new UserException("用户已存在"); } sql="insert into t_user(Class,teacher,address) value (?,?,?)"; preparedStatement=connection.prepareStatement(sql); preparedStatement.setString(1, user.getCourse()); preparedStatement.setString(2, user.getTeacher()); preparedStatement.setString(3, user.getAddress()); preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally { //关闭资源 DBUtil.close(resultSet); DBUtil.close(preparedStatement); DBUtil.close(connection); } } public void delete(int id) { Connection connection=DBUtil.getConnection(); String sql="delete from t_user where id=?"; PreparedStatement preparedStatement=null; try { preparedStatement=connection.prepareStatement(sql); preparedStatement.setInt(1, id); preparedStatement.executeUpdate(); }catch(SQLException e) { e.printStackTrace(); }finally { //关闭资源 DBUtil.close(preparedStatement); DBUtil.close(connection); } } public void update(User user) { //获得连接对象 Connection connection=DBUtil.getConnection(); //准备sql语句 String sql="update t_user set teacher=?,address=? where id= ?"; //创建语句传输对象 PreparedStatement preparedStatement=null; try { preparedStatement=connection.prepareStatement(sql); preparedStatement.setString(1, user.getTeacher()); preparedStatement.setString(2, user.getAddress()); preparedStatement.setInt(3, user.getId()); preparedStatement.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { //关闭资源 DBUtil.close(preparedStatement); DBUtil.close(connection); } } @Override public User load(int id) { //获得连接对象 Connection connection=DBUtil.getConnection(); //准备sql语句 String sql="select * from t_user where id = ?"; //创建语句传输对象 PreparedStatement preparedStatement=null; ResultSet resultSet=null; //集合中只能放User对象 User user=null; try { preparedStatement=connection.prepareStatement(sql); preparedStatement.setInt(1, id); resultSet=preparedStatement.executeQuery(); //遍历结果集 while(resultSet.next()) { user=new User(); user.setId(id); user.setTeacher(resultSet.getString("teacher")); user.setCourse(resultSet.getString("class")); user.setAddress(resultSet.getString("address")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { //关闭资源 DBUtil.close(resultSet); DBUtil.close(preparedStatement); DBUtil.close(connection); } return user; } @Override public User load(String username) { //获得连接对象 Connection connection=DBUtil.getConnection(); //准备sql语句 String sql="select * from t_user where class = ?"; //创建语句传输对象 PreparedStatement preparedStatement=null; ResultSet resultSet=null; //集合中只能放User对象 User user=null; try { preparedStatement=connection.prepareStatement(sql); preparedStatement.setString(1,username); resultSet=preparedStatement.executeQuery(); //遍历结果集 while(resultSet.next()) { user=new User(); user.setCourse(username); user.setId(resultSet.getInt("id")); user.setTeacher(resultSet.getString("teacher")); user.setAddress(resultSet.getString("address")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { //关闭资源 DBUtil.close(resultSet); DBUtil.close(preparedStatement); DBUtil.close(connection); } return user; } @Override public List<User> load() { //获得连接对象 Connection connection=DBUtil.getConnection(); //准备sql语句 String sql="select * from t_user "; //创建语句传输对象 PreparedStatement preparedStatement=null; ResultSet resultSet=null; List<User> users=new ArrayList<User>(); User user=null; try { preparedStatement=connection.prepareStatement(sql); resultSet=preparedStatement.executeQuery(); //遍历结果集 while(resultSet.next()) { user=new User(); user.setId(resultSet.getInt("id")); user.setCourse(resultSet.getString("class")); user.setTeacher(resultSet.getString("teacher")); user.setAddress(resultSet.getString("address")); users.add(user); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { //关闭资源 DBUtil.close(resultSet); DBUtil.close(preparedStatement); DBUtil.close(connection); } return users; } public User load(String username, String password) { //获得连接对象 Connection connection=DBUtil.getConnection(); //准备sql语句 String sql="select * from t_user where class = ?"; //创建语句传输对象 PreparedStatement preparedStatement=null; ResultSet resultSet=null; //集合中只能放User对象 User user=null; try { preparedStatement=connection.prepareStatement(sql); preparedStatement.setString(1, username); resultSet=preparedStatement.executeQuery(); //遍历结果集 while(resultSet.next()) { user=new User(); user.setId(resultSet.getInt("id")); user.setCourse(resultSet.getString("class")); user.setTeacher(resultSet.getString("teacher")); user.setAddress(resultSet.getString("address")); } if(user==null) { throw new UserException("该课程信息不存在"); } if(!user.getTeacher().equals(password)) { throw new UserException("老师信息不正确"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { //关闭资源 DBUtil.close(resultSet); DBUtil.close(preparedStatement); DBUtil.close(connection); } return user; } }
UserException---自定义异常类
package com.jaovo.msg.Util; public class UserException extends RuntimeException{ public UserException() { super(); // TODO Auto-generated constructor stub } public UserException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); // TODO Auto-generated constructor stub } public UserException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public UserException(String message) { super(message); // TODO Auto-generated constructor stub } public UserException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } }
ValidateUtil.java ---错误信息捕捉
package com.jaovo.msg.Util; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.jaovo.msg.dao.UserDaoImpl; import com.jaovo.msg.model.User; public class ValidateUtil {//验证信息是否为空,Map容器(保存映射关系) public static boolean validateNull(HttpServletRequest request,String []fileds){//不为空(没有错误信息)--true 为空--返回false boolean validate=true; //map对象用来装载不同错误信息 Map<String,String> errorMsg=new HashMap();//<>泛型(map 装载错误信息,返回这个容器信息) for(String filed:fileds) { String value =request.getParameter(filed);//获取对应参数 if(value==null||"".equals(value.trim())) { validate=false; errorMsg.put(filed, filed+"不能为空");//键和值 } if(!validate) { request.setAttribute("errormsg",errorMsg);//map装进将容器中 } } return validate; } public static boolean validateError(HttpServletRequest request,String []fileds){//不为空(没有错误信息)--true 为空--返回false boolean validate=true; //map对象用来装载不同错误信息 UserDaoImpl userDao = new UserDaoImpl(); List<User> users = userDao.load(); Map<String,String> errorMsg=new HashMap();//<>泛型(map 装载错误信息,返回这个容器信息) for(String filed:fileds) { String value =request.getParameter(filed);//获取对应参数 if(value==null||"".equals(value.trim())) { validate=false; errorMsg.put(filed, filed+"不能为空");//键和值 } for( User user : users ){ if(value.equals(user.getCourse())) { errorMsg.put(filed, filed+"已存在");//键和值 } } if(!validate) { request.setAttribute("errormsg",errorMsg);//map装进将容器中 } } return validate; } public static String showError(HttpServletRequest request,String filed)//反射 { Map<String, String> errorMsg=(Map<String, String> )request.getAttribute("errormsg"); if(errorMsg==null) { return ""; } String msg=errorMsg.get(filed);//有对象 if(msg==null) { return ""; } return msg; } }
三、运行结果截图
表中原有:
添加新信息:
表中新信息:
list.jsp