|
1. 靜態(tài)頁面的亂碼問題 文件的編碼和瀏覽器要顯示的編碼不一致。 1) 檢查文件原始的編碼, 可以用記事本打開, 然后選擇另存為來看; 2) 給當前頁面加入一個指令來建議瀏覽器用指定的編碼來顯示文件字符內(nèi)容. <meta http-equiv="content-type" content="text/html; charset=GBK"> 3) 如果系統(tǒng)是英文XP,沒裝東亞字符集支持, 也會顯示亂碼. 2. JSP 頁面的亂碼問題 1) page 指令有個 pageEncoding="GBK" 這個會指定當前頁面保存的編碼, 如果寫成ISO8859-1就不能保存漢字; 2) page 指令的 contentType="text/html; charset=ISO8859-1" 也會像靜態(tài)頁面一樣讓瀏覽器來優(yōu)先選擇一種編碼. 如果JSP亂碼的話,一般就顯示成?,而且不管你給瀏覽器選什么樣的編碼,它都不能正確顯示 3. 表單提交的亂碼問題(Tomcat 特有) 1). POST 的亂碼 a. 首先瀏覽器提交表單的編碼是根據(jù)表單所在頁面來決定的, 而不是根據(jù)提交后的 JSP 頁面的編碼來決定的. 把所有的頁面的編碼都設置成一樣的,例如 GBK. b. 處理方式就是在獲取參數(shù)之前設置編碼: request.setCharacterEncoding("GBK"); c. 可以用過濾器的方式來解決, Tomcat 已經(jīng)帶了一個現(xiàn)成的: apache-tomcat-5.5.23\webapps\jsp-examples\WEB-INF\classes\filters\SetCharacterEncodingFilter.java web.xml <filter> <filter-name>Set Character Encoding</filter-name> <filter-class>filters.SetCharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>GBK</param-value> </init-param> </filter> <filter-mapping> <filter-name>Set Character Encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 2) GET 方式的亂碼 用 setCharacterEncoding() 不能解決. TOMCAT 的一個BUG, GET 方式傳送的表單參數(shù)總是用的 ISO8859-1 編碼. 我們要把它轉(zhuǎn)成 GBK 方式. String username = request.getParameter("username"); System.out.println(username); // 轉(zhuǎn)碼, 先取得原始的二進制字節(jié)數(shù)組 byte[] data = username.getBytes("ISO8859-1"); // 根據(jù)新的字符集再構(gòu)造新的字符串 username = new String(data, "GBK"); 小結(jié): 所有的頁面(除了最后的 GET 的亂碼問題)都用統(tǒng)一的編碼(GBK或者UTF-8), 就不會出現(xiàn)亂碼問題. 4. 用過濾器來一次編碼徹底解決表單參數(shù)的亂碼問題 Tomcat 5/6 GBK 編碼下完美解決中文表單問題的過濾器  文章來源: http://www.aygfsteel.com/beansoft/archive/2007/10/10/151848.html
分頁的設計和編碼, 代碼下載請訪問: 用 MyEclipse 開發(fā)的 Hibernate + JSP 分頁代碼(跳頁錯誤已修正) 1. 當前頁碼的表單參數(shù) listuser.do?page=2 同時轉(zhuǎn)換成一個 int 類型的頁碼變量 int currentPage = Integer.parseInt( request.getParameter("page");// 當前頁 2. 下一頁 listuser.do?page=${currentPage+1} 上一頁 listuser.do?page=${currentPage-1} 3. 一頁顯示多少數(shù)據(jù) int pageSize = 5;//每頁顯示的數(shù)據(jù)數(shù) 4. 總頁數(shù) totalPage 1) 先從數(shù)據(jù)庫取得總記錄數(shù) dao.UserDAO#getUserTotalCount() int totalCount = executeQuery("select count(*) from Users"); 2) 根據(jù)一頁的數(shù)據(jù)類計算出總頁數(shù) dao.UserManager#getTotalPage(int pageSize) // 得到頁面總數(shù) int totalPageCount = ((totalCount + pageSize) - 1) / pageSize; if(totalPageCount == 0) { totalPageCount = 1; } 5. 從數(shù)據(jù)庫里把第currentPage頁的數(shù)據(jù)讀取出來(Hibernate), DAO 層的代碼 dao.UserDAO#findPagedAll(int currentPage, int pageSize) 兩個參數(shù): currentPage 當前頁(從1開始的) pageSize 取多少數(shù)據(jù) String queryString = "from User"; Query queryObject = getSession().createQuery(queryString); queryObject.setFirstResult((currentPage - 1) * pageSize); queryObject.setMaxResults(pageSize); List result = queryObject.list(); 6. 在前臺顯示上下頁的鏈接,并根據(jù)總頁數(shù)的上下限來避免讓用戶跳到第-1頁或者比最大頁數(shù)還大的頁碼哪里 <c:if test="${currentPage > 1}"> [ 上一頁的鏈接 ] </c:if> <c:if test="${currentPage <= 1}"> [ 上一頁的文本 ] </c:if> 7. 通過 forEach 來顯示數(shù)據(jù) <c:forEach items="${users}" var="user" > ${user.id} ${user.username} <c:/forEach> 8. 通過下拉菜單來跳轉(zhuǎn)頁面 轉(zhuǎn)到 <script> // 頁面跳轉(zhuǎn)函數(shù) // 參數(shù): 包含網(wǎng)址的選擇框(SELECT元素) function jumpPage(select) { var newUrl = "/hibernate_page/index.jsp?page=" + select.value; //alert(newUrl); document.location = newUrl; } </script> <!-- 輸出 HTML SELECT 元素, 并選中當前頁面編碼 --> <select onchange='jumpPage(this);'> <option value="1" selected>1頁</option> <option value="2" >2頁</option> </select>  文章來源: http://www.aygfsteel.com/beansoft/archive/2007/10/10/151704.html
最近有同學做項目的時候發(fā)現(xiàn) Spring 整合 Hibernate 時候用的 HibernateTemplate 不支持分頁, 上網(wǎng)搜了搜找到結(jié)果并測試成功, 只需要用下面的方法就能分頁: /**
* 使用hql 語句進行操作
* @param hql HSQL 查詢語句
* @param offset 開始取數(shù)據(jù)的下標
* @param length 讀取數(shù)據(jù)記錄數(shù)
* @return List 結(jié)果集
*/
public List getListForPage(final String hql, final int offset,
final int length) {
List list = getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query = session.createQuery(hql);
query.setFirstResult(offset);
query.setMaxResults(length);
List list = query.list();
return list;
}
});
return list;
}  文章來源: http://www.aygfsteel.com/beansoft/archive/2007/10/10/151702.html
常見的 Tomcat 5 表單編碼提交后亂碼的解決方案有很多, 有改 Tomcat Connector 屬性的, 有加過濾器的. 但是 Tomcat 自帶的那個過濾器只解決了 POST 方式的亂碼卻不能處理 GET 方式的亂碼. 在這里那我就給出一個不需要修改任何 Tomcat 配置文件的完美解決中文問題的過濾器的代碼: 首先是我們的測試頁面: index.jsp <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>表單測試頁面</title>
</head>
<body>
<form action="action.jsp">
GET 方式: <input type=text name="name" value="GET 中文">
<input type=submit>
</form>
<form action="action.jsp" method="POST">
POST 方式: <input type=text name="name" value="POST 中文">
<input type=submit>
</form>
</body>
</html>
和普通的表單沒有任何區(qū)別.
然后就是表單提交頁面 action.jsp:
<%@ page language="java" pageEncoding="GBK"%>
<html>
<body>
參數(shù): <%=request.getParameter("name") %> <br>
</body>
</html>
接著是過濾器的配置文件 web.xml (用 2.5 版本也可以):
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<filter>
<filter-name>TomcatFormFilter</filter-name>
<filter-class>filters.TomcatFormFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>TomcatFormFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
最后最關鍵的就是我們的過濾器代碼了, 對 GET 方式使用請求包裝器, 而 POST 方式則用 setCharacterEncoding():
package filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
public class TomcatFormFilter implements Filter {
/**
* Request.java
* 對 HttpServletRequestWrapper 進行擴充, 不影響原來的功能并能提供所有的 HttpServletRequest
* 接口中的功能. 它可以統(tǒng)一的對 Tomcat 默認設置下的中文問題進行解決而只需要用新的 Request 對象替換頁面中的
* request 對象即可.
*/
class Request extends HttpServletRequestWrapper
{
public Request(HttpServletRequest request) {
super(request);
}
/**
* 轉(zhuǎn)換由表單讀取的數(shù)據(jù)的內(nèi)碼.
* 從 ISO 字符轉(zhuǎn)到 GBK.
*/
public String toChi(String input) {
try {
byte[] bytes = input.getBytes("ISO8859-1");
return new String(bytes, "GBK");
}
catch (Exception ex) {
}
return null;
}
/**
* Return the HttpServletRequest holded by this object.
*/
private HttpServletRequest getHttpServletRequest()
{
return (HttpServletRequest)super.getRequest();
}
/**
* 讀取參數(shù) -- 修正了中文問題.
*/
public String getParameter(String name)
{
return toChi(getHttpServletRequest().getParameter(name));
}
/**
* 讀取參數(shù)列表 - 修正了中文問題.
*/
public String[] getParameterValues(String name)
{
String values[] = getHttpServletRequest().getParameterValues(name);
if (values != null) {
for (int i = 0; i < values.length; i++) {
values[i] = toChi(values[i]);
}
}
return values;
}
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpreq = (HttpServletRequest)request;
if(httpreq.getMethod().equals("POST")) {
request.setCharacterEncoding("GBK");
} else {
request = new Request(httpreq);
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
怎么樣, 是不是很簡單也很方便呢?  文章來源: http://www.aygfsteel.com/beansoft/archive/2007/10/09/151368.html
隨著JPA得到眾多廠商和開發(fā)人員的認同, 如同 Resin 的新聞中所說的那樣: 2007-07-18 Resin 3.1.2 adds significant features Resin 3.1.2 now includes an implementation of the Java Persistence API, which is a major feature of the Enterprise Java Beans 3.0 standard. New features have also been added to the Hessian 2.0 web services protocol that allow for better security and message compression. Resin's JAX-WS support continues to improve with better support for WSDL handling and handler chains. Both Resin and the Quercus Java-PHP engine also underwent major reliability tests making them even more solid than before. "Before JPA, developers had to choose from an array of non-standard, incompatible API's to do object persistence. JPA standardizes this fundamental task and makes it easier for developers to get their applications written faster. Resin's JPA implementation is efficient and reliable, so our customers can start using this exciting new standard right away," said Emil Ong, Software Engineer at Caucho Technology. Resin 的最新版也開始支持內(nèi)置的 JPA 了. 像上面這段話上所說, JPA 最大的優(yōu)點就是把開發(fā)人員從各種各樣的包和API中解放出來, 例如你的程序不再需要導入 org.hibernate.*** 或者 com.oracle.***, 而且便于隨時切換底層引擎. 這就像 JDBC 所起的作用那樣. PS: Resin 是另一款性能和易用性上都超過 Tomcat 的 Java Web 服務器, 同時也支持 Java 實現(xiàn)的 PHP. 雖然 Tomcat 是標準的實現(xiàn), 但是 Resin 在很多地方都比 Tomcat 優(yōu)秀.  文章來源: http://www.aygfsteel.com/beansoft/archive/2007/10/09/151360.html
| Project Name | Type | Lead | Version | Release Date | Download | Downloads | Hibernate 開發(fā)指南 | 原創(chuàng) | Xiaxin(夏昕) | | | 92頁, 530K | 131,158 | 《深入淺出Hibernate》 | 原創(chuàng)書籍 | Xiaxin(夏昕),Cao Xiaogang(曹曉鋼),Jerry Tang(唐勇) | | | 隨書示例, 7.5M | 190,908 | IBatis2 開發(fā)指南 | 原創(chuàng) | Xiaxin(夏昕) | | | 48頁,319K | 75,404 | Spring 開發(fā)指南 | 原創(chuàng) | Xiaxin (夏昕) | | | 169頁, 1.02M | 171,842 | Hibernate 手冊 | 翻譯 | Cao Xiaogang(曹曉鋼) | 3.2 | | 238頁,1.42M (PDF) HTML HTML_Single | 135,028 | Webwork2 開發(fā)指南 | 原創(chuàng) | Xiaxin (夏昕) | | | 60頁, 550K | 41,739 | 持續(xù)集成實踐之CruiseControl | 原創(chuàng) | mathaw | | | 34頁, 964K | 19,690 | Shift To Dynamic(smalltalk) | 原創(chuàng) | Raimundox(徐昊) | 0.3 | | 27頁,1.98M | 15,561 | luntbuild手冊 | 翻譯 | melthaw | | | web site | 15,627 | Mapping Objects to Relational Databases | 翻譯 | mochow(huhu) | | | 34頁,571K | 25,175 | SpringFramework概述 | 翻譯 | DigitalSonic | | | 24頁,322K | 22,095 | Java網(wǎng)絡程序員看Continuation
| 原創(chuàng) | 劉暢 | | 2006/02/16 | 57頁,1.45M | 90,087 | Hibernate Annotation Reference | 翻譯 | melthaw | | | 進行中 已提交給hibernate小組,等待英文正式版本發(fā)布 | | Spring 2.0 Reference | 翻譯 | DigitalSonic | 2.0 | 2006/10/22 | HTML , PDF(509頁, 3.74M) ,CHM(2.2M) | 95,748(gro下載統(tǒng)計) | [OSGI Opendoc] | 原創(chuàng) | Bluedavy | | | 90頁,3M | 130,663 | Seam 2.0 Reference | 翻譯 | Xiaogang Cao | 2.0 | | 進行中 | 架構(gòu)風格與基于網(wǎng)絡的軟件架構(gòu)設計 (NEW!) | 翻譯 | 原著:Roy Thomas Fielding博士,翻譯:李錕、廖志剛、劉丹、楊光 | | 2007/6/28 | PDF(84頁,810K) | 48,271 | Using the Rake Build Language (NEW!) | 翻譯 | 原著:Martin Fowler,翻譯:DigitalSonic | | 2007/6/1 | PDF(19頁,333K) | 5,202 | OSWorkflow中文手冊 (NEW!) | 翻譯 | 原作:OSWorkflow團隊;翻譯:陳剛 | 2.8 | 2007/8/21 | PDF(50頁,790K) | 16,218 | | | | | | | 總計:1,230,416 | (備注:下載量統(tǒng)計到2007年10月8日1:20, 以apache log文件為準,未區(qū)分flashget等軟件分段下載情況) 滿江紅站點還為以下開源軟件軟件/組織提供Hosting服務: 歡迎您的加入:我們可以為開源軟件提供CVS/SVN/wiki/JIRA等服務.請email: caoxg at yahoo.com 聯(lián)系. 目前管理員小組成員: 夏昕(nuke), 徐昊(Raimundox),mochow, 劉暢(liu chang),曹曉鋼 | | 感謝同志們的無私奉獻, 給廣大初學者帶來了福音. http://wiki.redsaga.com/confluence/display/RSTEAM/Home  文章來源: http://www.aygfsteel.com/beansoft/archive/2007/10/09/151237.html
摘要: http://hexapixel.com/projects/
http://hexapixel.com/ribbon/
下載地址: download the jar and the source
源碼包里面的 com.hexapixel.widgets.ribbon.RibbonTester 展示了如何使用這個組件.
作者提示道: 可能有很多 b... 閱讀全文 文章來源: http://www.aygfsteel.com/beansoft/archive/2007/10/07/150887.html
第一部分: Struts 開發(fā) 6.83MB 22分36秒 http://beansoft.java-cn.org/download/ssh_1_struts.exe 第二部分: Hibernate + Spring 11.5MB 38分59秒 http://beansoft.java-cn.org/download/ssh_2_hibernate_spring.exe 第三部分: 自己實現(xiàn) SpringProxyAction 5.05MB 14分25秒 http://beansoft.java-cn.org/download/ssh_3_struts_proxy_asm.exe 第四部分: ASM 錯誤解決及用 Spring 的代理實現(xiàn)整合 9.95MB 23分49秒 http://beansoft.java-cn.org/download/ssh_4_spring_struts.exe 大綱 PDF 下載: http://beansoft.java-cn.org/download/spring_struts_hibernate.pdf 427KB 代碼下載(不帶類庫): http://beansoft.java-cn.org/download/myssh.rar 45KB 視頻大綱: Java EE 講座 MyEclipse 5.5 開發(fā) Spring 整合 Struts, Hibernate 的應用 劉長炯 2007.10 本章要點 創(chuàng)建數(shù)據(jù)庫
快速開發(fā) Struts 應用
添加 Hibernate 功能
添加 Spring 功能
Spring 整合 Hibernate
模擬 Action 代理類實現(xiàn) Struts + Spring
Spring 整合 Struts
Asm 出錯和 log4j.properties 文件
測試運行
創(chuàng)建數(shù)據(jù)庫 ? 創(chuàng)建數(shù)據(jù)庫 ? 用 MyEclipse Derby 或者其它數(shù)據(jù)庫 ? 用 MyEclipse Database Explorer 管理數(shù)據(jù)庫 ? 執(zhí)行 SQL: ? CREATE TABLE bbsuser ( ? id int(11) NOT NULL, ? username varchar(200) NOT NULL, ? password varchar(20) NOT NULL, ? age int, ? PRIMARY KEY (id) ? ) ? ENGINE=MyISAM DEFAULT CHARSET=GBK; 快速開發(fā) Struts 應用 添加 Hibernate 功能 添加 Spring 功能 Spring 整合 Hibernate Spring 整合 Hibernate(續(xù)) 模擬 Action 代理類實現(xiàn) Struts + Spring Spring 整合 Struts ? 添加 Spring Plug in ? <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> ? <set-property property="contextConfigLocation" value="/WEB-INF/classes/applicationContext.xml" /> ? </plug-in> ? 替換 Action 的 Type ? <action path="/login“ … ? type="org.springframework.web.struts.DelegatingActionProxy" /> ? 在 Spring 配置文件中配置 Bean ? 要點: 通過 path 和 bean 的 name 進行匹配, 這兩個值必須一樣 ? <bean name="/login" class="com.test.struts.action.LoginAction"></bean> ? 注入 DAO 的代理 bean ? 詳細步驟參考文檔 Spring 整合 Struts 的兩種方式 ? struts1加載spring的兩種方式: 第一種:通過web.xml配置加載spring上下文環(huán)境,其配置方式如下: web.xml <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> 通過listener加載 <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> 或者利用severlet類加載 <servlet> <servlet-name>context</servlet-name> <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> 第二種方式: 使用Struts插件 在struts-config.xml中 <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property property="contextConfigLocation" value="/WEB-INF/applicationContext.xml"/> </plug-in> ? 這兩種配置的明顯區(qū)別就是,第一種方式可以配置多個spring配置文件。 Asm 出錯和 log4j.properties 文件 ? Log4j.properties ? # Configure logging for testing: optionally with log file ? log4j.rootLogger=WARN, stdout ? # log4j.rootLogger=WARN, stdout, logfile ? log4j.appender.stdout=org.apache.log4j.ConsoleAppender ? log4j.appender.stdout.layout=org.apache.log4j.PatternLayout ? log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n ? log4j.appender.logfile=org.apache.log4j.FileAppender ? log4j.appender.logfile.File=target/spring.log ? log4j.appender.logfile.layout=org.apache.log4j.PatternLayout ? log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n ? 刪除 asm-2.2.3.jar 測試運行 ? 測試運行 ? 用 MyEclipse 發(fā)布到 Tomcat ? 運行 ? 打開瀏覽器測試 本章小結(jié) ? 整合要點 ? ASM出錯的解決方案 ? Q and A? 截圖: PPT  視頻: 
 文章來源: http://www.aygfsteel.com/beansoft/archive/2007/10/07/150877.html
下載后導入項目到 MyEclipse , 然后修改數(shù)據(jù)庫連接參數(shù)即可測試. 我這用的是 MySQL 數(shù)據(jù)庫. 用 JSP 是因為 Hibernate 可以配合各種框架, 因此在代碼里我已經(jīng)盡量的把頁面和后臺的直接變量耦合分隔開了. hibernate_page.zip 433KB 部分代碼顯示: 相關 SQL: CREATE TABLE `user` (
`id` int(11) NOT NULL,
`username` varchar(200) NOT NULL,
`password` varchar(20) NOT NULL,
`age` int,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=GBK;
-- JDBC Driver Name: com.mysql.jdbc.Driver
-- JDBC Driver URL: jdbc:mysql://hostname/dbname?useUnicode=true&characterEncoding=GBK
insert into user values(1, '中文', 'beansoft', 1);
insert into user values(2, 'BeanSoft', 'beansoft', 2);
insert into user values(3, '張三', 'beansoft', 3);
insert into user values(4, '李四', 'beansoft', 4);
insert into user values(5, '王五', 'beansoft', 5);
insert into user values(6, '馬六', 'beansoft', 6);
insert into user values(7, '黑七', 'beansoft', 7);
insert into user values(8, '臘八', 'beansoft', 8);
insert into user values(9, '陸九', 'beansoft', 9);
insert into user values(10, '茅十八', 'beansoft', 10);
前臺 JSP 代碼:
<%@ page language="java" import="manager.*,java.util.*" pageEncoding="GBK"%>
<%@ page contentType="text/html;charset=GBK"%>
<%-- 我們使用 JSTL 來訪問數(shù)據(jù) --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
// 以下代碼為業(yè)務邏輯代碼, 應該放在 Servlet 或者 Struts 的 Action 或者其它框架的業(yè)務代碼部分, 這些代碼和當前頁面是獨立的
// {{{
// 分析當前頁碼
String pageString=request.getParameter("page");
if(pageString == null || pageString.length() == 0) {
pageString = "1";
}
int currentPage= 0 ;
try {
currentPage = Integer.parseInt(pageString);// 當前頁碼
} catch(Exception e) {}
if(currentPage == 0) {
currentPage = 1;
}
int pageSize = 3;//每頁顯示的數(shù)據(jù)數(shù)
// 讀取數(shù)據(jù)
UserManager manager = new UserManager();
List users = manager.findPagedAll(currentPage, pageSize);
request.setAttribute("users",users);// 保存用戶列表
request.setAttribute("totalPage", manager.getTotalPage(pageSize));// 保存總頁數(shù)
request.setAttribute("totalCount", manager.getUserTotalCount());// 保存記錄總數(shù)
request.setAttribute("currentPage", currentPage);// 保存當前頁碼
// }}}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>用戶列表頁面</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>用戶列表<br>
<%-- 輸出用戶列表 --%>
總用戶:${totalCount}個用戶<br>
<table width="80%" border="0">
<tr>
<td><b>用戶ID</b></td>
<td><b>用戶名</b></td>
<td><b>操作</b></td>
</tr>
<c:forEach items="${users}" var="user" >
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td><a href="edit.jsp?id=${user.id}">修改</a></td>
</tr>
</c:forEach>
</table>
第${currentPage}頁/共${totalPage}頁
<%-- 輸出頁面跳轉(zhuǎn)代碼, 分鏈接和靜態(tài)文字兩種 --%>
<c:if test="${currentPage > 1}">
[ <a href="${pageContext.request.contextPath}/index.jsp?page=${currentPage-1}">上一頁</a> ]
</c:if>
<c:if test="${currentPage <= 1}">
[ 上一頁 ]
</c:if>
<c:if test="${currentPage < totalPage}">
[ <a href="${pageContext.request.contextPath}/index.jsp?page=${currentPage+1}">下一頁</a> ]
</c:if>
<c:if test="${currentPage >= totalPage}">
[ 下一頁 ]
</c:if>
<%-- 輸出 JavaScript 跳轉(zhuǎn)代碼 --%>
轉(zhuǎn)到
<script>
// 頁面跳轉(zhuǎn)函數(shù)
// 參數(shù): 包含頁碼的選擇框(SELECT元素)
function jumpPage(select) {
var newUrl = "${pageContext.request.contextPath}/index.jsp?page=" + select.value;
//alert(newUrl);
document.location = newUrl;
}
</script>
<!-- 輸出 HTML SELECT 元素, 并選中當前頁面編碼 -->
<select onchange='jumpPage(this);'>
<c:forEach var="i" begin="1" end="${totalPage}">
<option value="${i}"
<c:if test="${currentPage == i}">
selected
</c:if>
>第${i}頁</option>
</c:forEach>
</select>
</body>
</html>
后臺 DAO:
package dao;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import util.HibernateSessionFactory;
/**
* Data access object (DAO) for domain model class User.
*
* @see dao.User
* @author MyEclipse Persistence Tools
*/
public class UserDAO {
private static final Log log = LogFactory.getLog(UserDAO.class);
// property constants
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String AGE = "age";
public Session getSession() {
return HibernateSessionFactory.getSession();
}
/**
* 得到用戶總數(shù)
*
* @return 用戶記錄總數(shù)
*/
public int getUserTotalCount() {
Query q = getSession().createQuery("select count(*) from User");
List cc = q.list();
Integer a = (Integer) cc.get(0);
return a.intValue();
}
/**
* 分頁顯示用戶數(shù)據(jù).
*
* @param currentPage
* 當前頁碼, 從 1 開始
* @param pageSize
* 每頁顯示數(shù)據(jù)量
* @return 用戶數(shù)據(jù)
*/
public List findPagedAll(int currentPage, int pageSize) {
log.debug("分頁查找");
try {
if (currentPage == 0) {
currentPage = 1;
}
String queryString = "from User";
Query queryObject = getSession().createQuery(queryString);
queryObject.setFirstResult((currentPage - 1) * pageSize);
queryObject.setMaxResults(pageSize);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public void save(User transientInstance) {
log.debug("saving User instance");
try {
getSession().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(User persistentInstance) {
log.debug("deleting User instance");
try {
getSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public User findById(java.lang.Integer id) {
log.debug("getting User instance with id: " + id);
try {
User instance = (User) getSession().get("dao.User", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(User instance) {
log.debug("finding User instance by example");
try {
List results = getSession().createCriteria("dao.User").add(
Example.create(instance)).list();
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public List findByProperty(String propertyName, Object value) {
log.debug("finding User instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from User as model where model."
+ propertyName + "= ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List findByUsername(Object username) {
return findByProperty(USERNAME, username);
}
public List findByPassword(Object password) {
return findByProperty(PASSWORD, password);
}
public List findByAge(Object age) {
return findByProperty(AGE, age);
}
public List findAll() {
log.debug("finding all User instances");
try {
String queryString = "from User";
Query queryObject = getSession().createQuery(queryString);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public User merge(User detachedInstance) {
log.debug("merging User instance");
try {
User result = (User) getSession().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(User instance) {
log.debug("attaching dirty User instance");
try {
getSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(User instance) {
log.debug("attaching clean User instance");
try {
getSession().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
}
后臺 Manager:
/**
*
*/
package manager;
import java.util.List;
/**
* 用戶管理類
*
* @author Administrator
*
*/
public class UserManager {
/** 用戶管理 DAO */
private dao.UserDAO userDAO = new dao.UserDAO();
/**
* 得到用戶總數(shù)
* @return 用戶記錄總數(shù)
*/
public int getUserTotalCount(){
return userDAO.getUserTotalCount();
}
/**
* 獲取總頁面數(shù).
*
* @param pageSize
* 一頁顯示數(shù)據(jù)量
* @return 頁面總數(shù)
*/
public int getTotalPage(int pageSize) {
int totalCount = userDAO.getUserTotalCount();
// 得到頁面總數(shù)
int totalPageCount = ((totalCount + pageSize) - 1) / pageSize;
return totalPageCount;
}
/**
* 分頁顯示用戶數(shù)據(jù).
* @param currentPage 當前頁碼, 從 1 開始
* @param pageSize 每頁顯示數(shù)據(jù)量
* @return 用戶數(shù)據(jù)
*/
public List findPagedAll(int currentPage, int pageSize) {
return userDAO.findPagedAll(currentPage, pageSize);
}
}
 文章來源: http://www.aygfsteel.com/beansoft/archive/2007/10/05/150583.html
視頻內(nèi)容: 1. 從 http://tomcat.apache.org/ 下載并安裝 Tomcat 6 服務器 2. 在 MyEclipse 中配置服務器 3. 在 MyEclipse 中啟動/停止 Tomcat 6 4. 新建 Web 項目 5. 新建靜態(tài)頁面并添加 GET 和 POST 表單 6. 創(chuàng)建 FormServlet 7. 編寫代碼將參數(shù)讀取出來并輸出 8. 發(fā)布并測試運行, 查看發(fā)布內(nèi)容 9. 頁面輸出漢字內(nèi)容亂碼問題解決 + 如何重新發(fā)布 10. POST 方式表單參數(shù)亂碼解決 11. GET 方式表單參數(shù)亂碼解決 下載: http://beansoft.java-cn.org/download/MyEclipse6_6.exe 9.37 MB 27分06秒 相關代碼: web.xml <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>FormServlet</servlet-name>
<servlet-class>servlet.FormServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FormServlet</servlet-name>
<url-pattern>/FormServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
form.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>form.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=GBK">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<form action="./FormServlet" method="GET">
GET: <input name="username">
<input type="submit">
</form>
<form action="./FormServlet" method="POST">
POST: <input name="username">
<input type="submit">
</form>
</body>
</html>
FormServlet.java
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FormServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public FormServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("GBK");
response.setContentType("text/html;charset=GBK");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" 您輸入的用戶名是:");
// GET 方式, 編碼轉(zhuǎn)換
String username = request.getParameter("username");
username = new String(username.getBytes("ISO8859-1"), "GBK");
out.print(username);
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// POST 表單參數(shù)的亂碼解決
request.setCharacterEncoding("GBK");
response.setContentType("text/html;charset=GBK");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" 您輸入的用戶名是:");
out.print(request.getParameter("username"));
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
 文章來源: http://www.aygfsteel.com/beansoft/archive/2007/10/05/150563.html
|