SFD2008 in GuiZhou University Eddan

Tuesday May 26, 2009

public class ManageXML {
        Element rootElement=null;
  Document doc=null;
 /**
  * addContent()用于为元素添加内容。该内容包括一个节点的所有内容。
  * 本例演示了怎么样创建一个简单的xml文件。
  * XMLOutputter outer=new XMLOutputter();outer.output(doc, writer);把一个XML的doc文件存放到一个新建的writer文件
  */
 public static void main(String[] args) {
  ManageXML manage=new ManageXML();
  String[] books = {"1","2","3","4"};
  manage.createRootElement(books);
  manage.outputXML("e:/project/JDOM/1.xml");  
 }
 
  
  public void createRootElement ( String[] books ) {
   //create root element named books
   rootElement=new Element("books");
   //create comment
   Comment comment=new Comment("The sample class for Handling XML");
   //add comment
   rootElement.addContent(comment);
   for(int i=0;i<books.length;i++){
    //create element <book>
    Element book=new Element("book");
    //add book[i] -- book name
    book.addContent(books[i]);
    //create attribute named id
    Attribute id=new Attribute("id",new Integer(i).toString());
    //add id into element<book>,be care,used setAttribute method not addAttribute method
    book.setAttribute(id);
    rootElement.addContent(book);
   }
  }
  
  public void outputXML(String fileName){
   Document doc=new Document(rootElement);
   //create XML output Object
   XMLOutputter outer=new XMLOutputter();
   //create output format
   Format format=Format.getPrettyFormat();
   //输出格式的缩进字符为两个空格
   format.setIndent("  ");
   try {
    //因为输出内容有汉字,所以输出格式的字符编码为GB2312
    format.setEncoding("GB2312");
    //为XML输出对象指定输出格式
    outer.setFormat(format);
    //创建写文件对象
    FileWriter writer = new FileWriter(fileName);
    //将根节点输出到XML文档
    outer.output(doc, writer);
    writer.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  } 

}

运行后,在目标路径产生了一个以下的XML文档

<?xml version="1.0" encoding="GB2312"?>
<books>
  <!--The sample class for Handling XML-->
  <book id="0">1</book>
  <book id="1">2</book>
  <book id="2">3</book>
  <book id="3">4</book>
</books>

JDOM是Java中最常用的解析XML文档的方法。创始人为Jason Hunter,其集成了DOM解析的简单易用和SAX解析的性能优越两大优点。

package com.jdom.parse;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.JDOMException;
import org.jdom.input.*;
import org.jdom.output.*;
import java.io.IOException;
import java.util.List;

/*1、安装包:在http://www.jdom.org下下载jdom的压缩文件,解压后,在其build子文件夹下可得到解析XML文档所需的jar包 jdom.jar
 * 把它放到该项目的Build Path下。Document doc=null;SAXBuilder sax=new SAXBuilder(false);doc=sax.build(fileName);
 * 2、JDOM可以将整个XML文档转换为一个document对象,相当于XML文档根节点,这与XSLT中的document()函数类似。
 * 3、利用上面得到的document节点的getRootElement()方法,得到XML文档的根元素。
 * 4、根元素提供了getChildren("person")方法获得子节点。
 * 5、用getAttribute(String attributeName)获得属性,getAttributeValue(String attributeName)获得属性的值。
 */
public class XMLParser {
 //
    public static void main(String args[]){
  //建立XMLParser类实例
  XMLParser parser=new XMLParser();
  //调用输出方法
  parser.getPeopleInformation(parser.getRoot("E:/project/JDOM/NewFile.xml"));
 }
 public Element getRoot(String fileName){
  Document doc=null;
  //创建解析对象
  SAXBuilder sax=new SAXBuilder(false);
  try {
   //解析XML文档,建立节点树,并返回根节点
   doc=sax.build(fileName);
  } catch (JDOMException e) {
   e.printStackTrace();
  } catch (IOException ex){
   ex.printStackTrace();
  }
  
  //获得根元素
  Element root=doc.getRootElement();
  return root;
 }
 
 public void getPeopleInformation(Element root){
  //获得根元素下所有名为“person”的子节点,这些节点被存储在List中
  List list=root.getChildren("person");
  //对List中的节点进行循环处理
  for(int i=0;i<list.size();i++){
   Element person=(Element)list.get(i);
   String name=person.getChild("name").getText();
   String id=person.getAttributeValue("id");
   String age=person.getChild("age").getText();
   String dept=person.getChild("dept").getText();
   System.out.print("person:"+name);
   System.out.print(" id:"+id);
   System.out.print(" age:"+age);
   System.out.print(" dept:"+dept);
   System.out.println();
  }
  
 } 
 
}

原XML为:

<?xml version="1.0" encoding="UTF-8"?>
<people>
  <person id="001">
    <name>Jack</name>
    <age>25</age>
    <dept>Development</dept>
  </person>
  <person id="002">
    <name>Alex</name>
    <age>22</age>
    <dept>Management</dept>
  </person>
  <person id="003">
    <name>Martin</name>
    <age>25</age>
    <dept>Development</dept>
  </person>
  <person id="004">
    <name>Mike</name>
    <age>22</age>
    <dept>testing</dept>
  </person>
  <person id="005">
    <name>John</name>
    <age>23</age>
    <dept>Management</dept>
  </person>
  <person id="006">
    <name>Lina</name>
    <age>22</age>
    <dept>testing</dept>
  </person>
</people>

运行结果:

person:Jack id:001 age:25 dept:Development
person:Alex id:002 age:22 dept:Management
person:Martin id:003 age:25 dept:Development
person:Mike id:004 age:22 dept:testing
person:John id:005 age:23 dept:Management
person:Lina id:006 age:22 dept:testing

 

Reference:《XML数据标记、处理、共享与分析开发典型应用》  张朝明等编著  电子工业出版社

一下两篇日志均引用此书

Wednesday Apr 22, 2009

          There are some steps to use Spring label library.

          1、down load library:spring-form.tld,spring.tld.you can down these files from Spring official page:http://www.springsource.org/download,then put them under the direction of /WEB-INF.

          2、Configure lable lib 

          Write following configure into web.xml file bewteen element of <web-app> and </web-app>:

   <jsp-config>
        <taglib>
            <taglib-uri>/spring</taglib-uri>
            <taglib-location>/WEB-INF/spring.tld</taglib-location>
        </taglib>
        <taglib>
            <taglib-uri>/spring-form</taglib-uri>
            <taglib-location>/WEB-INF/spring-form.tld</taglib-location>
        </taglib>
    </jsp-config>

           3、configure Spring resource lib

           write following context into applicationContext.xml file.

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename">
            <value>com.demo.spring.resources.ApplicationResources</value>
        </property>
    </bean>

           u should pls pay attention to the value element .eg :com.demo.spring.resources.ApplicationResources,all your properties will be created under com.demo.spring.resources,and your properties will named begin as ApplicationResources,if you don't do as this rule ,IDE will show error message:No message found under code 'register.page.title' for locale 'zh_CN' when you run your project.

          4、configure resource files

         u can create ApplicationResources.properties,ApplicationResources_zh_CN.properties,ApplicationResources_en.properties under page com.demo.spring.resources.

       eg.ApplicationResources.properties file content:

#login.jsp
login.page.title=Login Window
login.page.username=Username
login.page.password=Password
login.page.login=Login
login.page.register=Register

#register.jsp
register.page.title=Register Window
register.page.username=Username
register.page.password1=Password
register.page.password2=Confirm Password
register.page.email=Email
register.page.register=Register
register.page.back=Back

#welcome.jsp
welcome.page.title=Login is successful!
welcome.page.username=Welcome,
welcome.page.logout=Logout

      Resource file's name have a format:"default resource file name"+"_country"+"_language.properties",default resource file name is the value u defined in applicationContext.xml ,such as ths eg we defined  is ApplicationResources

     5、label words in u jsp page

     eg.login.jsp

     firstly ,add <%@taglib prefix="spring" uri="/spring" %> into your jsp page,be careful,/spring is the direction u defined in web.xml as step 1.

    secondly,add label for jsp.as blowing:

    <form name="form1" action="login.do" method="POST">
            <table border="1" width="200">
                    <tr>
                        <td colspan="2"><spring:message code="login.page.title" /></td>
                    </tr>
                    <tr>
                        <td><spring:message code="login.page.username" /></td>
                        <td><input type="text" name="username" size="10"></td>
                    </tr>
                    <tr>
                        <td><spring:message code="login.page.password" /></td>
                        <td><input type="password" name="password" size="10"></td>
                    </tr>
                    <tr>
                        <td colspan="2"><input type="submit" name="submit" value='<spring:message code="login.page.login" />'>
                            <a href="register.do?method=init"><spring:message code="login.page.register" /></a>
                        </td>
                    </tr>
            </table>

           In this eg,i use <spring:message>label.There are also three labels:<spring:hasBindErrors>,<spring:bind>,<spring:transform> in lable library.

Reference:《开发者突击:java web主流框架整合开发 j2ee+Structs+Hibernate+Spring》 刘中兵编著  ,电子工业出版社

          There are some steps to use Spring label library.

          1、down load library:spring-form.tld,spring.tld.you can down these files from Spring official page:http://www.springsource.org/download,then put them under the direction of /WEB-INF.

          2、Configure lable lib 

          Write following configure into web.xml file bewteen element of <web-app> and </web-app>:

   <jsp-config>
        <taglib>
            <taglib-uri>/spring</taglib-uri>
            <taglib-location>/WEB-INF/spring.tld</taglib-location>
        </taglib>
        <taglib>
            <taglib-uri>/spring-form</taglib-uri>
            <taglib-location>/WEB-INF/spring-form.tld</taglib-location>
        </taglib>
    </jsp-config>

           3、configure Spring resource lib

           write following context into applicationContext.xml file.

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename">
            <value>com.demo.spring.resources.ApplicationResources</value>
        </property>
    </bean>

           u should pls pay attention of the value element .eg :com.demo.spring.resources.ApplicationResources,all your properties will be created under com.demo.spring.resources,and your properties will named begin as ApplicationResources,if you don't do as this rule ,IDE will show error message:No message found under code 'register.page.title' for locale 'zh_CN' when you run your project.

          4、configure resource files

         u can create ApplicationResources.properties,ApplicationResources_zh_CN.properties,ApplicationResources_en.properties under page com.demo.spring.resources.

       eg.ApplicationResources.properties file content:

#login.jsp
login.page.title=Login Window
login.page.username=Username
login.page.password=Password
login.page.login=Login
login.page.register=Register

#register.jsp
register.page.title=Register Window
register.page.username=Username
register.page.password1=Password
register.page.password2=Confirm Password
register.page.email=Email
register.page.register=Register
register.page.back=Back

#welcome.jsp
welcome.page.title=Login is successful!
welcome.page.username=Welcome,
welcome.page.logout=Logout

      Resource file's name have a format:"default resource file name"+"_country"+"_language.properties",default resource file name is the value u defined in applicationContext.xml ,such as ths eg we defined  is ApplicationResources

     5、label words in u jsp page

     eg.login.jsp

     firstly ,add <%@taglib prefix="spring" uri="/spring" %> in your jsp page,be careful,/spring is the direction u defined in web.xml as step 1.

    secondly,add label for jsp.as blowing:

    <form name="form1" action="login.do" method="POST">
            <table border="1" width="200">
                    <tr>
                        <td colspan="2"><spring:message code="login.page.title" /></td>
                    </tr>
                    <tr>
                        <td><spring:message code="login.page.username" /></td>
                        <td><input type="text" name="username" size="10"></td>
                    </tr>
                    <tr>
                        <td><spring:message code="login.page.password" /></td>
                        <td><input type="password" name="password" size="10"></td>
                    </tr>
                    <tr>
                        <td colspan="2"><input type="submit" name="submit" value='<spring:message code="login.page.login" />'>
                            <a href="register.do?method=init"><spring:message code="login.page.register" /></a>
                        </td>
                    </tr>
            </table>

           In this eg,i use <spring:message>label.There are also three labels:<spring:hasBindErrors>,<spring:bind>,<spring:transform> in lable library.

Reference:《开发者突击:java web主流框架整合开发 j2ee+Structs+Hibernate+Spring》 刘中兵编著  ,电子工业出版社

Friday Apr 17, 2009

    There is a good image which directly shows Spring Integration Model .

    

     Open netbeans,choose new "project--javaWeb",then click "next" twice,at the last step,select "Spring Web MVC" frame.Now,a simple spring frame has been built in your netbeans IDE.

     This time ,i practise to develop a login demo.First of all , build a jsp page named login.jsp and write following code in this page.

    <body>
        <form name="form1" action="login.do" method="POST">
            <table border="1" width="200">
                    <tr>
                        <td colspan="2">登录窗口</td>
                    </tr>
                    <tr>
                        <td>用户名</td>
                        <td><input type="text" name="username" size="10"></td>
                    </tr>
                    <tr>
                        <td>密码</td>
                        <td><input type="password" name="password" size="10"></td>
                    </tr>
                    <tr>
                        <td colspan="2"><input type="submit" name="submit" value="登录"><a href="register.do?method=init">注册新用户</a></td>
                    </tr>
            </table>

        </form>
    </body>

   besides,create a form class which is a orginal JavaBean class and contains relative variable  of  login.jsp.

public class LoginForm {
    private String username;
    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    } 
}

     For the more,create a new login control named LoginAction.java .

 protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,Object command,BindException errors) throws Exception{
        LoginForm loginForm=(LoginForm)command;

        if(isValid(loginForm)){
            request.getSession().setAttribute(Constants.USERNAME_KEY,loginForm.getUsername());
            return new ModelAndView(getSuccessView());
        }else{
            Map modle=errors.getModel();
            modle.put("loginForm", loginForm);
            return new ModelAndView(getFormView(),modle);
        }
    }

    private boolean isValid(LoginForm loginForm) {
        if(loginForm.getUsername().equals("admin") || loginForm.getPassword().equals("admin")){
            return true;
        }else{
            return false;
        }
    }

 At last,configure controller mapping and controller.

   controller mapping

<bean id="loginMapping"
    class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/login.do">loginAction</prop>
            </props>
        </property>
    </bean>

controller

    <bean id="loginAction"
    class="com.demo.spring.actions.LoginAction">
        <property name="commandClass">
            <value>com.demo.spring.forms.LoginForm</value>
        </property>
        <!-- return the failure page -->
        <property name="formView">
            <value>login</value>
        </property>
        <!--return the success page-->
        <property name="successView">
            <value>welcome</value>
        </property>
    </bean>

    Enjoy your spring tour~~

   Reference:

http://www.ibm.com/developerworks/cn/java/wa-spring1/spring_framework.gif

《开发者突击:java web主流框架整合开发 j2ee+Structs+Hibernate+Spring》 刘中兵编著  ,电子工业出版社