作业 8-2自由编程

作业 8-2自由编程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
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;
    }
}


正在回答

登陆购买课程后可参与讨论,去登陆

4回答

同学你好,

1、代码完成的不错,继续努力!

2、对于同学询问的第一个问题,同学可以参考如下链接老师的回答:http://class.imooc.com/course/qadetail/175605 

3、对于第二个问题,同学可以直接采用如下方式,获取查询出来的属性值,循环创建带参的course对象,进行赋值。添加到集合中。具体如下:

http://img1.sycdn.imooc.com//climg/5e1af930097725d407900204.jpg

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

http://img1.sycdn.imooc.com//climg/5e1afd5e09e1dcf610200269.jpg

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

http://img1.sycdn.imooc.com//climg/5e1afd770954dd9b05590098.jpg

4、建议同学注意一下,命名规则, 当变量名由一个单词组成时,则该单词均小写。当由多个单词组成时,第一个单词所有字母均小写,从第二个单词开始,每个单词的首字母大写。如:CourseList应改为:courseList

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!

  • jia_蛙 提问者 #1
    谢谢老师!
    2020-01-12 20:50:41
提问者 jia_蛙 2020-01-12 17:36:11
1
2
3
4
5
6
7
8
9
10
功能粗略的实现了,还有很多地方要修改,之前web的知识点很多都要看笔记,忘了很多,我有两个
问题,想问一下老师:
1.就是过滤器那里,为什么向后传递强转后的对象和直接传递没强转的两个
对象都可以达到过滤的效果?
 
2.创建一个新的对象 然后赋给course,让全部属性为空
我尝试过直接course=null,但是结果只能显示第一条,之后的全部
就为null了,有没有什么更好的办法
 
麻烦老师在看看有没有那里有可以修改的更好一点的地方


提问者 jia_蛙 2020-01-12 17:31:33
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<%@ 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
添加课程的控制器 -- 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;
        }
    }
}

http://img1.sycdn.imooc.com//climg/5e1ae6d8093626cc03380486.jpg

http://img1.sycdn.imooc.com//climg/5e1ae6ee09a7a9a903370630.jpg

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师
插入代码