两亩三分地

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  17 随笔 :: 20 文章 :: 2 评论 :: 0 Trackbacks

#

     摘要: adminCategoryList.jsp 管理Category数据,对其进行修改或删除操作 Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> 1 <%@ page language=...  阅读全文
posted @ 2009-09-28 18:47 Chucky 阅读(97) | 评论 (0)编辑 收藏

CategoryServlet,正如第4篇中提到的这个Servlet主要是针对Category数据的操作,包括添加,删除,修改,更新等等。
之所以拿CategoryServlet纯粹因为它比较简单。

对于CategoryServlet的基本思路是:接收requst传来的参数method,然后在根据method的要求来进行不同的操作。
 1 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
 2             throws ServletException, IOException {
 3         response.setContentType("text/html;charset=UTF-8");
 4         request.setCharacterEncoding("UTF-8");
 5         String method = request.getParameter("method");
 6         if (method.equals("add")) {
 7             add(request, response);
 8         } else if (method.equals("delete")) {
 9             delete(request, response);
10         } else if (method.equals("edit")) {
11             preEdit(request, response);
12         } else if (method.equals("update")) {
13             update(request, response);
14         } else if (method.equals("list")) {
15             list(request, response);
16         }
17 }
直接添加这些方法,netbeans会有无法找到对应方法的提示,


点击黄色小灯泡,IDE自动生成对应的方法,建议在这些方法后面添加throws语句。例:
1 private void add(HttpServletRequest request, HttpServletResponse response)
2             throws ServletException, IOException {
3
4         }

a. add方法:接收分类名称(category.name),QueryRunner对象根据sql命令执行update操作,request传回结果(比如:转到对应页面)
 1 private void add(HttpServletRequest request, HttpServletResponse response)
 2             throws ServletException, IOException {
 3         String name = request.getParameter("name");
 4         String sql = "insert into category (name) values (?)";
 5         String params[] = {name};
 6         QueryRunner qr = DbHelper.getQueryRunner();
 7         try {
 8             qr.update(sql, params);
 9         } catch (SQLException ex) {
10             Logger.getLogger(CategoryServlet.class.getName()).log(Level.SEVERE, null, ex);
11         }
12         list(request,response);
13     }

b. delete方法:接收分类类别(category.id),QueryRunner对象根据sql语句执行update操作,request传回结果(比如:转到对应页面)
 1 private void delete(HttpServletRequest request, HttpServletResponse response)
 2             throws ServletException, IOException {
 3         String id = request.getParameter("id");
 4         String sql = "delete from category where id = "+id;
 5         
 6         QueryRunner qr = DbHelper.getQueryRunner();
 7         try {
 8             qr.update(sql);
 9         } catch (SQLException ex) {
10             Logger.getLogger(CategoryServlet.class.getName()).log(Level.SEVERE, null, ex);
11         }
12         
13         list(request,response);
14     }

c. preEdit方法:接收分类类别(category.id),QueryRunner对象根据sql语句执行query操作,request传回结果,转入对应编辑页面;
 1 private void preEdit(HttpServletRequest request, HttpServletResponse response)
 2             throws ServletException, IOException {
 3         String id = request.getParameter("id");
 4         String sql = "select id,name from category where id = "+id;
 5         List categories = null;
 6         Category category = null;
 7         
 8         QueryRunner qr = DbHelper.getQueryRunner();
 9         try {
10             categories = (List) qr.query(sql, new BeanListHandler(Category.class));
11         } catch (SQLException ex) {
12             Logger.getLogger(CategoryServlet.class.getName()).log(Level.SEVERE, null, ex);
13         }
14         
15         if (categories != null){
16             category = (Category)categories.get(0);
17         }
18         request.setAttribute("category", category);
19         request.getRequestDispatcher("/admin/editCategory.jsp").forward(request, response);
20     }

d. update方法:接收分类名称(name),编号(id),QueryRunner对象根据sql语句执行update操作,request传回结果(比如:转到对应页面);
 1  private void update(HttpServletRequest request, HttpServletResponse response)
 2             throws ServletException, IOException {
 3         String id = request.getParameter("id");
 4         String name = request.getParameter("name");
 5         String sql = "update category set name = ? where id = ?";
 6         String params[] = {name,id};
 7         
 8         QueryRunner qr = DbHelper.getQueryRunner();
 9         try {
10             qr.update(sql, params);
11         } catch (SQLException ex) {
12             Logger.getLogger(CategoryServlet.class.getName()).log(Level.SEVERE, null, ex);
13         }
14         list(request,response);
15     }

e. list方法:list所有相关的分类,request传回结果(比如:转到对应页面);
 1  private void list(HttpServletRequest request, HttpServletResponse response)
 2             throws ServletException, IOException {
 3         String sql = "select id, name from category order by name";
 4         List categories = null;
 5 
 6         QueryRunner qr = DbHelper.getQueryRunner();
 7         try {
 8             categories = (List) qr.query(sql, new BeanListHandler(Category.class));
 9         } catch (SQLException ex) {
10             Logger.getLogger(CategoryServlet.class.getName()).log(Level.SEVERE, null, ex);
11         }
12 
13         request.setAttribute("categories", categories);
14         request.getRequestDispatcher("/admin/adminCategoryList.jsp").forward(request, response);
15     }


posted @ 2009-09-28 17:12 Chucky 阅读(101) | 评论 (0)编辑 收藏

我们都知道一个数据系统的核心就是JDBC的编程,对数据进行操作,主要包括添加,删除,更新以及查询。
在对数据进行操作之前首先要做的是:
   
    1.加载jdbc驱动程序;
    2.建立到指定数据库的连接(连接池/数据源);
    3.提交数据库操作命令;
    4.取得结果。

下面看一下BlogServlet中关于add方法中的 code5-1
 1
 1 private void add(HttpServletRequest request, HttpServletResponse response)
 2             throws ServletException, IOException{
 3         response.setContentType("text/html;charset=UTF-8");
 4         request.setCharacterEncoding("UTF-8");
 5 
 6         String title = request.getParameter("title");
 7         String content = request.getParameter("content");
 8         String categoryId = request.getParameter("category");
 9 
10         String sql =  "insert into blog(title,content,category_id,date) values(?,?,?,now())";
11         String params[] = {title,content,categoryId};
12         QueryRunner qr = DbHelper.getQueryRunner();
13         int result = 0;
14 
15         try {
16           result = qr.update(sql, params);
17         } catch (SQLException ex) {
18             Logger.getLogger(BlogServlet.class.getName()).log(Level.SEVERE, null, ex);
19         }
20     }

在后面的文章中我们会提到apache提供的commons-dbutils-1.2jar有点小问题,这个我们以后还会提到。

由于每次对jdbc编程少不了建立数据源,获取数据源,建立连接的工作,所以这里再提供一个辅助类DbHelper来完成以上工作。
DbHelper.java (code 5-2)
 1 package com.blog.utils;
 2 
 3 import java.util.logging.Level;
 4 import java.util.logging.Logger;
 5 import javax.naming.Context;
 6 import javax.naming.InitialContext;
 7 import javax.naming.NamingException;
 8 import javax.sql.DataSource;
 9 import org.apache.commons.dbutils.QueryRunner;
10 
11 /**
12  *
13  * @author Chucky
14  */
15 public class DbHelper {
16 
17     public static QueryRunner getQueryRunner() {
18         DataSource ds = null;
19         Context context = null;
20         try {
21             context = new InitialContext();
22             ds = (DataSource) context.lookup("jdbc/Blog");
23         } catch (NamingException ex) {
24             Logger.getLogger(DbHelper.class.getName()).log(Level.SEVERE, null, ex);
25         }
26         QueryRunner qr = new QueryRunner(ds);
27         return qr;
28     }
29 }

现在通过DbUtils库和DbHelper辅助类的使用,原先code 5-1可以简化成
 1 private void add(HttpServletRequest request, HttpServletResponse response)
 2             throws ServletException, IOException{
 3         response.setContentType("text/html;charset=UTF-8");
 4         request.setCharacterEncoding("UTF-8");
 5 
 6         String title = request.getParameter("title");
 7         String content = request.getParameter("content");
 8         String categoryId = request.getParameter("category");
 9 
10         String sql =  "insert into blog(title,content,category_id,date) values(?,?,?,now())";
11         String params[] = {title,content,categoryId};
12         QueryRunner qr = DbHelper.getQueryRunner();
13         int result = 0;
14 
15         try {
16           result = qr.update(sql, params);
17         } catch (SQLException ex) {
18             Logger.getLogger(BlogServlet.class.getName()).log(Level.SEVERE, null, ex);
19         }
20     }
QueryRunner类是DbUtils的核心类,只要通过query()方法对数据查询或update()对数据删除delete/添加insert/更新update;
在后面的文章中,会详细解释。

posted @ 2009-09-28 16:24 Chucky 阅读(487) | 评论 (2)编辑 收藏

项目开发的准备工作已经差不多了,现在需要的是与数据表对应的数据类。
1. 数据类
按照编程习惯首先创建package,项目名称右键选择New->Java package; package name填写com.blog

在com.blog下面创建与数据表对应的Blog,Comment,Category以及User这4个类
blog.java
 1 /*
 2  * To change this template, choose Tools | Templates
 3  * and open the template in the editor.
 4  */
 5 
 6 package com.blog;
 7 
 8 import java.util.Date;
 9 
10 /**
11  *
12  * @author Chucky
13  */
14 public class Blog {
15     private int id;
16     private String title;
17     private String content;
18     private Date date;
19     private int categoryId;
20     private String category;
21 
22     public String getCategory() {
23         return category;
24     }
25 
26     public void setCategory(String category) {
27         this.category = category;
28     }
29 
30     public int getCategoryId() {
31         return categoryId;
32     }
33 
34     public void setCategoryId(int categoryId) {
35         this.categoryId = categoryId;
36     }
37 
38     public String getContent() {
39         return content;
40     }
41 
42     public void setContent(String content) {
43         this.content = content;
44     }
45 
46     public Date getDate() {
47         return date;
48     }
49 
50     public void setDate(Date date) {
51         this.date = date;
52     }
53 
54     public int getId() {
55         return id;
56     }
57 
58     public void setId(int id) {
59         this.id = id;
60     }
61 
62     public String getTitle() {
63         return title;
64     }
65 
66     public void setTitle(String title) {
67         this.title = title;
68     }
69     
70 }
71 
Category.java
 1 /*
 2  * To change this template, choose Tools | Templates
 3  * and open the template in the editor.
 4  */
 5 
 6 package com.blog;
 7 
 8 /**
 9  * This is category class which records id and name
10  * @author Chucky
11  */
12 public class Category {
13     private int id;
14     private String name;
15 
16     public int getId() {
17         return id;
18     }
19 
20     public void setId(int id) {
21         this.id = id;
22     }
23 
24     public String getName() {
25         return name;
26     }
27 
28     public void setName(String name) {
29         this.name = name;
30     }
31     
32 }
33 
Comment.java
 1 /*
 2  * To change this template, choose Tools | Templates
 3  * and open the template in the editor.
 4  */
 5 
 6 package com.blog;
 7 
 8 import java.util.Date;
 9 
10 /**
11  * this is comment class which records id,name,content,date and blog_id
12  * @author Chucky
13  */
14 public class Comment {
15     private int id;
16     private String name;
17     private String content;
18     private Date date;
19     private int blog_id;
20 
21     public int getBlog_id() {
22         return blog_id;
23     }
24 
25     public void setBlog_id(int blog_id) {
26         this.blog_id = blog_id;
27     }
28 
29     public String getContent() {
30         return content;
31     }
32 
33     public void setContent(String content) {
34         this.content = content;
35     }
36 
37     public Date getDate() {
38         return date;
39     }
40 
41     public void setDate(Date date) {
42         this.date = date;
43     }
44 
45     public int getId() {
46         return id;
47     }
48 
49     public void setId(int id) {
50         this.id = id;
51     }
52 
53     public String getName() {
54         return name;
55     }
56 
57     public void setName(String name) {
58         this.name = name;
59     }
60     
61 }
62 
User.java
 1 /*
 2  * To change this template, choose Tools | Templates
 3  * and open the template in the editor.
 4  */
 5 
 6 package com.blog;
 7 
 8 /**
 9  *
10  * @author Chucky
11  */
12 public class User {
13     private int id;
14     private String userName;
15     private String password;
16 
17     public int getId() {
18         return id;
19     }
20 
21     public void setId(int id) {
22         this.id = id;
23     }
24 
25     public String getPassword() {
26         return password;
27     }
28 
29     public void setPassword(String password) {
30         this.password = password;
31     }
32 
33     public String getUserName() {
34         return userName;
35     }
36 
37     public void setUserName(String userName) {
38         this.userName = userName;
39     }
40 
41 }
42 
值得注意的是为了开发的方便,在Blog.java里与数据表不同,多了一个category属性。


2. Servlet
考虑到如果按照以后jsp的功能来写servlet的话,文件多了既混乱也不便于管理,所以按照数据类创建
BlogServlet(与blog相关的Servlet,如:添加,删除,修改,浏览,查询), CommentServlet, CategoryServlet和UserServlet,4个Servlet。


因为默认添加servlet信息到deployment文件,所以打开web.xml,相应的servlet信息已经被添加进去了。

posted @ 2009-09-28 15:41 Chucky 阅读(114) | 评论 (0)编辑 收藏

1.连接池
a.点击项目名称,右键选择New(新建)->other...


b.在categories选框里选择:Glassfish   右边File types(文件类型)选择:JDBC Connection Pool


c.JDBC Connection Pool Name(JDBC连接池名称):输入BlogPool;连接之前创建的blogs库。


d.全部默认选项,按finish(完成),连接池算是创建完成了。


2. 数据源
按步骤1-a,1-b选择JDBC Resource

c.Gerneral Attributes(一般属性)Connection Pool选择Use Existing JDBC Connetion Pool(使用已有的连接池)
下拉单里选择刚刚创建的BlogPool,JNDI Name里填写:jdbc/Blog

Finish以后,在项目的Server Resources的sun-resources.xml文件里可以查看到连接池和数据源的信息。
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE resources PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Resource Definitions //EN" "http://www.sun.com/software/appserver/dtds/sun-resources_1_3.dtd">
 3 <resources>
 4   <jdbc-resource enabled="true" jndi-name="jdbc/Blog" object-type="user" pool-name="BlogPool">
 5     <description/>
 6   </jdbc-resource>
 7   <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="BlogPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
 8     <property name="URL" value="jdbc:mysql://localhost:3306/blogs"/>
 9     <property name="User" value="root"/>
10     <property name="Password" value="()"/>
11   </jdbc-connection-pool>
12 </resources>
13 

posted @ 2009-09-28 15:05 Chucky 阅读(259) | 评论 (0)编辑 收藏

建表等工作完成(关于MySql在Netbeans的配置可以参考一下之前的文章)。开工。

打开Netbeans,新建项目,分类(categories)里面选择Java web,右边项目(projects)选框里 web application。



在第一个项目里,不使用任何frameworks;所以直接选择finish。



posted @ 2009-09-28 14:46 Chucky 阅读(132) | 评论 (0)编辑 收藏

Blog-又称博客,现在基本所有大大小小门户网站都有自己的博客园;大凡网民十之五六有自己的博客。
项目基本用到的几个元素:
blog:  记录博文信息,包括:博文编号(id),标题(title),内容(content),发布时间(date),分类编号(category_id)
category: 记录分类信息,包括:分类编号(id),名称(name)
comment: 记录评论信息,包括:评论编号(id),评论人名(name),评论内容(content),发布时间(date),博客编号(blog_id)
users: 记录用户信息,包括:用户编号(id),用户名(username),密码(password)
 1 -- ----------------------------
 2 -- Table structure for blog
 3 -- ----------------------------
 4 DROP TABLE IF EXISTS `blog`;
 5 CREATE TABLE `blog` (
 6   `id` int(11NOT NULL auto_increment,
 7   `category_id` int(11default NULL,
 8   `title` varchar(400) collate utf8_unicode_ci default NULL,
 9   `content` varchar(4000) collate utf8_unicode_ci default NULL,
10   `date` datetime default NULL,
11   PRIMARY KEY  (`id`),
12   KEY `FK_Relationship_1` (`category_id`)
13 ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
14 
15 -- ----------------------------
16 -- Table structure for category
17 -- ----------------------------
18 DROP TABLE IF EXISTS `category`;
19 CREATE TABLE `category` (
20   `id` int(11NOT NULL auto_increment,
21   `name` varchar(200) collate utf8_unicode_ci default NULL,
22   PRIMARY KEY  (`id`)
23 ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
24 
25 -- ----------------------------
26 -- Table structure for comment
27 -- ----------------------------
28 DROP TABLE IF EXISTS `comment`;
29 CREATE TABLE `comment` (
30   `id` int(11NOT NULL auto_increment,
31   `blog_id` int(11default NULL,
32   `name` varchar(200) collate utf8_unicode_ci default NULL,
33   `content` varchar(1000) collate utf8_unicode_ci default NULL,
34   `date` datetime NOT NULL,
35   PRIMARY KEY  (`id`),
36   KEY `FK_Relationship_2` (`blog_id`)
37 ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
38 
39 -- ----------------------------
40 -- Table structure for users
41 -- ----------------------------
42 DROP TABLE IF EXISTS `users`;
43 CREATE TABLE `users` (
44   `id` int(11NOT NULL auto_increment,
45   `username` varchar(200) collate utf8_unicode_ci default NULL,
46   `password` varchar(200) collate utf8_unicode_ci default NULL,
47   PRIMARY KEY  (`id`)
48 ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
49 
利用PowerDesigner可以很容易的设计并创建出相应的实体模型,并建立个各个实体之间的关系; 最后转换生成相应的sql的脚本。
考虑到中文乱码问题,在生成Sql脚本的时候记得选择utf-8编码。

posted @ 2009-09-28 14:29 Chucky 阅读(141) | 评论 (0)编辑 收藏

最近很闲,闲到无所事事。偶尔看到之前下载的《v512工作室_Java高端培训系列视频》中关于J2EE博客系统开发的讲座,一口气把37章看完,也算是恶补了一下J2EE的知识吧;
基本整理了一下从前的知识,计划利用netbeans重新写一下这个项目,说是盗版也好,抄袭也好,反正I dont care;
计划是分别写3个不同的版本(Servlet/Struts/Hibernate,Springs),算是拾回自己早已忘记的那点Java的东西。
基本的开发工具包括: Netbeans 6.7,MySql5.1以及GlassFish v2.x。

希望在接下来的10月能顺利完成以上3个项目,在过去简直是小菜一碟,现在么。。。。。。
posted @ 2009-09-28 13:39 Chucky 阅读(75) | 评论 (0)编辑 收藏

1.
从公司大门出来,长叹了口气,面试不过就这样而已。不过我是还没有清楚,我面试到底是面的什么职位。

昨天接到推荐朋友email说是和Oracle相关的初级职位,可是鬼子看了我的resume,一个劲地问点C和C++的东西。

浦西到浦东尽管有地铁,可是到张江还是很远的。家里过去足足1个半小时。

面试的是两个技术人员,一中国女人和一个印度小伙。读书时候印度鬼子见多了,所以到也不怕,中国人的话底细倒是不清楚了。
不过一上来人家就开英文,我只想说 那女的英文SUCKS 。最后她倒是先投降讲中文了。不过后面的面试题我可以撞墙去了。
一个打印倒3角, 一个是递归;最惨的是之前表现太差,最后让我写个HELLO WORLD 没写出来~
可以买豆腐撞死了。

2.

在回家的地铁上 所以有时间重新思考一下 刚才的题目。
倒3角
         1
       22
     333
   4444
 55555
2个循环 第一负责打空格 第2个打数字可以吗?

递归算法 5! = 5 * 4 * 3 * 2 * 1
算法本身应该有RETURN 和 一个判断

Hello World 不说了 回家自己翻入门书吧 一般总在前面几章

3.

到家,先跟家里人汇报一下面试情况,少不了被老头子批一顿。
打开Netbeans, 5分钟不到把几道问题都给解了~
我真是可以撞墙了~

a. 倒三角 Netbeans 新建project
for (int i = 0; i < 5; i++) {
            for (int j = 4; j >= 0; j--) {
                if (j > i) {
                    System.out.print(" ");
                } else {
                    System.out.print(i + 1);
                }
            }
            System.out.println();
        }

b. Recursion (印度鬼在纸上写了这个单词,我第一反应是类似循环,中国女的竟然说Loop -_-!)
出了门才想起来 这个中文叫递归~
当时在纸上胡乱写了2笔,没有写return也没加判断;
static private int recursion(int x) {
        
if (x>1){
            
return x*recursion(x-1);
        }
else{
            
return 1;
        }
    }

c. Hello World!
自己都想笑了,
当时我在whitebroad上鬼画是
static public void main(){
    println("Hello world!");
}
其实错的还不算离谱。
public static void main (String[] args){
  System.out.println(
"Hello World!");
}

习惯了用IDE 工具以后很多超级基本的东西反而不会写了;
coding的时候 用纸笔和电脑效果也果然是差别巨大;
当用电脑的时候思路如泉涌,打字基本不用经过大脑就直接出来了~
 
下次面试的时候给我台PC就好了~

posted @ 2008-12-04 20:39 Chucky 阅读(191) | 评论 (0)编辑 收藏

Finally I would get a job interview for junior Java developer position. So these days I try to prepare as much as possible for that interview.

Now the question is what a junior Java developer should know? There are some suggestions.

As a junior Java developer you’d be expected to know the basics of the language.

(Try practice tests for the Sun Certification exams although I’m not convinced you need to do the exam itself).

 Then you should also know:

     *Basic design patterns, why you need them and how to implement them in Java.

     * MVC framework – know how Struts works

     * XML basics (how to parse, manipulate and create – SAX/DOM/XSLT)

     * JDBC

     * Know how to use an IDE such as Eclipse or IntelliJ IDEA (Eclipse is most common)

     * Know what Inversion of Control is and what are its advantages

     * Know how to write unit tests using JUnit

       * Know what is Continuous integration testing

       * Know what mock testing

     * Familiarize yourself with different components of J2EE, what they are and what they’re useful for.

     * Know Ant

This is a basic list of what I think would get you through most Junior/entry level Java job interview.
If you have more time, start playing with Spring, Hibernate, JSF etc and spend some time learning to build/package a WebApp and deploy it to a container.



posted @ 2008-11-22 16:10 Chucky 阅读(115) | 评论 (0)编辑 收藏

仅列出标题
共4页: 上一页 1 2 3 4 下一页