之所以拿CategoryServlet純粹因為它比較簡單。
對于CategoryServlet的基本思路是:接收requst傳來的參數method,然后在根據method的要求來進行不同的操作。
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 }

點擊黃色小燈泡,IDE自動生成對應的方法,建議在這些方法后面添加throws語句。例:
2 throws ServletException, IOException {
3
4 }
a. add方法:接收分類名稱(category.name),QueryRunner對象根據sql命令執行update操作,request傳回結果(比如:轉到對應頁面)
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傳回結果(比如:轉到對應頁面)
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傳回結果,轉入對應編輯頁面;
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傳回結果(比如:轉到對應頁面);
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傳回結果(比如:轉到對應頁面);
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 }
在對數據進行操作之前首先要做的是:
1.加載jdbc驅動程序;
2.建立到指定數據庫的連接(連接池/數據源);
3.提交數據庫操作命令;
4.取得結果。
下面看一下BlogServlet中關于add方法中的 code5-1
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)
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可以簡化成
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 }
在后面的文章中,會詳細解釋。
1. 數據類
按照編程習慣首先創建package,項目名稱右鍵選擇New->Java package; package name填寫com.blog

在com.blog下面創建與數據表對應的Blog,Comment,Category以及User這4個類
blog.java
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
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
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
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
2. Servlet
考慮到如果按照以后jsp的功能來寫servlet的話,文件多了既混亂也不便于管理,所以按照數據類創建
BlogServlet(與blog相關的Servlet,如:添加,刪除,修改,瀏覽,查詢), CommentServlet, CategoryServlet和UserServlet,4個Servlet。


因為默認添加servlet信息到deployment文件,所以打開web.xml,相應的servlet信息已經被添加進去了。
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文件里可以查看到連接池和數據源的信息。
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
打開Netbeans,新建項目,分類(categories)里面選擇Java web,右邊項目(projects)選框里 web application。



在第一個項目里,不使用任何frameworks;所以直接選擇finish。
項目基本用到的幾個元素:
blog: 記錄博文信息,包括:博文編號(id),標題(title),內容(content),發布時間(date),分類編號(category_id)
category: 記錄分類信息,包括:分類編號(id),名稱(name)
comment: 記錄評論信息,包括:評論編號(id),評論人名(name),評論內容(content),發布時間(date),博客編號(blog_id)
users: 記錄用戶信息,包括:用戶編號(id),用戶名(username),密碼(password)
2 -- Table structure for blog
3 -- ----------------------------
4 DROP TABLE IF EXISTS `blog`;
5 CREATE TABLE `blog` (
6 `id` int(11) NOT NULL auto_increment,
7 `category_id` int(11) default 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(11) NOT 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(11) NOT NULL auto_increment,
31 `blog_id` int(11) default 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(11) NOT 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
考慮到中文亂碼問題,在生成Sql腳本的時候記得選擇utf-8編碼。
基本整理了一下從前的知識,計劃利用netbeans重新寫一下這個項目,說是盜版也好,抄襲也好,反正I dont care;
計劃是分別寫3個不同的版本(Servlet/Struts/Hibernate,Springs),算是拾回自己早已忘記的那點Java的東西。
基本的開發工具包括: Netbeans 6.7,MySql5.1以及GlassFish v2.x。
希望在接下來的10月能順利完成以上3個項目,在過去簡直是小菜一碟,現在么。。。。。。
從公司大門出來,長嘆了口氣,面試不過就這樣而已。不過我是還沒有清楚,我面試到底是面的什么職位。
昨天接到推薦朋友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 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也沒加判斷;
if (x>1){
return x*recursion(x-1);
}else{
return 1;
}
}
c. Hello World!
自己都想笑了,
當時我在whitebroad上鬼畫是
static public void main(){
println("Hello world!");
}
其實錯的還不算離譜。
System.out.println("Hello World!");
}
習慣了用IDE 工具以后很多超級基本的東西反而不會寫了;
coding的時候 用紙筆和電腦效果也果然是差別巨大;
當用電腦的時候思路如泉涌,打字基本不用經過大腦就直接出來了~
下次面試的時候給我臺PC就好了~
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).
*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.