Java课堂测试——课程管理
Posted ruangongyouxi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java课堂测试——课程管理相关的知识,希望对你有一定的参考价值。
Java课堂测试——课程管理
本周的Java课,王老师让学长们就上周的课堂测试内容进行了讲解。本次讲解加强了我对JavaWeb的项目的认识。虽然JSP文件和Servlet文件里面涉及到的各个方法我不能很好的理解,可是关于表单提交,和数据库的信息处理等代码,我勉强可以理解它们的作用,并可以根据自己的需要对现有的代码进行修改,实现自己需要的功能。就本周的测试而言,我可以实现大部分要求的功能,但是有很多不足之处,比如界面不美观,无法实现模糊查找等。我将对本次的实验做出如下总结。
首先创建一个类,在类里面实现数据库的连接,如下所示。
package 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() {
try {
//1 加载驱动
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String user = "root";
String password = "ms911";
String url = "jdbc:mysql://localhost:3306/test_db_person?useSSL=false&characterEncoding=UTF8"; //test数据库名
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();
}
}
}
在此段代码里面,要有驱动的加载,写入正确的数据库用户名、数据库密码以及数据库连接字符串。并且有资源的关闭函数。为了实现数据库的连接,需要将合适的包放在lib文件夹里面,并且在项目的Build Path选项里面将包导入。
还有一个Java文件里面写入数据信息的操作方法,即增删改查,具体代码如下所示。
package com.demo;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import util.DBUtil;
public class LoginerDaoImpl {
@SuppressWarnings("resource")//sql1
public User addUser(User user) {
Connection connection=DBUtil.getConnection();
String sql="insert into yonghu(id,password,place) values(?,?,?)";
// String sql1="insert into form1(userName,state) values(?,?)";
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
try {
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setString(1, user.getId());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setString(3, user.getPlace());
preparedStatement.executeUpdate();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
DBUtil.close(resultSet);
DBUtil.close(preparedStatement);
DBUtil.close(connection);
}
return user;
}
@SuppressWarnings("resource")
public void deleteUser(String userName) {
Connection connection = DBUtil.getConnection();
String sql = "delete from yonghu where id= ?";
// String sql1="delete from yonghu where userName=?";
PreparedStatement preparedStatement = null;
try {
preparedStatement= connection.prepareStatement(sql);
preparedStatement.setString(1, userName);
preparedStatement.executeUpdate();
// preparedStatement= connection.prepareStatement(sql1);
// preparedStatement.setString(1, userName);
// preparedStatement.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtil.close(preparedStatement);
DBUtil.close(connection);
}
}
public void updateUser(User user) {
Connection connection = DBUtil.getConnection();
String sql = "update yonghu set password=?,place=? where id=?";
PreparedStatement preparedStatement = null;
try {
preparedStatement= connection.prepareStatement(sql);
preparedStatement.setString(3, user.getId());
preparedStatement.setString(1, user.getPassword());
preparedStatement.setString(2, user.getPlace());
preparedStatement.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtil.close(preparedStatement);
DBUtil.close(connection);
}
}
public User loadUser(String id) {
Connection connection = DBUtil.getConnection();
String sql = "select * from yonghu where id=?";
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
User user = null;
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, id);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()) {
user = new User();
user.setId(id);
user.setPlace(resultSet.getString("place"));
user.setPassword(resultSet.getString("password"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DBUtil.close(connection);
DBUtil.close(resultSet);
DBUtil.close(preparedStatement);
}
return user;
}
public List<User> load() {
Connection connection = DBUtil.getConnection();
String sql = "select * from yonghu";
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.getString("id"));
user.setPassword(resultSet.getString("password"));
user.setPlace(resultSet.getString("place"));
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;
}
}
并且为了方便信息的处理,建立了一个类,代码如下:
package com.demo;
import java.sql.Connection;
public class User {
private String id;
private String password;
private String place;
public String getId() {
return id;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String id,String password) {
this.id=id;
this.password=password;
}
public User() {
// TODO Auto-generated constructor stub
}
}
实现主界面的代码如下。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="com.demo.LoginerDaoImpl" %>
<%@page import="com.demo.User" %>
<%@page import="java.util.List" %>
<%@page import="java.util.ArrayList" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="GB18030">
<title>菜单界面</title>
</head>
<%-- <%
String mess=(String)session.getAttribute("message");
if("success".equals(mess)){
%>
<script language=‘javascript‘>alert(‘成功!‘); </script>
<%
}
%> --%>
<body>
**********************<br>
增(输入数据库里面没有的课程信息,添加此条信息到数据库中):
<form action = "<%=request.getContextPath()%>/Zengjia" method="post">
课程名称:
<input type = "text" name="id" size="15"><br>
任课教师:
<input type = "text" name="password" size="15"><br>
上课地点:
<input type = "text" name="place" size="15"><br>
<input type = "submit" value = "确定">
</form>
**********************<br>
删(输入数据库里面已有的课程名称):
<form action = "delete.jsp" method="post">
课程名称:
<input type = "text" name="id1" size="15"><br>
<input type = "submit" value = "确定">
</form>
**********************<br>
改(输入数据库中已有的课程名称以及更改后的任课教师信息以及更改后的上课地点):
<form action = "<%=request.getContextPath()%>/Xiugai" method="post">
课程名称:
<input type = "text" name="id" size="15"><br>
任课教师:
<input type = "text" name="password" size="15"><br>
上课地点:
<input type = "text" name="place" size="15"><br>
<input type = "submit" value = "确定">
</form>
**********************<br>
查(输入数据库里面已有的课程信息):
<form action = "dange.jsp" method="post">
课程信息:
<input type = "text" name="id1" size="15"><br>
<input type = "submit" value = "确定">
</form>
**********************<br>
<input type="button" value="显示全部" onclick="window.location.href=‘quanbu.jsp‘;"/><br>
**********************<br>
</body>
</html>
在主界面中有为了实现各种功能而创建的表单,以及跳转到别的JSP文件的按钮。
首先是增加信息的功能。在表单里面填写入相应的信息之后,点击提交按钮,将会跳转到相应的Servlet界面,对应的代码如下。
package com.demo;
import java.io.IOException;
import java.io.PrintWriter;
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 javafx.scene.control.Alert;
/**
* Servlet implementation class Zengjia
*/
@WebServlet("/Zengjia")
public class Zengjia extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Zengjia() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request. setCharacterEncoding("UTF-8");
LoginerDaoImpl daoImpl=new LoginerDaoImpl();
String id1=request.getParameter("id");
String mima1=request.getParameter("password");
String didian=request.getParameter("place");
PrintWriter out = response.getWriter();
if(mima1.equals("王建民")||mima1.equals("刘立嘉")||mima1.equals("刘丹")||mima1.equals("王辉")||mima1.equals("杨子光")) {
out.print("<script>alert(‘The teacher is right!‘);window.location.href=‘success.jsp‘</script>");
}
if(daoImpl.loadUser(id1)!=null) {
out.print("<script>alert(‘The course information already exists!‘);window.location.href=‘success.jsp‘</script>");
//System.out.println("已存在");
//response.sendRedirect("success.jsp");
return;
}
User user=new User();
user.setId(id1);
user.setPassword(mima1);
user.setPlace(didian);
daoImpl.addUser(user);
response.sendRedirect("success.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
在这段代码里面,获取表单里面的内容。会进行两个判断,判断课程的老师是否为指定得那些老师,并且根据课程名字判断是否已经有了这门课。如果这门课程已经存在的话,则会弹出提示,并且将页面跳转到主界面上,如果课程名称没有重复,则会调用相应的函数进行信息的添加。添加成功之后将页面跳转到主界面上。
提交课程删除的表单,写入课程名称之后,点击提交按钮,将会跳转到对应的JSP文件上,代码如下所示:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="com.demo.LoginerDaoImpl" %>
<%@page import="com.demo.User" %>
<%@page import="java.util.List" %>
<%@page import="java.util.ArrayList" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="GB18030">
<title>查询单个信息</title>
</head>
<%
User user=new User();
request.setCharacterEncoding("UTF-8");
LoginerDaoImpl daoImpl=new LoginerDaoImpl();
String id1=request.getParameter("id1");
user=daoImpl.loadUser(id1);
%>
<body>
课程名称:
<%=user.getId()%><br>
任课教师:
<%=user.getPassword() %><br>
上课地点:
<%=user.getPlace() %><br>
<form action = "<%=request.getContextPath()%>/Shanchu" method="post">
请再次确认本课程名称:
<input type = "text" name="id1" size="15"><br>
<input type = "submit" value = "确定删除">
</form>
</body>
</html>
在这段代码里面调用带参数的查询方法,根据表单提交的课程名称,将对应的课程信息继续输出显示。并会在此界面上提供一个表单。确认删除的课程名字,输入名字,点击提交按钮之后将会跳转到相应的Servlet文件上,在此文件获取表单里面的课程名称。调用方法进行删除,并且将页面跳转到主界面。
同理,对于信息的修改,以及信息的查询也是像上述的步骤一样。继续信息的处理。
关于修改的代码如下:
package com.demo;
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;
/**
* Servlet implementation class Xiugai
*/
@WebServlet("/Xiugai")
public class Xiugai extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Xiugai() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
LoginerDaoImpl daoImpl=new LoginerDaoImpl();
String id1=request.getParameter("id");
String mima1=request.getParameter("password");
String didian=request.getParameter("place");
User user=new User();
user.setId(id1);
user.setPassword(mima1);
user.setPlace(didian);
daoImpl.updateUser(user);
response.sendRedirect("success.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
带参数查询的查询代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="com.demo.LoginerDaoImpl" %>
<%@page import="com.demo.User" %>
<%@page import="java.util.List" %>
<%@page import="java.util.ArrayList" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="GB18030">
<title>查询单个信息</title>
</head>
<%
User user=new User();
request.setCharacterEncoding("UTF-8");
LoginerDaoImpl daoImpl=new LoginerDaoImpl();
String id1=request.getParameter("id1");
user=daoImpl.loadUser(id1);
%>
<body>
课程名称:
<%=user.getId()%><br>
任课教师:
<%=user.getPassword() %><br>
上课地点:
<%=user.getPlace() %><br>
**********************<br>
<input type="button" value="返回功能界面" onclick="window.location.href=‘success.jsp‘;"/><br>
**********************<br>
</body>
</html>
查询全部信息的代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="com.demo.LoginerDaoImpl" %>
<%@page import="com.demo.User" %>
<%@page import="java.util.List" %>
<%@page import="java.util.ArrayList" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="GB18030">
<title>显示全部信息</title>
</head>
<%
LoginerDaoImpl loginerDaoImpl=new LoginerDaoImpl();
List<User> users = new ArrayList<User>();
User user=new User();
users=loginerDaoImpl.load();
%>
<body>
<table>
<tr>
<td>课程名称</td>
<td>任课教师</td>
<td>上课地点</td>
</tr>
<%for(User u:users) { %>
<tr>
<td><%=u.getId() %></td>
<td><%=u.getPassword() %></td>
<td><%=u.getPlace() %></td>
</tr>
<%} %>
</table>
**********************<br>
<input type="button" value="返回功能界面" onclick="window.location.href=‘success.jsp‘;"/><br>
**********************<br>
</body>
</html>
在本次的实验中,遇到了中文信息乱码的问题,通过将一些属性设置为UTF-8,我对这一问题进行了解决。
以上是关于Java课堂测试——课程管理的主要内容,如果未能解决你的问题,请参考以下文章