作业 8-2自由编程
JAVABean -- Course.java
public class Course implements Serializable{
private int id;// 课程编号
private String name;//课程名
private String category;//所属方向
private String desp;//课程描述
private Date createTime;//创建时间
public Course() {
super();
}
public Course(int id, String name, String category, String desp, Date createTime) {
super();
this.id = id;
this.name = name;
this.category = category;
this.desp = desp;
this.createTime = createTime;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDesp() {
return desp;
}
public void setDesp(String desp) {
this.desp = desp;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
------------------------------
字符集过滤类-- CharacterFilter.java
public class CharacterFilter implements Filter{
//销毁方法
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
//设置请求字符集
//注意 这里的我们需要的是对HttpServletRequest,HttpServletResponse所以要对其进行强转,
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
//设置请求字符集格式
request.setCharacterEncoding("UTF-8");
//设置相应字符集
response.setContentType("text/html;charset=UTF-8");
//把请求和相应继续向后传递
arg2.doFilter(request, response);
//问题1:我记得这里向后传递的时候,可以传递reqeust、response 也可以
//向后传递arg0、arg1 之前学到过滤器的时候有同学问过,原因是什么不记得了?
}
//初始化方法
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
------------------------------
课程管理的接口类 -- CourseManage.java
/**
* 课程管理的接口类
* @author 25677
*
*/
public interface CourseManage {
//添加课程的方法
Boolean addCourse(Course course);
//读取所有课程的方法
List<Course> readAllCourse();
}
---------------------------------
课程管理的接口的实现类-- CourseManageImpl.java
public class CourseManageImpl implements CourseManage {
//连接对象
Connection conn = null;
//执行SQL对象
PreparedStatement pstmt = null;
//结果集对象
ResultSet rs = null;
/**
* addCourse - 添加课程的方法
* - 根据用户在首页输入的课程的课程名来进行判断
* - 如果相同,则返回false,添加失败,不相同才进行添加
*
*/
@Override
public Boolean addCourse(Course course) {
boolean flag = false;
try {
//1.获得连接
conn = ConnectionUtil.getConnection();
//2.编写SQL
String sql1 = "SELECT * FROM course WHERE name = ? ";
//3.预编译SQL
pstmt = conn.prepareStatement(sql1);
//4.设置?占位符中的具体值
pstmt.setString(1, course.getName());
//5.执行SQL
rs = pstmt.executeQuery();
//6.根据用户输入的
if(rs.next()) {
//有下一条记录说明存在相同的用户名直接返回false
return flag = false;
}else {
//不存在相同的用户名才执行保存操作
String name = course.getName();
String category = course.getCategory();
String desp = course.getDesp();
Date createTime = course.getCreateTime();
//编写保存操作的SQL
String sql2 = "INSERT INTO course(name,category,desp,createTime) VALUES(?,?,?,?)";
//预编译SQL
pstmt = conn.prepareStatement(sql2);
//设置值
pstmt.setString(1, name);
pstmt.setString(2, category);
pstmt.setString(3, desp);
pstmt.setDate(4, createTime);
//执行SQL
int i = pstmt.executeUpdate();
if(i>0) {
//影响行数大于1
return flag = true;
}else {
//影响行数小于1
return flag = false;
}
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
//释放资源
ConnectionUtil.release(rs, pstmt, conn);
}
return flag;
}
/**
* readAllCourse 读取所有课程的方法
*/
@Override
public List<Course> readAllCourse() {
//创建一个List集合用于存储所查询到的课程
List<Course> courseList = new ArrayList<Course>();
Course course = new Course();
try {
//从连接池中获取一个连接
conn = ConnectionUtil.getConnection();
//编写SQL
String sql = "SELECT * FROM course";
//预编译SQL
pstmt = conn.prepareStatement(sql);
//执行SQL
rs = pstmt.executeQuery();
while(rs.next()) {
course.setId(rs.getInt("id"));
course.setName(rs.getString("name"));
course.setCategory(rs.getString("category"));
course.setDesp(rs.getString("desp"));
course.setCreateTime(rs.getDate("createTime"));
courseList.add(course);
//问题2:创建一个新的对象 然后赋给course,让全部属性为空
//我尝试过直接course=null,但是结果只能显示第一条,之后的全部
//就为null了,有没有什么更好的办法
course = new Course();
}
}catch(Exception e) {
e.printStackTrace();
}finally {
//释放资源
ConnectionUtil.release(rs, pstmt, conn);
}
return courseList;
}
}64
收起
正在回答
4回答
同学你好,
1、代码完成的不错,继续努力!
2、对于同学询问的第一个问题,同学可以参考如下链接老师的回答:http://class.imooc.com/course/qadetail/175605
3、对于第二个问题,同学可以直接采用如下方式,获取查询出来的属性值,循环创建带参的course对象,进行赋值。添加到集合中。具体如下:

3、建议在进行插入时间时,可以直接使用now()函数,不需要再进行赋值。具体如下:

在Course类中使用@JSONField(format = "yyyy-MM-dd"),格式化json的时间属性

4、建议同学注意一下,命名规则, 当变量名由一个单词组成时,则该单词均小写。当由多个单词组成时,第一个单词所有字母均小写,从第二个单词开始,每个单词的首字母大写。如:CourseList应改为:courseList
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
jia_蛙
2020-01-12 17:31:33
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加课程</title>
<script type="text/javascript">
//表单验证
function validate_form(){
//获取课程名的值
var categoryId = document.getElementById("name").value;
if(categoryId == "" || categoryId == null){
alert("'课程名'不能为空!");
return false;
}
//获取所属方向的值
var categoryId = document.getElementById("category").value;
if(categoryId == "" || categoryId == null){
alert("'所属方向'不能为空!");
return false;
}
//获取课程描述的值
var categoryId = document.getElementById("desp").value;
if(categoryId == "" || categoryId == null){
alert(" '课程描述' 不能为空!");
return false;
}
}
</script>
</head>
<body>
<form onsubmit="return validate_form()" action="${pageContext.request.contextPath}/AddCourseServlet" method="post">
<div>
<h3>课程添加</h3>
课程名: <input type="text" name="name" id="name"><br>
所属方向:<input type="text" name="category" id="category" ><br>
课程描述: <input type= "text" name="desp" id="desp"><br>
</div>
<button type="submit">添加</button>
</form>
</body>
</html>
-----------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误跳转</title>
</head>
<body>
<h2 style="color:red">添加失败,课程名不能相同!</h2>
<a href="${pageContext.request.contextPath}/page/addCourse.jsp">点击返回添加页面</a><br>
<a href="${pageContext.request.contextPath}/page/showCourse.jsp">点击返回展示页面</a>
</body>
</html>
---------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>所有课程</title>
<%
String flag = request.getParameter("flag");
%>
<!-- 引入JQury文件 -->
<script type="text/javascript" src="../js/jquery-3.4.1.js"></script>
<script type="text/javascript">
var flag = '<%=flag%>';
if("1" == flag){
alert("添加成功!");
}
//页面就绪函数,该函数在页面加载完成之后就会自动执行
$(function(){
//使用JQ封装AJAX创建对象的方法: $.ajax
$.ajax({
//地址
"url":"/jdbcWork/ReadAllCourseServlet",
//请求方式
"type":"post",
"dataType":"json",
"success":function(json){
console.log(json);
for(var i =0;i<json.length;i++){
var c = json[i];
$("#div").append("<tr>" + "<th>" + c.name + "</th>"
+ "<th>" + c.category + "</th>"
+"<th>" + c.desp +"</th>"
+"<th>" + c.createTime + "</th>"
+ "</tr>");
}
}
})
})
</script>
</head>
<body>
<table id='div'>
<tr>
<th>课程名称</th>
<th>所属方向</th>
<th>课程描述</th>
<th>创建时间</th>
</tr>
</table>
</body>
jia_蛙
2020-01-12 17:29:21
添加课程的控制器 -- AAddCourseServlet.java
@WebServlet("/AddCourseServlet")
public class AddCourseServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接收参数
String name = (String) request.getParameter("name");
String category = (String)request.getParameter("category");
String desp = (String) request.getParameter("desp");
Date createTime = new Date(System.currentTimeMillis());
//2.封装数据
int id = 1;
Course course = new Course(id++,name,category,desp,createTime);
//3.处理参数
CourseManage courseManager = new CourseManageImpl();
//调用添加课程的方法
Boolean flag = courseManager.addCourse(course);
//4.返回结果
if(flag) {
//成功跳转至显示所有课程页面
response.sendRedirect(request.getContextPath() + "/page/showCourse.jsp?flag=1");
}else {
//失败跳转至添加页面提示添加失败
response.sendRedirect(request.getContextPath() + "/page/fail.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
---------------------------------------------
读取所有课程的控制器 -- ReadAllCourseServlet.java
@WebServlet("/ReadAllCourseServlet")
public class ReadAllCourseServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取数据
CourseManage courseManager = new CourseManageImpl();
List<Course> CourseList = courseManager.readAllCourse();
//2.使用fastJson的核心对象JSON中的toJSONString()方法对list对象进行序列化
String json = JSON.toJSONString(CourseList);
//3.把转换后的json字符串响应回去
response.getWriter().print(json);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
---------------------------------------------------
工具类 ConnectionUtil.java
public class ConnectionUtil {
//创建一个静态的连接池常量
private final static ComboPooledDataSource dataSource = new ComboPooledDataSource();
/**
* 获得连接的方法
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
Connection conn = dataSource.getConnection();
return conn;
}
/**
* 资源释放的方法
*/
public static void release(Statement stmt,Connection conn) {
if(stmt != null) {
try {
stmt.close();
}catch(SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if(conn != null) {
try {
conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
public static void release(ResultSet rs,Statement stmt,Connection conn) {
if(rs != null) {
try {
rs.close();
}catch(SQLException e) {
e.printStackTrace();
}
rs = null;
}
if(stmt != null) {
try {
stmt.close();
}catch(SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if(conn != null) {
try {
conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}

3. Java 数据库开发与实战应用
- 参与学习 人
- 提交作业 357 份
- 解答问题 8016 个
本阶段将带你学习MySQL数据库,JDBC接口,MyBatis框架等,带你掌握的数据的存放和管理。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星