﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-study-文章分类-JSP</title><link>http://www.blogjava.net/xixidabao/category/10244.html</link><description>GROW WITH JAVA</description><language>zh-cn</language><lastBuildDate>Fri, 14 Dec 2007 10:03:51 GMT</lastBuildDate><pubDate>Fri, 14 Dec 2007 10:03:51 GMT</pubDate><ttl>60</ttl><item><title>Tomcat+MySql+Struts中文问题绝妙的解决方案</title><link>http://www.blogjava.net/xixidabao/articles/167382.html</link><dc:creator>JAVA之路</dc:creator><author>JAVA之路</author><pubDate>Thu, 13 Dec 2007 01:16:00 GMT</pubDate><guid>http://www.blogjava.net/xixidabao/articles/167382.html</guid><description><![CDATA[<p>&nbsp;&nbsp; &nbsp;开发Web应用程序时，无论是用什么样的框架技术来开发，一碰从数据库存取涉及到中文的数据，就要面对中文乱码或者是各种编码方式不匹配的异常，今天晚上终于搞定了Tomcat+MySql+Struts的中文问题，用到了很简单的方法，很快就能搞定。</p>
<p>&nbsp;&nbsp; &nbsp;在做以下工作之前，<font size="1">所有的HTML/JSP的charset都设为charset=gb2312。</font></p>
<p>&nbsp; &nbsp; 第一个要解决的是表单提交乱码问题。在使用Struts提供的ActionForm过程中，无论表单采用的是Struts标签还是Html标签，都可以用ActionForm的Get/Set来获取和设置表单的元素值（它们的作用效果与request.getParameter()方法一样），但提取出来的数据不经过处理的话就是乱码，主要的原因是1.Tomcat的J2EE实现对表单提交即Post方法提交时，处理参数采用默认的ISO8859_1来处理2.Tomcat对Get方法提交的请求在query-string处理时采用了和Post方法不一样的处理方式。所以如果要正确地显示和获取中文数据采用的解决方案：（1）对于Post方法提交的表单通过编写一个过滤器（filer）的方法解决，过滤器在用户提交的数据被处理之前被调用，可以通过这个Java代码改变参数的编码方式（目标编码方式可以通过Web.xml文件里面的参数指定）。过滤器的代码如下：</p>
<p>import java.io.IOException;<br />
import javax.servlet.Filter;<br />
import javax.servlet.FilterChain;<br />
import javax.servlet.FilterConfig;<br />
import javax.servlet.ServletException;<br />
import javax.servlet.ServletRequest;<br />
import javax.servlet.ServletResponse;<br />
import javax.servlet.UnavailableException;</p>
<p><br />
/**<br />
&nbsp;* &lt;p&gt;Example filter that sets the character encoding to be used in parsing the<br />
&nbsp;* incoming request, either unconditionally or only if the client did not<br />
&nbsp;* specify a character encoding.&nbsp; Configuration of this filter is based on<br />
&nbsp;* the following initialization parameters:&lt;/p&gt;<br />
&nbsp;* &lt;ul&gt;<br />
&nbsp;* &lt;li&gt;&lt;strong&gt;encoding&lt;/strong&gt; - The character encoding to be configured<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp; for this request, either conditionally or unconditionally based on<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp; the &lt;code&gt;ignore&lt;/code&gt; initialization parameter.&nbsp; This parameter<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp; is required, so there is no default.&lt;/li&gt;<br />
&nbsp;* &lt;li&gt;&lt;strong&gt;ignore&lt;/strong&gt; - If set to "true", any character encoding<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp; specified by the client is ignored, and the value returned by the<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp; &lt;code&gt;selectEncoding()&lt;/code&gt; method is set.&nbsp; If set to "false,<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp; &lt;code&gt;selectEncoding()&lt;/code&gt; is called &lt;strong&gt;only&lt;/strong&gt; if the<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp; client has not already specified an encoding.&nbsp; By default, this<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp; parameter is set to "true".&lt;/li&gt;<br />
&nbsp;* &lt;/ul&gt;<br />
&nbsp;*<br />
&nbsp;* &lt;p&gt;Although this filter can be used unchanged, it is also easy to<br />
&nbsp;* subclass it and make the &lt;code&gt;selectEncoding()&lt;/code&gt; method more<br />
&nbsp;* intelligent about what encoding to choose, based on characteristics of<br />
&nbsp;* the incoming request (such as the values of the &lt;code&gt;Accept-Language&lt;/code&gt;<br />
&nbsp;* and &lt;code&gt;User-Agent&lt;/code&gt; headers, or a value stashed in the current<br />
&nbsp;* user's session.&lt;/p&gt;<br />
&nbsp;*<br />
&nbsp;* @author Craig McClanahan<br />
&nbsp;* @version $Revision: 1.2 $ $Date: 2004/03/18 16:40:33 $<br />
&nbsp;*/</p>
<p>public class SetCharacterEncodingFilter implements Filter {</p>
<p><br />
&nbsp;&nbsp;&nbsp; // ----------------------------------------------------- Instance Variables</p>
<p><br />
&nbsp;&nbsp;&nbsp; /**<br />
&nbsp;&nbsp;&nbsp;&nbsp; * The default character encoding to set for requests that pass through<br />
&nbsp;&nbsp;&nbsp;&nbsp; * this filter.<br />
&nbsp;&nbsp;&nbsp;&nbsp; */<br />
&nbsp;&nbsp;&nbsp; protected String encoding = null;</p>
<p><br />
&nbsp;&nbsp;&nbsp; /**<br />
&nbsp;&nbsp;&nbsp;&nbsp; * The filter configuration object we are associated with.&nbsp; If this value<br />
&nbsp;&nbsp;&nbsp;&nbsp; * is null, this filter instance is not currently configured.<br />
&nbsp;&nbsp;&nbsp;&nbsp; */<br />
&nbsp;&nbsp;&nbsp; protected FilterConfig filterConfig = null;</p>
<p><br />
&nbsp;&nbsp;&nbsp; /**<br />
&nbsp;&nbsp;&nbsp;&nbsp; * Should a character encoding specified by the client be ignored?<br />
&nbsp;&nbsp;&nbsp;&nbsp; */<br />
&nbsp;&nbsp;&nbsp; protected boolean ignore = true;</p>
<p><br />
&nbsp;&nbsp;&nbsp; // --------------------------------------------------------- Public Methods</p>
<p><br />
&nbsp;&nbsp;&nbsp; /**<br />
&nbsp;&nbsp;&nbsp;&nbsp; * Take this filter out of service.<br />
&nbsp;&nbsp;&nbsp;&nbsp; */<br />
&nbsp;&nbsp;&nbsp; public void destroy() {</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.encoding = null;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.filterConfig = null;</p>
<p>&nbsp;&nbsp;&nbsp; }</p>
<p><br />
&nbsp;&nbsp;&nbsp; /**<br />
&nbsp;&nbsp;&nbsp;&nbsp; * Select and set (if specified) the character encoding to be used to<br />
&nbsp;&nbsp;&nbsp;&nbsp; * interpret request parameters for this request.<br />
&nbsp;&nbsp;&nbsp;&nbsp; *<br />
&nbsp;&nbsp;&nbsp;&nbsp; * @param request The servlet request we are processing<br />
&nbsp;&nbsp;&nbsp;&nbsp; * @param result The servlet response we are creating<br />
&nbsp;&nbsp;&nbsp;&nbsp; * @param chain The filter chain we are processing<br />
&nbsp;&nbsp;&nbsp;&nbsp; *<br />
&nbsp;&nbsp;&nbsp;&nbsp; * @exception IOException if an input/output error occurs<br />
&nbsp;&nbsp;&nbsp;&nbsp; * @exception ServletException if a servlet error occurs<br />
&nbsp;&nbsp;&nbsp;&nbsp; */<br />
&nbsp;&nbsp;&nbsp; public void doFilter(ServletRequest request, ServletResponse response,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; FilterChain chain)<br />
&nbsp;throws IOException, ServletException {</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Conditionally select and set the character encoding to be used<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (ignore || (request.getCharacterEncoding() == null)) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String encoding = selectEncoding(request);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (encoding != null)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; request.setCharacterEncoding(encoding);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p>&nbsp;// Pass control on to the next filter<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; chain.doFilter(request, response);</p>
<p>&nbsp;&nbsp;&nbsp; }</p>
<p><br />
&nbsp;&nbsp;&nbsp; /**<br />
&nbsp;&nbsp;&nbsp;&nbsp; * Place this filter into service.<br />
&nbsp;&nbsp;&nbsp;&nbsp; *<br />
&nbsp;&nbsp;&nbsp;&nbsp; * @param filterConfig The filter configuration object<br />
&nbsp;&nbsp;&nbsp;&nbsp; */<br />
&nbsp;&nbsp;&nbsp; public void init(FilterConfig filterConfig) throws ServletException {</p>
<p>&nbsp;this.filterConfig = filterConfig;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.encoding = filterConfig.getInitParameter("encoding");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String value = filterConfig.getInitParameter("ignore");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (value == null)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.ignore = true;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else if (value.equalsIgnoreCase("true"))<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.ignore = true;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else if (value.equalsIgnoreCase("yes"))<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.ignore = true;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.ignore = false;</p>
<p>&nbsp;&nbsp;&nbsp; }</p>
<p><br />
&nbsp;&nbsp;&nbsp; // ------------------------------------------------------ Protected Methods</p>
<p><br />
&nbsp;&nbsp;&nbsp; /**<br />
&nbsp;&nbsp;&nbsp;&nbsp; * Select an appropriate character encoding to be used, based on the<br />
&nbsp;&nbsp;&nbsp;&nbsp; * characteristics of the current request and/or filter initialization<br />
&nbsp;&nbsp;&nbsp;&nbsp; * parameters.&nbsp; If no character encoding should be set, return<br />
&nbsp;&nbsp;&nbsp;&nbsp; * &lt;code&gt;null&lt;/code&gt;.<br />
&nbsp;&nbsp;&nbsp;&nbsp; * &lt;p&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp; * The default implementation unconditionally returns the value configured<br />
&nbsp;&nbsp;&nbsp;&nbsp; * by the &lt;strong&gt;encoding&lt;/strong&gt; initialization parameter for this<br />
&nbsp;&nbsp;&nbsp;&nbsp; * filter.<br />
&nbsp;&nbsp;&nbsp;&nbsp; *<br />
&nbsp;&nbsp;&nbsp;&nbsp; * @param request The servlet request we are processing<br />
&nbsp;&nbsp;&nbsp;&nbsp; */<br />
&nbsp;&nbsp;&nbsp; protected String selectEncoding(ServletRequest request) {</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return (this.encoding);</p>
<p>&nbsp;&nbsp;&nbsp; }</p>
<p>}</p>
<p>编绎后把class文件放在classes目录下，并在Web应用的web.xml文件中添加如下代码：</p>
<p>&lt;filter&gt;<br />
&nbsp;&nbsp;&lt;filter-name&gt;Set Character Encoding&lt;/filter-name&gt;<br />
&nbsp;&nbsp;&lt;filter-class&gt;com.neusoft.equipment.controller.SetCharacterEncodingFilter&lt;/filter-class&gt;<br />
&nbsp;&nbsp;&lt;init-param&gt;<br />
&nbsp;&nbsp;&nbsp;&lt;param-name&gt;encoding&lt;/param-name&gt;<br />
&nbsp;&nbsp;&nbsp;&lt;param-value&gt;gbk&lt;/param-value&gt;<br />
&nbsp;&nbsp;&lt;/init-param&gt;<br />
&nbsp;&lt;/filter&gt;<br />
&nbsp;&lt;filter-mapping&gt;<br />
&nbsp;&nbsp;&lt;filter-name&gt;Set Character Encoding&lt;/filter-name&gt;<br />
&nbsp;&nbsp;&lt;url-pattern&gt;/*&lt;/url-pattern&gt;<br />
&nbsp;&lt;/filter-mapping&gt;只要是gb2312,gbk,utf8等支持多字节编码的字符集都可以储存汉字，当然，gb2312中的汉字数量远少于gbk，而gb2312,gbk等都可在utf8下编码，这里指定目标编码方式是gbk，重新启动Tomcat后就可以了。<br />
（2）对Get方法提交的表单，由于参数是紧跟在用户的URL请求后面，Tomcat对其的处理方法与Post方法不一样。所以上面设置的过滤器对Get方法没有作用，它需要在其他地方设置。找到Tomca的server.xml配置文件，找到对80（或者是8080等别的，这个是自己修改后的）的Connector组件的设置部分，给这个Connector组件添加一个属性：URIEncoding＝"GBK"。修改后的Connector组件是这样的：</p>
<p>&nbsp;&lt;!-- Define a non-SSL HTTP/1.1 Connector on port 80--&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;Connector port="80" maxHttpHeaderSize="8192"<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; maxThreads="150" minSpareThreads="25" maxSpareThreads="75"<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; enableLookups="false" redirectPort="8443" acceptCount="100"<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; connectionTimeout="20000" disableUploadTimeout="true"&nbsp; URIEncoding＝"GBK"/&gt;这样修改后，重启Tomcat就可以正确处理GET方法提交的表单数据了。</p>
<p>&nbsp;&nbsp; &nbsp;第二个要解决的是数据库存取数据出现的乱码等情况。对于不同的数据库往往支持不同的编码，造成了应用时比较混乱，不同的数据库的解决方法往往是不同的，针对MySql，网上也有各种各样的解决方案，但个人觉得那些太繁了，现在有一个极其简单的解决办法：修改MySql的配置文件，打开MySql安装后的根目录，找到my.init文件，把[mysqld]区的如下语句：default-character-set=latin1修改为：default-character-set=gbk，然后在[client]区增加：default-character-set=gbk，修改后记得做一件事情，到Widows控制面板的管理工具下的服务程序，把Mysql服务停止了重新启动，这样就根本解决了MySql的数据库乱码问题，很简单～～～～</p>
<img src ="http://www.blogjava.net/xixidabao/aggbug/167382.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/xixidabao/" target="_blank">JAVA之路</a> 2007-12-13 09:16 <a href="http://www.blogjava.net/xixidabao/articles/167382.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>解决jsp,tomcat,MYSQL下中文乱码问题</title><link>http://www.blogjava.net/xixidabao/articles/167375.html</link><dc:creator>JAVA之路</dc:creator><author>JAVA之路</author><pubDate>Thu, 13 Dec 2007 01:02:00 GMT</pubDate><guid>http://www.blogjava.net/xixidabao/articles/167375.html</guid><description><![CDATA[<h1>解决jsp,tomcat,MYSQL下中文乱码问题</h1>
<div id="cczoom"><a href="http://www.xclass.cn/catalog.asp?tags=tomcat%E6%9C%8D%E5%8A%A1%E5%99%A8"><img alt="查看tomcat服务器标签专题" src="http://www.xclass.cn/logo/tomcat.gif" /></a>
<p style="font-size: 9pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 这些天开发一个项目，服务器是tomcat,操作系统是xp,采用的是MVC架构，模式是采用Facade模式，总是出现乱码，通过简单的设置页面字符集，总算可以正确显示中文，可是没想到表单里提交的数据里的中文还是有乱码，我狂晕，没想到JSP里的乱码问题比ASP里严重多了，自己也解决了好多天，同事也帮忙解决，也参考了网上众多网友的文章和意见，总算是搞定。但是好记性不如烂笔杆，所以特意记下，以防止自己遗忘，同时也给那些遇到同样问题的人提供一个好的参考途径：</p>
<p style="font-size: 9pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 以下内容参考了网上的方法</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">(一)&nbsp;&nbsp;&nbsp;&nbsp;JSP设计页面上是中文，但运行时看到的是乱码：</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">解决的办法就是在JSP页面的编码的地方&lt;%@&nbsp;page&nbsp;language="java"&nbsp;contentType="text/html;charset=GBK"&nbsp;%&gt;，因为Jsp转成Java文件时的编码问题，默认的话有的服务器是ISO-8859-1，如果一个JSP中直接输入了中文，Jsp把它当作ISO8859-1来处理是肯定有问题的，这一点，我们可以通过查看Jasper所生成的Java中间文件来确认</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">(二)&nbsp;&nbsp;&nbsp;&nbsp;当用Request对象获取客户提交的汉字代码的时候，会出现乱码，比如表单里：</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">解决的办法是：要配置一个filter,也就是一个Servelet的过滤器，代码如下：</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">import&nbsp;java.io.IOException;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">import&nbsp;javax.servlet.Filter;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">import&nbsp;javax.servlet.FilterChain;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">import&nbsp;javax.servlet.FilterConfig;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">import&nbsp;javax.servlet.ServletException;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">import&nbsp;javax.servlet.ServletRequest;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">import&nbsp;javax.servlet.ServletResponse;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">import&nbsp;javax.servlet.UnavailableException;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">public&nbsp;class&nbsp;SetCharacterEncodingFilter&nbsp;implements&nbsp;Filter&nbsp;{</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;void&nbsp;destroy()&nbsp;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black"><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">{</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;void&nbsp;doFilter(ServletRequest&nbsp;request,&nbsp;ServletResponse&nbsp;response,</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black"><span style="font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">FilterChain&nbsp;chain)throws&nbsp;IOException,&nbsp;ServletException&nbsp;</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black"><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">{</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;request.setCharacterEncoding("GBK");</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;传递控制到下一个过滤器</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;chain.doFilter(request,&nbsp;response);</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;void&nbsp;init(FilterConfig&nbsp;filterConfig)&nbsp;throws&nbsp;ServletException&nbsp;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black"><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">{</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">}</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">配置web.xml</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&lt;filter&gt;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&lt;filter-name&gt;Set&nbsp;Character&nbsp;Encoding&lt;/filter-name&gt;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&lt;filter-class&gt;com.SetCharacterEncodingFilter&lt;/filter-class&gt;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&lt;/filter&gt;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&lt;filter-mapping&gt;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&lt;filter-name&gt;Set&nbsp;Character&nbsp;Encoding&lt;/filter-name&gt;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&lt;url-pattern&gt;/*&lt;/url-pattern&gt;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&lt;/filter-mapping&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">如果你的还是出现这种情况的话你就往下看看是不是你出现了第四中情况，你的Form提交的数据是不是用get提交的，一般来说用post提交的话是没有问题的，如果是的话，你就看看第四中解决的办法。</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">还有就是对含有汉字字符的信息进行处理，处理的代码是：</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">package&nbsp;dbJavaBean;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">public&nbsp;class&nbsp;CodingConvert</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">{&nbsp;&nbsp;&nbsp;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">public&nbsp;CodingConvert()</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">{</p>
<p style="margin: 0in 0in 0in 1in; color: black"><span style="font-size: 9.75pt; font-family: Arial">&nbsp;&nbsp;</span><span style="font-size: 9.75pt; font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-size: 9.75pt; font-family: Arial">//</span><span style="font-size: 9pt; font-family: Verdana">process</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">}</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">public&nbsp;String&nbsp;toGb(String&nbsp;uniStr)</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">{</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String&nbsp;gbStr&nbsp;=&nbsp;"";</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(uniStr&nbsp;==&nbsp;null)</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black"><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">{</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black"><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">&nbsp;&nbsp;&nbsp;uniStr&nbsp;=&nbsp;"";</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black"><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">{</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1.5in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;byte[]&nbsp;tempByte&nbsp;=&nbsp;uniStr.getBytes("ISO8859_1");</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1.5in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;gbStr&nbsp;=&nbsp;new&nbsp;String(tempByte,"GB2312");</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black"><span style="font-family: Arial">&nbsp;&nbsp;</span><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">catch(Exception&nbsp;ex)</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black"><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">{</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // exception process</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black"><span style="font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Arial">}</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;gbStr;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">&nbsp;}</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">&nbsp;public&nbsp;String&nbsp;toUni(String&nbsp;gbStr)</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black"><span style="font-family: Verdana">&nbsp;</span><span style="font-family: Arial">{</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String&nbsp;uniStr&nbsp;=&nbsp;"";</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(gbStr&nbsp;==&nbsp;null)</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black"><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">{</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black"><span style="font-family: Arial">&nbsp;&nbsp;&nbsp;</span><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">gbStr&nbsp;=&nbsp;"";</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black"><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">{</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1.5in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;byte[]&nbsp;tempByte&nbsp;=&nbsp;gbStr.getBytes("GB2312");</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1.5in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;uniStr&nbsp;=&nbsp;new&nbsp;String(tempByte,"ISO8859_1");</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black"><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">catch(Exception&nbsp;ex)</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black"><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">{</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black"><span style="font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Arial">}</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black"><span style="font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="font-family: Verdana">&nbsp;</span><span style="font-family: Arial">return&nbsp;uniStr;</span></p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 1in; color: black; font-family: Arial">}</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">}</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">你也可以在直接的转换，首先你将获取的字符串用ISO-8859-1进行编码，然后将这个编码存放到一个字节数组中，然后将这个数组转化成字符串对象就可以了，例如：</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">String&nbsp;str=request.getParameter(&#8220;girl&#8221;);</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">Byte&nbsp;B[]=str.getBytes(&#8220;ISO-8859-1&#8221;);</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">Str=new&nbsp;String(B);</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">通过上述转换的话，提交的任何信息都能正确的显示。</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">(三)&nbsp;&nbsp;&nbsp;&nbsp;在Formget请求在服务端用request.&nbsp;getParameter(&#8220;name&#8221;)时返回的是乱码；按tomcat的做法设置Filter也没有用或者用request.setCharacterEncoding("GBK");也不管用问题是出在处理参数传递的方法上：如果在servlet中用doGet(HttpServletRequest&nbsp;request,&nbsp;HttpServletResponse&nbsp;response)方法进行处理的话前面即使是写了：</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">request.setCharacterEncoding("GBK");</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">response.setContentType("text/html;charset=GBK");</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">也是不起作用的，返回的中文还是乱码！！！如果把这个函数改成doPost(HttpServletRequest&nbsp;request,&nbsp;HttpServletResponse&nbsp;response)一切就OK了。</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">同样，在用两个JSP页面处理表单输入之所以能显示中文是因为用的是post方法传递的，改成get方法依旧不行。</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">由此可见在servlet中用doGet()方法或是在JSP中用get方法进行处理要注意。这毕竟涉及到要通过浏览器传递参数信息，很有可能引起常用字符集的冲突或是不匹配。</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">解决的办法是：</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">1)&nbsp;打开tomcat的server.xml文件，找到区块，加入如下一行：&nbsp;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">URIEncoding=&#8221;GBK&#8221;&nbsp;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">完整的应如下：&nbsp;</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&lt;Connector&nbsp;port="8080"&nbsp;maxThreads="150"&nbsp;minSpareThreads="25"&nbsp;maxSpareThreads="75"</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&nbsp;enableLookups="false"&nbsp;redirectPort="8443"&nbsp;acceptCount="100"&nbsp;debug="0"</p>
<p style="font-size: 9.75pt; margin: 0in 0in 0in 0.5in; color: black; font-family: Arial">&nbsp;connectionTimeout="20000"&nbsp;disableUploadTimeout="true"&nbsp;URIEncoding="GBK"/&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">2)重启tomcat,一切OK。</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">需要加入的原因大家可以去研究&nbsp;$TOMCAT_HOME/webapps/tomcat-docs/config/http.html下的这个文件就可以知道原因了。需要注意的是：这个地方如果你要是用UTF-8的时候在传递的过程中在Tomcat中也是要出现乱码的情况，如果不行的话就换别的字符集。</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">(四)&nbsp;&nbsp;&nbsp;&nbsp;JSP页面上有中文，按钮上面也有中文，但是通过服务器查看页面的时候出现乱码：</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;解决的办法是：首先在JSP文件中不应该直接包含本地化的消息文本，而是应该通过&lt;bean:message&gt;标签从Resource&nbsp;Bundle中获得文本。应该把你的中文文本放到Application.properties文件中，这个文件放在WEB-INF/classes/*下，例如我在页面里有姓名，年龄两个label,我首先就是要建一个Application.properties，里面的内容应该是name=&#8221;姓名&#8221;&nbsp;age=&#8221;年龄&#8221;,然后我把这个文件放到WEB-INF/classes/properties/下，接下来根据Application.properties文件，对他进行编码转化，创建一个中文资源文件，假定名字是Application_cn.properties。在JDK中提供了native2ascii命令，他能够实现字符编码的转换。在DOS环境中找到你放置Application.properties的这个文件的目录，在DOS环境中执行一下命令，将生成按GBK编码的中文资源文件Application_cn.properties：native2ascii&nbsp;?encoding&nbsp;gbk&nbsp;Application.properties&nbsp;Application_cn.properties执行以上命令以后将生成如下内容的Application_cn.properties文件：name="u59d3"u540d&nbsp;age="u5e74"u9f84,在Struts-config.xml中配置：&lt;message-resources&nbsp;parameter="properties.Application_cn"/&gt;。到这一步，基本上完成了一大半，接着你就要在JSP页面上写&lt;%@&nbsp;page&nbsp;language="java"&nbsp;contentType="text/html;charset=GBK"&nbsp;%&gt;,到名字的那个label是要写&lt;bean:message&nbsp;key=&#8221;name&#8221;&gt;,这样的化在页面上出现的时候就会出现中文的姓名，年龄这个也是一样，按钮上汉字的处理也是同样的。</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">(五)&nbsp;&nbsp;&nbsp;&nbsp;写入到数据库是乱码：</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">解决的方法：要配置一个filter,也就是一个Servelet的过滤器，代码如同第二种时候一样。</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">如果你是通过JDBC直接链接数据库的时候，配置的代码如下：jdbc:mysql://localhost:3306/workshopdb?useUnicode=true&amp;characterEncoding=GBK，这样保证到数据库中的代码是不是乱码。</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">如果你是通过数据源链接的化你不能按照这样的写法了，首先你就要写在配置文件中，在tomcat&nbsp;5.0.19中配置数据源的地方是在</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">C:"Tomcat&nbsp;5.0"conf"Catalina"localhost这个下面，我建立的工程是workshop，放置的目录是webapp下面,workshop.xml的配置文件如下：</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&lt;!--&nbsp;insert&nbsp;this&nbsp;Context&nbsp;element&nbsp;into&nbsp;server.xml&nbsp;--&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&lt;Context&nbsp;path="/workshop"&nbsp;docBase="workshop"&nbsp;debug="0"</p>
<p style="font-size: 9.75pt; margin: 0in; color: black"><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">reloadable="true"&nbsp;&gt;</span></p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&lt;Resource&nbsp;name="jdbc/WorkshopDB"</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;auth="Container"</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;type="javax.sql.DataSource"&nbsp;/&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&lt;ResourceParams&nbsp;name="jdbc/WorkshopDB"&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&lt;parameter&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;name&gt;factory&lt;/name&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value&gt;org.apache.commons.dbcp.BasicDataSourceFactory&lt;/value&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&lt;/parameter&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&lt;parameter&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;name&gt;maxActive&lt;/name&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value&gt;100&lt;/value&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&lt;/parameter&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&lt;parameter&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;name&gt;maxIdle&lt;/name&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value&gt;30&lt;/value&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&lt;/parameter&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&lt;parameter&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;name&gt;maxWait&lt;/name&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value&gt;10000&lt;/value&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&lt;/parameter&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;parameter&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;name&gt;username&lt;/name&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value&gt;root&lt;/value&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&lt;/parameter&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&lt;parameter&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;name&gt;password&lt;/name&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value&gt;&lt;/value&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&lt;/parameter&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&lt;!--&nbsp;Class&nbsp;name&nbsp;for&nbsp;mm.mysql&nbsp;JDBC&nbsp;driver&nbsp;--&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&lt;parameter&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;name&gt;driverClassName&lt;/name&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value&gt;com.mysql.jdbc.Driver&lt;/value&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black"><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">&lt;/parameter&gt;</span></p>
<p style="font-size: 9.75pt; margin: 0in; color: black"><span style="font-family: Arial">&nbsp;&nbsp;&nbsp;</span><span style="font-family: Arial">&lt;parameter&gt;</span></p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;name&gt;url&lt;/name&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black"><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">&lt;value&gt;</span></p>
<p style="font-size: 9.75pt; margin: 0in; color: black"><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">&lt;![CDATA[jdbc:mysql://localhost:3306/workshopdb?useUnicode=true<span style="color: #ff0000"><font face="Courier New">&amp;amp;</font></span>characterEncoding=GBK]]&gt;</span></p>
<p style="font-size: 9.75pt; margin: 0in; color: black"><span style="font-family: Verdana">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="font-family: Arial">&lt;/value&gt;</span></p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&lt;/parameter&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&lt;/ResourceParams&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&lt;/Context&gt;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">粗体的地方要特别的注意，和JDBC直接链接的时候是有区别的，如果你是配置正确的化，当你输入中文的时候到数据库中就是中文了，有一点要注意的是你在显示数据的页面也是要用&lt;%@&nbsp;page&nbsp;language="java"&nbsp;contentType="text/html;charset=GBK"&nbsp;%&gt;这行代码的。需要注意的是有的前台的人员在写代码的是后用Dreamver写的，写了一个Form的时候把他改成了一个jsp，这样有一个地方要注意了，那就是在Dreamver中Action的提交方式是request的，你需要把他该过来，因为在jsp的提交的过程中紧紧就是POST和GET两种方式，但是这两种方式提交的代码在编码方面还是有很大不同的，这个在后面的地方进行说明。3</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">以上就是我在开发系统中解决中文的问题，不知道能不能解决大家的问题，时间匆忙，没有及时完善，文笔也不是很好，有些地方估计是词不达意。大家可以给我意见，希望能共同进步。</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">其它上按以上的方法就可以解决的。</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">第（二）种方法里，这个过滤器比较简单，如果字符集不同的话，那就要手动修改这个过滤器，下面介绍一个功能强的过滤器：</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial"><br />
package com.manage.filter;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">import javax.servlet.*;<br />
import java.io.IOException;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial"><br />
public class SetCharacterEncodingFilter implements Filter {<br />
protected String encoding = null;<br />
protected FilterConfig filterConfig = null;<br />
protected boolean ignore = true;<br />
public void destroy() {</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">this.encoding = null;<br />
this.filterConfig = null;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">}</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial"><br />
public void doFilter(ServletRequest request, ServletResponse response,<br />
FilterChain chain)<br />
throws IOException, ServletException {<br />
if (ignore || (request.getCharacterEncoding() == null)) {<br />
String encoding = selectEncoding(request);<br />
if (encoding != null)<br />
request.setCharacterEncoding(encoding);<br />
}<br />
chain.doFilter(request, response);</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">}</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial"><br />
public void init(FilterConfig filterConfig) throws ServletException {</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">this.filterConfig = filterConfig;<br />
this.encoding = filterConfig.getInitParameter("encoding");<br />
String value = filterConfig.getInitParameter("ignore");<br />
if (value == null)<br />
this.ignore = true;<br />
else if (value.equalsIgnoreCase("true"))<br />
this.ignore = true;<br />
else if (value.equalsIgnoreCase("yes"))<br />
this.ignore = true;<br />
else<br />
this.ignore = false;</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">}<br />
protected String selectEncoding(ServletRequest request) {</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">return (this.encoding);</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">}</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">}//EOC</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">/**在web.xml里这样设置<br />
&nbsp;&nbsp;&lt;filter&gt;<br />
&nbsp;&nbsp;&lt;filter-name&gt;Set Character Encoding&lt;/filter-name&gt;<br />
&nbsp;&nbsp;&lt;filter-class&gt;<br />
&nbsp;&nbsp;&nbsp;com.manage.filter.SetCharacterEncodingFilter<br />
&nbsp;&nbsp;&lt;/filter-class&gt;<br />
&nbsp;&nbsp;&lt;init-param&gt;<br />
&nbsp;&nbsp;&nbsp;&lt;param-name&gt;encoding&lt;/param-name&gt;<br />
&nbsp;&nbsp;&nbsp;&lt;param-value&gt;UTF-8&lt;/param-value&gt;<br />
&nbsp;&nbsp;&lt;/init-param&gt;<br />
&nbsp;&nbsp;&lt;init-param&gt;<br />
&nbsp;&nbsp;&nbsp;&lt;param-name&gt;ignore&lt;/param-name&gt;<br />
&nbsp;&nbsp;&nbsp;&lt;param-value&gt;true&lt;/param-value&gt;<br />
&nbsp;&nbsp;&lt;/init-param&gt;<br />
&nbsp;&lt;/filter&gt;<br />
&nbsp;&lt;filter-mapping&gt;<br />
&nbsp;&nbsp;&lt;filter-name&gt;Set Character Encoding&lt;/filter-name&gt;<br />
&nbsp;&nbsp;&lt;servlet-name&gt;action&lt;/servlet-name&gt;<br />
&nbsp;&lt;/filter-mapping&gt; <br />
*/</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">针对第（二）种方法，还有一个很简单的方法，就是在每个页面里都加上以下代码：&lt;%request.setCharacterEncoding("gb2312");%&gt; <br />
&lt;%response.setCharacterEncoding("gb2312");%&gt; <br />
这样听说行，不过我试了没有效果</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 针对MYSQL数据库的中文乱码问题，我已经总结了一篇专门的解决方法，</p>
<p style="font-size: 9.75pt; margin: 0in; color: black; font-family: Arial">请参考<a href="http://www.busfly.cn/post/58.html">http://www.busfly.cn/post/58.html</a>&nbsp;<a href="http://www.busfly.cn/post/58.html">再谈乱码问题，如何解决MYSQL数据中文乱码问题</a></p>
</div>
<img src ="http://www.blogjava.net/xixidabao/aggbug/167375.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/xixidabao/" target="_blank">JAVA之路</a> 2007-12-13 09:02 <a href="http://www.blogjava.net/xixidabao/articles/167375.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>体验Struts(4)---用ajax实现三级下拉列表 </title><link>http://www.blogjava.net/xixidabao/articles/48315.html</link><dc:creator>JAVA之路</dc:creator><author>JAVA之路</author><pubDate>Fri, 26 May 2006 05:53:00 GMT</pubDate><guid>http://www.blogjava.net/xixidabao/articles/48315.html</guid><description><![CDATA[<pre>接着上次的话题，下面的就是学生注册时需要的学院，专业，班级，三层列表，
学院：
<html:select property="instituteId" onchange="getDepartments(this.value)">
     <html:options collection="institutes" property="value" labelProperty="label"/>
    </html:select>
专业：
<html:select property="departmentId" styleId="department" onchange="getClasses(this.value)"></html:select>
班级：
<html:select property="classId" styleId="classid" ></html:select>

学院是上来就应该有的，我们把他放到了LabelValueBean里
public Vector<LabelValueBean> getInstitutes()
    {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try
        {
            connection = getConnection();
            pstmt = connection.prepareStatement( "select * from institute" );
            rs = pstmt.executeQuery();
            Vector<LabelValueBean> institutes = new Vector<LabelValueBean>();
            institutes.add( new LabelValueBean( "请选择所在学院", "" ) );
            while ( rs.next() )
            {
                institutes.add( new LabelValueBean(
                        rs.getString( "institute" ), rs.getString( "id" ) ) );
            }
            return institutes;
        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }
        finally
        {
            close( rs );
            close( pstmt );
            close( connection );
        }
        return null;
    }
而当它选择了一个学院后，相应的getDepartments(this.value)的js脚本就该工作了，还是四步
var xmlHttp;
function createXMLHttpRequest()
{
 if (window.XMLHttpRequest) 
 { 
  xmlHttp = new XMLHttpRequest(); 
 }
 else if (window.ActiveXObject) 
 {
  xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
}
发出请求
function getDepartments(institute) 
{
 createXMLHttpRequest()
 var url = "ajax.do?institute="+institute+"&method=getDepartments"
 xmlHttp.open("GET",url, true)
 xmlHttp.onreadystatechange = departments
 xmlHttp.send(null)
}
处理响应
function departments()
{
 if (xmlHttp.readyState == 4) 
 {
  if (xmlHttp.status == 200) 
  {
   resText = xmlHttp.responseText
   each = resText.split("|")
   buildSelect( each, document.getElementById("departmentId"), "请选择所在专业");
  }
 }
}
function buildSelect(str,sel,label)
{
 sel.options.length=0;
 sel.options[sel.options.length]=new Option(label,"")
 for(var i=0;i<str.length;i++)
 {
  each=str[i].split(",")
  sel.options[sel.options.length]=new Option(each[0],each[1])
 }
}
我把从数据库中得到的各个专业进行了编码，之后再这里再回归回去，下面的是编码过程
public StringBuffer getDepartmentsByInstituteIdForAjax( Long instituteId )
    {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try
        {
            connection = getConnection();
            pstmt = connection
                    .prepareStatement( "select * from department where instituteID=?" );
            pstmt.setLong( 1, instituteId );
            rs = pstmt.executeQuery();
            StringBuffer sb = new StringBuffer();
            while ( rs.next() )
            {
                sb.append( rs.getString( "department" ) + ","
                        + rs.getLong( "id" ) );
                if ( !rs.isLast() ) sb.append( "|" );
            }
            return sb;
        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }
        finally
        {
            close( rs );
            close( pstmt );
            close( connection );
        }
        return null;
    }
当然这些都是由
public ActionForward getDepartments( ActionMapping mapping,
            ActionForm form, HttpServletRequest req, HttpServletResponse res )
            throws Exception
    {
        Service service = getService();
        res.getWriter().write(
                service.getDepartmentsByInstituteIdForAjax(
                        Long.parseLong( req.getParameter( "institute" ) ) )
                        .toString() );
        return null;
    }
来控制

===========班级的再这里
public ActionForward getClasses( ActionMapping mapping, ActionForm form,
            HttpServletRequest req, HttpServletResponse res ) throws Exception
    {
        Service service = getService();
        res.getWriter().write(
                service.getClassesByDepartmentIdForAjax(
                        Long.parseLong( req.getParameter( "department" ) ) )
                        .toString() );
        return null;
    }


public StringBuffer getClassesByDepartmentIdForAjax( Long departmentId )
    {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try
        {
            connection = getConnection();
            pstmt = connection
                    .prepareStatement( "select * from class where departmentID=?" );
            pstmt.setLong( 1, departmentId );
            rs = pstmt.executeQuery();
            StringBuffer sb = new StringBuffer();
            while ( rs.next() )
            {
                sb.append( rs.getString( "class" ) + "," + rs.getLong( "id" ) );
                if ( !rs.isLast() ) sb.append( "|" );
            }
            return sb;
        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }
        finally
        {
            close( rs );
            close( pstmt );
            close( connection );
        }
        return null;
    }

function getClasses(department)
{
 createXMLHttpRequest()
 var url = "ajax.do?department="+department+"&method=getClasses"
 xmlHttp.open("GET",url, true)
 xmlHttp.onreadystatechange = classes
 xmlHttp.send(null)
}

function classes()
{
 if (xmlHttp.readyState == 4) 
 {
  if (xmlHttp.status == 200) 
  {
   resText = xmlHttp.responseText
   each = resText.split("|")
   buildSelect( each, document.getElementById("classid"), "请选择所在班级");
  }
 }
} 


</pre><img src ="http://www.blogjava.net/xixidabao/aggbug/48315.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/xixidabao/" target="_blank">JAVA之路</a> 2006-05-26 13:53 <a href="http://www.blogjava.net/xixidabao/articles/48315.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>体验Struts(3)---加上点ajax </title><link>http://www.blogjava.net/xixidabao/articles/48314.html</link><dc:creator>JAVA之路</dc:creator><author>JAVA之路</author><pubDate>Fri, 26 May 2006 05:52:00 GMT</pubDate><guid>http://www.blogjava.net/xixidabao/articles/48314.html</guid><description><![CDATA[<pre>你问我什么叫ajax，我也不太了解，我了解的是那支培养了无数荷兰足球精华的Ajax，谁知道怎么有人用几个单词的头字母也能凑出这个单词来，不过感觉用它来做东西，应该会挺有意思的
比如当用户在注册的时候，用户点一个按纽不用刷新界面就可以获得一句提示，是有这人还是没有这人啊？这次我尝试了用ajax技术来做一个三级关键的下拉列表，而这是我要讲的关键。
其实现在一般的ajax都是向Servlet发出请求，之后服务器响应，再偷摸的把结果传给它，之后显示出来，而换到Struts，有人会发甍，也一样，Action是Servlet，DispatchAction也是，只要把代码往这里写，让它往.do那里请求就行了。
在接下来我就向大家介绍我是怎样实现上述功能的
因为大学里面的结构是这里的
学院-专业-班级-学生
在学生注册的时候他是依赖于上述对象的，所以用户注册就需要一个三级的下拉选择
而ajax就能象变魔术一样，从服务器那里偷摸弄来您需要的列表
下面我先给大家展示一下第一个功能是怎么实现的吧？
当用户在注册的时候，点一个按纽，之后会弹出一个alert来告诉你这个用户是否有人用了，下面就让我们来看看这个功能是怎么实现的吧？

<html:button styleClass="cancel" property="submit" value="验证用户是否存在" onclick="teacherCheck()"/>
这里定义了按纽，用来测试老师是否已经存在了
大体的ajax的JS代码都上面这四部分，
先是创建XMLHttpRequest，
var xmlHttp;
function createXMLHttpRequest()
{
 if (window.XMLHttpRequest) 
 { 
  xmlHttp = new XMLHttpRequest(); 
 }
 else if (window.ActiveXObject) 
 {
  xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
}
之后是客户响应部分的代码
function teacherCheck() 
{
 var f = document.TeacherRegisterForm 从表单里读字段
 var user = f.user.value
 if(user=="") 
 {
　　 window.alert("用户名不能为空！")
  f.user.focus()
　　 return false
   }
 else 
 {
  createXMLHttpRequest()        这里都是精华了
  var url = "ajax.do?method=checkUserIsExist&user="+user   定义响应地址
  xmlHttp.open("GET",url, true)    发出响应
  xmlHttp.onreadystatechange = checkUser  把从服务器得到的响应再传给另个函数
  xmlHttp.send(null)
   }
}

function checkUser()
{
 if (xmlHttp.readyState == 4) 
 {
  if (xmlHttp.status == 200) 
  {
   alert(xmlHttp.responseText)        这里是对响应结果的操作，在这里我们是滩出对话框，并把服务器发来的信息显示出来
  }
 }
}
我把所有乱七八糟的操作都放到了一个DispatchAction里，所以它也不例外的在这个DA中了
public ActionForward checkUserIsExist( ActionMapping mapping,
            ActionForm form, HttpServletRequest req, HttpServletResponse res )
            throws Exception
    {
        Service service = getService();
        res.getWriter().write(service.checkUserIsExistForAjax( req.getParameter( "user" ) ) );
        return null;
    }
它仅仅是把业务逻辑部分的结果发送回去，而真正的判断是在业务逻辑那里实现的，
public String checkUserIsExistForAjax( String user )把结果弄成String的形式传回去
    {
        Connection connection = null;
        PreparedStatement pstmt1 = null;
        ResultSet rs = null;
        try
        {
            connection = getConnection();
            pstmt1 = connection
                    .prepareStatement( "select * from user where user=?" );
            pstmt1.setString( 1, user );
            rs = pstmt1.executeQuery();
            rs.last();
            if ( rs.getRow() > 0 )
            {
                return ID.M_EXIST; 用户存在
            }
        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }
        finally
        {
            close( rs );
            close( pstmt1 );
            close( connection );
        }
        return ID.M_NOEXIST;用户不存在
    }
</pre>

<img src ="http://www.blogjava.net/xixidabao/aggbug/48314.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/xixidabao/" target="_blank">JAVA之路</a> 2006-05-26 13:52 <a href="http://www.blogjava.net/xixidabao/articles/48314.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>体验Struts(2)---整体结构</title><link>http://www.blogjava.net/xixidabao/articles/48313.html</link><dc:creator>JAVA之路</dc:creator><author>JAVA之路</author><pubDate>Fri, 26 May 2006 05:51:00 GMT</pubDate><guid>http://www.blogjava.net/xixidabao/articles/48313.html</guid><description><![CDATA[<pre>为了让大家更方便的了解我这个设计，我先把我的一些整体的规划都说出来吧，由于我是初学，难免会参照本书籍来看，我买的是那本孙某女的书《精通：*****》，看了看她前面的介绍，我一看了不得，能出书，写的还都不错，这女的可不得了，渐渐疑惑的地方非常多，比如例子里面注释都拽上了英语，搞不懂，而当我从网上下到电子盗版jakarta struts（我已安下栽说明要求的那样在24小时后删除了）这本书的时候我才恍然大悟，原来是抄袭啊？至于是谁抄的谁，口说无凭，不能乱诽谤，不过大家心里都该有杆称！

下面就是代码了：
package com.boya.subject.model;
public interface Person
{
    public Long getId();
    public void setId( Long id );
    public String getName();
    public void setName( String name );
    public String getPassword();
    public void setPassword( String password );
    public String getTelphone();
    public void setTelphone( String telphone );
    public String getUser();
    public void setUser( String user );
    public String getType();
}

package com.boya.subject.model;
public abstract class User implements Person
{
    private Long id;数据库id
    private String user;用户名
    private String password;密码
    private String name;姓名
    private String telphone;电话

    public Long getId()
    {
        return id;
    } 

    public void setId( Long id )
    {
        this.id = id;
    } 

    public String getName()
    {
        return name;
    } 

    public void setName( String name )
    {
        this.name = name;
    } 

    public String getPassword()
    {
        return password;
    } 

    public void setPassword( String password )
    {
        this.password = password;
    } 

    public String getTelphone()
    {
        return telphone;
    } 

    public void setTelphone( String telphone )
    {
        this.telphone = telphone;
    } 

    public String getUser()
    {
        return user;
    } 

    public void setUser( String user )
    {
        this.user = user;
    }
}

package com.boya.subject.model;
public class Admin extends User
{
    private String grade = null; 管理员权限 

    public String getGrade()
    {
        return grade;
    } 

    public void setGrade( String grade )
    {
        this.grade = grade;
    } 

    public String getType()
    {
        return "admin";
    }
}

package com.boya.subject.model;
public class Teacher extends User
{
    private String level; 教师职称 

    public String getLevel()
    {
        return level;
    } 

    public void setLevel( String level )
    {
        this.level = level;
    } 

    public String getType()
    {
        return "teacher";
    }
}

package com.boya.subject.model; 

public class Student extends User
{
    private String sn;学生学号
    private SchoolClass schoolClass; 班级 

    public SchoolClass getSchoolClass()
    {
        return schoolClass;
    } 

    public void setSchoolClass( SchoolClass schoolClass )
    {
        this.schoolClass = schoolClass;
    } 

    public String getSn()
    {
        return sn;
    } 

    public void setSn( String sn )
    {
        this.sn = sn;
    } 

    public String getType()
    {
        return "student";
    }
}

而对于Action我分别做了一个抽象类，之后别的从这里继承
先是Action的
package com.boya.subject.controller; 

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.boya.subject.frame.ID;
import com.boya.subject.frame.ServiceFactory;
import com.boya.subject.model.Person;
import com.boya.subject.service.Service;
import com.boya.subject.util.HtmlUtil; 

public abstract class BaseAction extends Action
{
    /**
     * 由服务工厂方法创建服务
     * @return 数据库操作的服务
     * 2006-5-16 18:10:04
     */
    public Service getService()
    {
        ServiceFactory factory = (ServiceFactory) getAppObject( ID.SF );
        Service service = null;
        try
        {
            service = factory.createService();
        }
        catch ( Exception e )
        {
        }
        return service;
    } 

    /**
     * 判断用户是否合法登陆
     * @param req 
     * @return 用户是否登陆
     * 2006-5-16 18:11:26
     */
    public boolean isLogin( HttpServletRequest req )
    {
        if ( getPerson( req ) != null ) return true;
        else
            return false;
    } 

    
    /**
     * 抽象方法,子类实现
     * @param mapping
     * @param form
     * @param req
     * @param res
     * @return
     * @throws Exception
     * 2006-5-16 18:12:54
     */
    protected abstract ActionForward executeAction( ActionMapping mapping,
            ActionForm form, HttpServletRequest req, HttpServletResponse res )
            throws Exception; 

    /**
     * 获取session范围的用户
     * @param req
     * @return 当前用户
     * 2006-5-16 18:13:35
     */
    public abstract Person getPerson( HttpServletRequest req ); 

    /**
     * 父类的执行Action
     * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    public ActionForward execute( ActionMapping mapping, ActionForm form,
            HttpServletRequest req, HttpServletResponse res ) throws Exception
    {
        if ( !isLogin( req ) )
        {
            HtmlUtil.callParentGo( res.getWriter(), ID.M_UNLOGIN, ID.P_INDEX );
            return null;
        }
        return executeAction( mapping, form, req, res );
    } 

    /**
     * 删除session中属性为attribute的对象
     * @param req
     * @param attribute 对象属性
     * 2006-5-16 18:16:59
     */
    public void removeSessionObject( HttpServletRequest req, String attribute )
    {
        HttpSession session = req.getSession();
        session.removeAttribute( attribute );
    } 

    /**
     * 设置session中属性为attribute的对象
     * @param req
     * @param attribute 设置属性
     * @param o 设置对象
     * 2006-5-16 18:17:50
     */
    public void setSessionObject( HttpServletRequest req, String attribute,
            Object o )
    {
        req.getSession().setAttribute( attribute, o );
    } 

    /**
     * 设置application中属性为attribute的对象
     * @param req
     * @param attribute 设置属性
     * @param o 设置对象
     * 2006-5-16 18:17:50
     */
    public void setAppObject( String attribute, Object o )
    {
        servlet.getServletContext().setAttribute( attribute, o );
    } 

    public Object getSessionObject( HttpServletRequest req, String attribute )
    {
        Object obj = null;
        HttpSession session = req.getSession( false );
        if ( session != null ) obj = session.getAttribute( attribute );
        return obj;
    } 

    public Object getAppObject( String attribute )
    {
        return servlet.getServletContext().getAttribute( attribute );
    } 

    public void callParentGo( HttpServletResponse res, String msg, String url )
            throws IOException
    {
        HtmlUtil.callParentGo( res.getWriter(), msg, url );
    } 

    public void callMeGo( HttpServletResponse res, String msg, String url )
            throws IOException
    {
        HtmlUtil.callMeGo( res.getWriter(), msg, url );
    } 

    public void callBack( HttpServletResponse res, String msg )
            throws IOException
    {
        HtmlUtil.callBack( res.getWriter(), msg );
    } 

    public void callMeConfirm( HttpServletResponse res, String msg, String ok,
            String no ) throws IOException
    {
        HtmlUtil.callMeConfirm( res.getWriter(), msg, ok, no );
    }
}
再是DispatchAction的
package com.boya.subject.controller; 

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import com.boya.subject.frame.ID;
import com.boya.subject.frame.ServiceFactory;
import com.boya.subject.model.Person;
import com.boya.subject.service.Service;
import com.boya.subject.util.HtmlUtil; 

public abstract class BaseDispatchAction extends DispatchAction
{
    /**
     * 由服务工厂方法创建服务
     * @return 数据库操作的服务
     * 2006-5-16 18:10:04
     */
    public Service getService()
    {
        ServiceFactory factory = (ServiceFactory) getAppObject( ID.SF );
        Service service = null;
        try
        {
            service = factory.createService();
        }
        catch ( Exception e )
        {
        }
        return service;
    } 

    /**
     * 判断用户是否合法登陆
     * @param req 
     * @return 用户是否登陆
     * 2006-5-16 18:11:26
     */
    public boolean isLogin( HttpServletRequest req )
    {
        if ( getPerson( req ) != null ) return true;
        else
            return false;
    } 

    /**
     * 获取session范围的用户
     * @param req
     * @return 当前用户
     * 2006-5-16 18:13:35
     */
    public abstract Person getPerson( HttpServletRequest req ); 

    /**
     * 父类的执行DispatchAction
     * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    public ActionForward execute( ActionMapping mapping, ActionForm form,
            HttpServletRequest req, HttpServletResponse res ) throws Exception
    {
        try
        {
            if ( !isLogin( req ) )
            {
                callParentGo( res, ID.M_UNLOGIN, ID.P_INDEX );
                return null;
            }
            return super.execute( mapping, form, req, res );
        }
        catch ( NoSuchMethodException e )
        {
            callBack( res, ID.M_NOMETHOD );
            return null;
        }
    } 

    /**
     * 删除session中属性为attribute的对象
     * @param req
     * @param attribute 对象属性
     * 2006-5-16 18:16:59
     */
    public void removeSessionObject( HttpServletRequest req, String attribute )
    {
        HttpSession session = req.getSession();
        session.removeAttribute( attribute );
    } 

    /**
     * 设置session中属性为attribute的对象
     * @param req
     * @param attribute 设置属性
     * @param o 设置对象
     * 2006-5-16 18:17:50
     */
    public void setSessionObject( HttpServletRequest req, String attribute,
            Object o )
    {
        req.getSession().setAttribute( attribute, o );
    } 

    /**
     * 设置application中属性为attribute的对象
     * @param req
     * @param attribute 设置属性
     * @param o 设置对象
     * 2006-5-16 18:17:50
     */
    public void setAppObject( String attribute, Object o )
    {
        servlet.getServletContext().setAttribute( attribute, o );
    } 

    public Object getSessionObject( HttpServletRequest req, String attribute )
    {
        Object obj = null;
        HttpSession session = req.getSession( false );
        if ( session != null ) obj = session.getAttribute( attribute );
        return obj;
    } 

    public Object getAppObject( String attribute )
    {
        return servlet.getServletContext().getAttribute( attribute );
    } 

    public void callParentGo( HttpServletResponse res, String msg, String url )
            throws IOException
    {
        HtmlUtil.callParentGo( res.getWriter(), msg, url );
    } 

    public void callMeGo( HttpServletResponse res, String msg, String url )
            throws IOException
    {
        HtmlUtil.callMeGo( res.getWriter(), msg, url );
    } 

    public void callBack( HttpServletResponse res, String msg )
            throws IOException
    {
        HtmlUtil.callBack( res.getWriter(), msg );
    } 

    public void callMeConfirm( HttpServletResponse res, String msg, String ok,
            String no ) throws IOException
    {
        HtmlUtil.callMeConfirm( res.getWriter(), msg, ok, no );
    }
} 
对于程序中的一些提示信息，我比较喜欢用JS来写，所以我把这些都放到了一个类中
import java.io.IOException;
import java.io.Writer; 

public class HtmlUtil
{
    public static void callParentGo( Writer out, String msg, String url )
            throws IOException
    {
        out.write( "<script language=\"javascript\">" );
        out.write( "alert(\"" + msg + "\");" );
        out.write( "parent.location.href=\"" + url + "\";" );
        out.write( "</script>" );
    } 

    public static void callMeGo( Writer out, String msg, String url )
            throws IOException
    {
        out.write( "<script language=\"javascript\">" );
        out.write( "alert(\"" + msg + "\");" );
        out.write( "location.href=\"" + url + "\";" );
        out.write( "</script>" );
    } 

    public static void callMeConfirm( Writer out, String msg ,String ok, String no )
            throws IOException
    {
        out.write( "<script language=\"javascript\">" );
        out.write( "if(window.confirm(\"" + msg + "\")){" );
        out.write( "location.href=\"" + ok + "\"}else{" );
        out.write( "location.href=\"" + no + "\"}" );
        out.write( "</script>" );
    } 

    public static void callBack( Writer out, String msg ) throws IOException
    {
        out.write( "<script language=\"javascript\">" );
        out.write( "alert(\"" + msg + "\");" );
        out.write( "parent.history.back();" );
        out.write( "</script>" );
    }
} 
</pre>

<img src ="http://www.blogjava.net/xixidabao/aggbug/48313.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/xixidabao/" target="_blank">JAVA之路</a> 2006-05-26 13:51 <a href="http://www.blogjava.net/xixidabao/articles/48313.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>体验Struts(1)---用户登陆的实现 </title><link>http://www.blogjava.net/xixidabao/articles/48311.html</link><dc:creator>JAVA之路</dc:creator><author>JAVA之路</author><pubDate>Fri, 26 May 2006 05:50:00 GMT</pubDate><guid>http://www.blogjava.net/xixidabao/articles/48311.html</guid><description><![CDATA[<pre>看到题目，您一定觉得很土，Struts早已风靡，而关于Stuts的文章也早已遍地都是，如果你觉得土那你就别看了，我只是把我这段时间学到的一些比较肤浅知识在这里记录一下，如果您真在这些连载文章中获得了您想要的知识，那么我就会很欣慰了。
        这不快毕业了吗？我选的题目就和Struts有关，做一个关于学校的毕业设计选题系统，就是B/S结构，访问数据库的一些俗套的东西，为了巩固我这段时间学习Struts，我把这个系统竟往难里做，这样对我这个动手能力差的人，实际工作经验少的人来说，会有点帮助吧？
        当初就是这样想的，所以就开始了我的Struts之旅。
        那我就从我的第一页讲起吧，当然第一页一般都是登陆，至于怎么配置Struts，您还是参考一些别人的文章吧，我觉得写这些就够土的了，写怎么配置，怎么实现就更土！

        <%@ page contentType="text/html; charset=gb2312"%>
        <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
       <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
       <html:javascript dynamicJavascript="true" staticJavascript="true" formName="LoginForm"/>这句是生成验证登陆表单所需要的js代码
       <html:form action="/ajax.do?method=login" onsubmit="return validateLoginForm(this)">
            用户名：<html:text property="user" size="16" maxlength="16"/>
            密码：    <html:password property="password" size="16" maxlength="16"/>
                           <html:submit styleClass="loginbutton" property="submit" value="登陆"/>
                           <html:button property="reg" styleClass="loginbutton" 
                                    onclick="window.location='ajax.do?method=register'" value="注册"/>
                           <html:errors property="user"/><html:errors property="password"/>
       </html:form>

       把控制格式的HTML删除掉，应该剩下这些就是主干了，对于这个毕业设计选题系统，有三种角色，管理员(Admin)，教师(Teacher)，学生(Student)而我把他们的登陆都做到了一起，在后台这三种角色也是都放在了一个表中，对于他们这三种对象，都是继承于Person的类，所以在登陆时可以忽视他们的具体角色，用多态来实现登陆。        

    action="/ajax.do?method=login" ：将一些关于登陆啊，注册的一些乱七八糟的操作我都放到了一个DispatchAction，之后可以用method的不同来分别调用不同的功能。
   onsubmit="return validateLoginForm(this)"：这个是用来实现Struts自带的validate验证
   <html:errors property="user"/><html:errors property="password"/> ：是用来显示在登陆时的错误信息

    在这里需要的Struts相关配置会有如下的几个方面：
      首先是要对配置文件进行配置我们登陆时需要的FormBean和Action
       (1)struts-config.xml：
            <form-bean name="LoginForm" type="com.boya.subject.view.LoginForm" />
            <action path="/ajax" type="com.boya.subject.controller.InterDispatchAction" name="LoginForm" scope="request" validate="true" input="/index.jsp" parameter="method">
                  <forward name="fail" path="/index.jsp" />   对于登陆失败，我们准备返回到这里
           </action>
     (2)validation.xml:
            <constant>
                  <constant-name>user</constant-name>
                  <constant-value>^[0-9a-zA-Z]*$</constant-value>
               这里是常量配置，因为我们还会需要到用户名的验证，所以把他设置为了常量
           </constant>
          下面是对这个bean的具体严整手段了，按字段field分别来写他们所依赖depaends的检验手段，常用的有必须填required，正则表达式验证mask，最大maxlength和最小minlength
            <form name="LoginForm">
              <field property="user"对应LoginForm里的一个属性  depends="required,mask,minlength,maxlength">
                   <msg name="mask" key="input.user.mask" />从application.properties里读取input.user.mask           
                    <arg0 key="input.user" resource="true" />从application.properties里读取input.user
                   <arg1 name="minlength" key="${var:minlength}" resource="false" />
                   <arg1 name="maxlength" key="${var:maxlength}" resource="false" />
                  以上三部分构成了js的一条错误提示，以下是具体的严整规则了
                <var>
                    <var-name>mask</var-name>
                    <var-value>${user}</var-value>
                </var>
                <var>
                    <var-name>minlength</var-name>
                    <var-value>1</var-value>
                </var>
                <var>
                    <var-name>maxlength</var-name>
                    <var-value>16</var-value>
                </var>
         </field>
   <field property="password"
    depends="required,mask,minlength,maxlength">
    <arg0 key="input.password" resource="true" />
    <arg1 name="minlength" key="${var:minlength}"
     resource="false" />
    <arg1 name="maxlength" key="${var:maxlength}"
     resource="false" />
    <var>
     <var-name>mask</var-name>
     <var-value>${password}</var-value>
    </var>
    <var>
     <var-name>minlength</var-name>
     <var-value>1</var-value>
    </var>
    <var>
     <var-name>maxlength</var-name>
     <var-value>16</var-value>
    </var>
   </field>

  </form>
 对于我们需要的FormBean是这样写的：
package com.boya.subject.view;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;

public class LoginForm extends ActionForm
{
    private static final long serialVersionUID = 1L;
    private String user = null;
    private String password = null;

    public String getPassword()
    {
        return password;
    }

    public void setPassword( String password )
    {
        this.password = password;
    }

    public String getUser()
    {
        return user;
    }

    public void setUser( String user )
    {
        this.user = user;
    }
    
    public void reset(ActionMapping mapping,HttpServletRequest request)
    {
        this.password = null;这里很重要，当用户输入有错时，需要返回登陆界面给用户，为了用户填写方便我们可以设置返回给用户的哪部分信息设置为空
    }
}

我用来实现登陆的DispatchAction代码如下：
      public ActionForward login( ActionMapping mapping, ActionForm form,
            HttpServletRequest req, HttpServletResponse res ) throws Exception
    {
         Service service = getService();调用业务逻辑
        LoginForm loginForm = (LoginForm) form;获取formbean
        String user = loginForm.getUser();提取用户名
        Person person = service.getUser( user );从业务逻辑中查找用户
        ActionMessages messages = new ActionMessages();
        ActionMessage am;
        if ( person == null )如果用户不存在，我们就返回
        {
            am = new ActionMessage( "index.jsp.fail.user", user );参数的意义：第一个是主串，而后面的作为arg数组
            messages.add( "user", am );把错误信息放到errors 属性为user那里去显示
            saveErrors( req, messages );
            form.reset( mapping, req );如果出现错误，调用formbean的重置功能
            return mapping.findForward( ID.FAIL );
        }
        if ( !person.getPassword().equals( loginForm.getPassword() ) )如果密码不一致
        {
            am = new ActionMessage( "index.jsp.fail.password", user );
            messages.add( "password", am );
            saveErrors( req, messages );
            form.reset( mapping, req );
            return mapping.findForward( ID.FAIL );
        }
       
        setSessionObject( req, person.getType(), person );把用户放到session里
        return new ActionForward( person.getType() + ".do", true );我在每个类型用户的类中加入了一个getType来在这里调用，之后动态的去对应的admin.do,student.do,teacher.do的主页面，并且这里实现的不是请求转发，而是请求从定向
   }


</pre><img src ="http://www.blogjava.net/xixidabao/aggbug/48311.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/xixidabao/" target="_blank">JAVA之路</a> 2006-05-26 13:50 <a href="http://www.blogjava.net/xixidabao/articles/48311.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>体验Struts(5)---从分页体会MVC </title><link>http://www.blogjava.net/xixidabao/articles/48310.html</link><dc:creator>JAVA之路</dc:creator><author>JAVA之路</author><pubDate>Fri, 26 May 2006 05:48:00 GMT</pubDate><guid>http://www.blogjava.net/xixidabao/articles/48310.html</guid><description><![CDATA[<pre>大家都知道Struts是一种基于MVC的结构，而这个MVC又怎么样理解呢？书上阐述的一般都很详细，而我的理解很直白，我们可以把业务逻辑放到每个JSP页面中，当你访问一个JSP页面的时候，就可以看到业务逻辑得到的结果，而把这些业务逻辑与HTML代码夹杂到了一起，一定会造成一些不必要的麻烦，可以不可以不让我们的业务逻辑和那些HTML代码夹杂到一起呢？多少得搀杂一些，那干脆，尽量少的吧，于是我们可以尝试着把业务逻辑的运算过程放到一个Action里，我们访问这个Action，之后Action执行业务逻辑，最后把业务逻辑的结果放到request中，并将页面请求转发给一个用于显示结果的jsp页面，这样，这个页面就可以少去很多的业务逻辑，而只是单纯的去显示一些业务逻辑计算结果的页面而已。这时的Action称为控制器，JSP页可以叫做视图了，而控制器操作的业务对象，无非就应该叫模型了！

从上面的话，我们来分析一下当我们要做一个分页时所需要的部分，而在这之前，我们先看看他们的执行过程吧，首先我们第一次请求访问一个页面，它会把所有记录的前N条显示给我们，之后计算是否有下一页，等类似的信息，当我们点下一页的时候，就获取下一页的信息，我们还可以添加一个搜索，比如我们用于显示学生的，可以安学生姓名查找，学号查找，班级查找。而对于显示的对象，我们一般也都会封装为javabean，所以用于放置查询结果的容器是不定的，而这时，我们就需要用泛型来提升我们的代码效率！

首先我们写一个用于分页显示的javabean：

package com.boya.subject.model;

import java.util.Vector; 

public class Page<E>
{
    private int current = 1;        //当前页
    private int total = 0;         //总记录数
    private int pages = 0;    //总页数
    private int each = 5;         //每页显示
    private int start = 0;      //每页显示的开始记录数
    private int end = 0;       //每页显示的结束记录数
    private boolean next = false;        //是否有下一页
    private boolean previous = false;  //是否有上一页
    private Vector<E> v = null;    //存放查询结果的容器 

    public Page( Vector<E> v ,int per)
    {
        this.v = v;
        each = per;
        total = v.size();   //容器的大小就是总的记录数
        if ( total % each == 0 ) 
            pages = total / each;       //计算总页数
        else
            pages = total / each + 1;
        if ( current >= pages )
        {
            next = false;
        }
        else
        {
            next = true;
        }
        if ( total < each )
        {
            start = 0;
            end = total;
        }
        else
        {
            start = 0;
            end = each;
        }
    }
    
    public int getCurrent()
    {
        return current;
    } 

    public void setCurrent( int current )
    {
        this.current = current;
    } 

    public int getEach()
    {
        return each;
    } 

    public void setEach( int each )
    {
        this.each = each;
    } 

    public boolean isNext()
    {
        return next;
    } 

    public void setNext( boolean next )
    {
        this.next = next;
    } 

    public boolean isPrevious()
    {
        return previous;
    } 

    public void setPrevious( boolean previous )
    {
        this.previous = previous;
    } 

    public int getEnd()
    {
        return end;
    } 

    public int getPages()
    {
        return pages;
    } 

    public int getStart()
    {
        return start;
    } 

    public int getTotal()
    {
        return total;
    } 

 //获取下一页的对象们   

public Vector<E> getNextPage()
    {
        current = current + 1;
        if ( (current - 1) > 0 )
        {
            previous = true;
        }
        else
        {
            previous = false;
        }
        if ( current >= pages )
        {
            next = false;
        }
        else
        {
            next = true;
        }
        Vector<E> os = gets();
        return os;
    }

 //获取上一页 

    public Vector<E> getPreviouspage()
    {
        current = current - 1;
        if ( current == 0 )
        {
            current = 1;
        }
        if ( current >= pages )
        {
            next = false;
        }
        else
        {
            next = true;
        }
        if ( (current - 1) > 0 )
        {
            previous = true;
        }
        else
        {
            previous = false;
        }
        Vector<E> os = gets();
        return os;
    }

 //一开始获取的 

    public Vector<E> gets()
    {
        if ( current * each < total )
        {
            end = current * each;
            start = end - each;
        }
        else
        {
            end = total;
            start = each * (pages - 1);
        }
        Vector<E> gets = new Vector<E>();
        for ( int i = start; i < end; i++ )
        {
            E o = v.get( i );
            gets.add( o );
        }
        return gets;
    }
}



 而对于按不同搜索，我们需要一个FormBean，一般的搜索，都是模糊搜索，搜索个大概，而且输入的信息中文的比重也会很大，所以，我把对中文字符的转换放到了这个BEAN里，在进行select * from * where like这样的查询时，如果是like ''这样就可以得到所有的记录了，我便用这个来对付没有输入查询关键字的情况，而like '%*%'可以匹配关键字，而%%也在这里添加上了！

package com.boya.subject.view; 

import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping; 

public class SearchForm extends ActionForm
{
    private static final long serialVersionUID = 1L;
    private String key;
    private String from; 

    public String getFrom()
    {
        return from;
    } 

    public void setFrom( String from )
    {
        this.from = from;
    } 

      public void reset( ActionMapping mapping, HttpServletRequest req )
    {
        this.key = null;
    } 

    public String getKey()
    {
        return key;
    } 

    public void setKey( String key )
    {
        try
        {
            key = new String( key.getBytes( "iso-8859-1" ), "gb2312" );
        }
        catch ( UnsupportedEncodingException e )
        {
            e.printStackTrace();
        }
        this.key = "%" + key + "%";
    }
    
    public String getAny(){
        return "%%";
    }
}
前期都做好了，我现在就要开始访问这个Action了，可是这个控制器还没写呢！这里是代码 

public class AdminUserAction extends AdminAction
{
    private Vector<Student> ss; //用来装结果的容器
    private Page<Student> ps; //分页显示的PAGE对象 

    protected ActionForward executeAction( ActionMapping mapping,
            ActionForm form, HttpServletRequest req, HttpServletResponse res )
            throws Exception
    {
        if ( !isSupper( req ) )
        {
            return notSupper( res );//如果不是超级管理员怎么办？
        }
        Service service = getService();//获取业务逻辑
        SearchForm sf = (SearchForm) form;//获取搜索FORM
        String op = req.getParameter( "op" );//获取用户对页面的操作
        String search = req.getParameter( "search" );//是否执行了搜索
        Vector<Student> temp = null; //用于存放临时反馈给用户的结果容器
                if ( op == null )//如果用户没有执行上/下一页的操作
                {
                    if ( search != null )//用户如果执行了搜索
                    {
                        if ( sf.getFrom().equalsIgnoreCase( "class" ) )//如果是按班级查找
                        {
                            ss = service.getAllStudentBySchoolClassForAdmin( sf
                                    .getKey() );//获取from的关键字
                        }
                        else if ( sf.getFrom().equalsIgnoreCase( "name" ) )//如果是按姓名查找
                        {
                            ss = service.getAllStudentByNameForAdmin( sf
                                    .getKey() );
                        }
                        else if ( sf.getFrom().equalsIgnoreCase( "user" ) )//如果是按用户名查找
                        {
                            ss = service.getAllStudentByUserForAdmin( sf
                                    .getKey() );
                        }
                        else
                        {
                            ss = service.getAllStudentBySnForAdmin( sf.getKey() );//按学号查找
                        }
                        form.reset( mapping, req );//重置搜索表单
                    }
                    else
                    {
                        ss = service.getAllStudentForAdmin( sf.getAny() ); //用户未执行查找就显示全部，
                    }
                    if ( ss != null && ss.size() != 0 )//如果查找不为空，有记录，那就创建一个分页对象
                    {
                        ps = new Page<Student>( ss, 10 );//将查询结果和每页显示记录数作为参数构件对象
                        temp = ps.gets();//并获取第一页
                    }
                }
                else//如果用户执行了操作
                {
                    if ( op.equals( "next" ) )//操作是下一页
                    {
                        temp = ps.getNextPage();
                    }
                    if ( op.equals( "previous" ) )//操作是上一页
                    {
                        temp = ps.getPreviouspage();
                    }
                }
                req.setAttribute( "search", SelectUtil.studentSearch() );//把搜索用到的表单放到request中
                req.setAttribute( "students", temp );//该页显示的学生
                req.setAttribute( "page", ps );//分页对象
                return mapping.findForward( "student" );//请求转发
    }
}


用到SelectUtil中的代码如下：
/**
     * 获取学生查找类别的select
     * @return 学生查找类别
     * 2006-5-17 9:06:12
     */
    public static Vector<LabelValueBean> studentSearch()
    {
        Vector<LabelValueBean> s = new Vector<LabelValueBean>();
        s.add( new LabelValueBean( "按学号查找", "sn" ) );
        s.add( new LabelValueBean( "按班级查找", "class" ) );
        s.add( new LabelValueBean( "按姓名查找", "name" ) );
        s.add( new LabelValueBean( "按用户查找", "user" ) );
        return s;
    }
在看页面视图前先让我们看看Model吧，

public class Student extends User
{
    private String sn;
    private SchoolClass schoolClass; //这里的班级做为了一种对象，我们在视图显示的时候就有了一层嵌套 

    public SchoolClass getSchoolClass()
    {
        return schoolClass;
    } 

    public void setSchoolClass( SchoolClass schoolClass )
    {
        this.schoolClass = schoolClass;
    } 

    public String getSn()
    {
        return sn;
    } 

    public void setSn( String sn )
    {
        this.sn = sn;
    } 

    public String getType()
    {
        return "student";
    }
}
在了解了model后，还是看看视图吧，


先放个查询表单：

<html:javascript dynamicJavascript="true" staticJavascript="true" formName="SearchForm" />
<html:form action="/adminUser.do?search=true" onsubmit="return validateSearchForm(this)">

<html:select property="from" >
<html:options collection="search" property="value" labelProperty="label" />
</html:select>

<html:text property="key" size="16" maxlength="16"/>

<html:image src="images/search.gif"/>

</html:form>

由于模型中有嵌套，那么我们就将用到Nested标签，其实没有嵌套也可以使用这个标签，下面的是用于显示信息的，用迭迨器进行遍历request范围的students，你不安排范围，他会自动找到的，并把每次遍历的对象起名叫student，并作为层次的根元素，

<logic:iterate id="student" name="students">

<nested:root name="student">

<nested:nest property="schoolClass"><nested:write property="schoolClass"/></nested:nest>//寻找了student的schoolClass属性对象的schoolClass嵌套

<nested:write property="name"/>      //student的名字

<nested:link page="/adminActions.do?method=deleteStudent" paramId="id" paramProperty="id" onclick="return window.confirm('您真的要删除吗？')">删除</nested:link>

</nested:root>

这里是显示分页对象的：

第<bean:write name="page" property="current" />页
共<bean:write name="page" property="pages" />页
        //上一页是否存在
        <logic:equal name="page" property="previous" value="true">
               <html:link page="/adminUser.do?part=student&op=previous">
                <font color="6795b4">上一页</font>
               </html:link>&nbsp;&nbsp;  
        </logic:equal>
        <logic:notEqual name="page" property="previous" value="true">上一页&nbsp;&nbsp;  </logic:notEqual>
        
       //下一页是否存在
         <logic:equal name="page" property="next" value="true">
         <html:link page="/adminUser.do?part=student&op=next">
          <font color="6795b4">下一页</font>
         </html:link>&nbsp;&nbsp;  </logic:equal>
        <logic:notEqual name="page" property="next" value="true">下一页&nbsp;&nbsp;  </logic:notEqual>
        

共有<bean:write name="page" property="total" />条数据

</logic:iterate>

到这里不知道您看明白了多少，在我的这个JSP页里几乎没有任何的业务逻辑，这样的设计就比把HTML和JAVA搀杂在一起好了很多。



</pre><img src ="http://www.blogjava.net/xixidabao/aggbug/48310.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/xixidabao/" target="_blank">JAVA之路</a> 2006-05-26 13:48 <a href="http://www.blogjava.net/xixidabao/articles/48310.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>实现一个 Servlet 过滤器</title><link>http://www.blogjava.net/xixidabao/articles/41951.html</link><dc:creator>JAVA之路</dc:creator><author>JAVA之路</author><pubDate>Wed, 19 Apr 2006 08:48:00 GMT</pubDate><guid>http://www.blogjava.net/xixidabao/articles/41951.html</guid><description><![CDATA[
		<p>
				<em>
						<strong>
								<font color="#000000" size="5">实现一个 Servlet 过滤器</font>
						</strong>
				</em>
		</p>
		<p>
				<font color="#000000" size="4">
						<em>
								<strong>1. 编写实现类的程序</strong>
						</em>
				</font>
		</p>
		<p>
				<font color="#000000">过滤器 API 包含 3 个简单的接口（又是数字 3！），它们整洁地嵌套在 javax.servlet 包中。那 3 个接口分别是 Filter 、 FilterChain 和 FilterConfig 。从编程的角度看，过滤器类将实现 Filter 接口，然后使用这个过滤器类中的 FilterChain 和 FilterConfig 接口。该过滤器类的一个引用将传递给 FilterChain 对象，以允许过滤器把控制权传递给链中的下一个资源。 FilterConfig 对象将由容器提供给过滤器，以允许访问该过滤器的初始化数据。 </font>
		</p>
		<p>
				<font color="#000000">为了与我们的三步模式保持一致，过滤器必须运用三个方法，以便完全实现 Filter 接口： </font>
		</p>
		<p>
				<font color="#000000">init() ：这个方法在容器实例化过滤器时被调用，它主要设计用于使过滤器为处理做准备。该方法接受一个 FilterConfig 类型的对象作为输入。 </font>
		</p>
		<p>
				<font color="#000000">doFilter() ：与 servlet 拥有一个 service() 方法（这个方法又调用 doPost() 或者 doGet() ）来处理请求一样，过滤器拥有单个用于处理请求和响应的方法―― doFilter() 。这个方法接受三个输入参数：一个 ServletRequest 、 response 和一个 FilterChain 对象。 </font>
		</p>
		<p>
				<font color="#000000">destroy() ：正如您想像的那样，这个方法执行任何清理操作，这些操作可能需要在自动垃圾收集之前进行。 <br />清单 1 展示了一个非常简单的过滤器，它跟踪满足一个客户机的 Web 请求所花的大致时间。</font>
		</p>
		<p>
				<br />
				<font color="#000000" size="4">
						<em>
								<strong>清单 1. 一个过滤器类实现</strong>
						</em>
				</font>
		</p>
		<p>
				<br />
				<font color="#000000">import javax.servlet.*;<br />import java.util.*;<br />import java.io.*;</font>
		</p>
		<p>
				<font color="#000000">public class TimeTrackFilter implements Filter {<br />     private FilterConfig filterConfig = null;</font>
		</p>
		<p>
				<font color="#000000">     public void init(FilterConfig filterConfig)<br />        throws ServletException {</font>
		</p>
		<p>
				<font color="#000000">        this.filterConfig = filterConfig;<br />     }</font>
		</p>
		<p>
				<font color="#000000">     public void destroy() {</font>
		</p>
		<p>
				<font color="#000000">        this.filterConfig = null;<br />     }</font>
		</p>
		<p>
				<font color="#000000">     public void doFilter( ServletRequest request,<br />        ServletResponse response, FilterChain chain )<br />        throws IOException, ServletException {</font>
		</p>
		<p>
				<font color="#000000">        Date startTime, endTime;<br />        double totalTime;</font>
		</p>
		<p>
				<font color="#000000">        startTime = new Date();</font>
		</p>
		<p>
				<font color="#000000">        // Forward the request to the next resource in the chain<br />        chain.doFilter(request, wrapper);</font>
		</p>
		<p>
				<font color="#000000">        // -- Process the response -- \\</font>
		</p>
		<p>
				<font color="#000000">        // Calculate the difference between the start time and end time<br />        endTime = new Date();<br />        totalTime = endTime.getTime() - startTime.getTime();<br />        totalTime = totalTime / 1000; //Convert from milliseconds to seconds</font>
		</p>
		<p>
				<font color="#000000">        StringWriter sw = new StringWriter();<br />        PrintWriter writer = new PrintWriter(sw);</font>
		</p>
		<p>
				<font color="#000000">        writer.println();<br />        writer.println("===============");<br />        writer.println("Total elapsed time is: " + totalTime + " seconds." );<br />        writer.println("===============");</font>
		</p>
		<p>
				<font color="#000000">        // Log the resulting string<br />        writer.flush();<br />        filterConfig.getServletContext().<br />           log(sw.getBuffer().toString());</font>
		</p>
		<p>
				<font color="#000000">     }<br />}</font>
		</p>
<img src ="http://www.blogjava.net/xixidabao/aggbug/41951.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/xixidabao/" target="_blank">JAVA之路</a> 2006-04-19 16:48 <a href="http://www.blogjava.net/xixidabao/articles/41951.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>