SoFunction
Updated on 2025-03-11

An example of development using JSP + JAVABEAN + XML

This example refers to some websites related documents about JSP’s operations on XML, and combines some personal experiences. The example involves the content of some codes on the backend management end of an internal ordering system developed by an enterprise, and the functions are mainly focused on the management of basic restaurant information.

The reason for the development of the example itself was part of a joke I had with my colleagues at the original company. I hereby express my miss for those friends I work with.

The example itself is a program with a B/S structure running under the TOMCAT4.01 platform. The configuration of TOMCAT will not be explained here. Only explain the directory structure of relevant files and folders.

Directory structure description:
/tomcat/webapps/canyin/
/tomcat/webapps/canyin/jsp/                  ----JSP File Directory
/tomcat/webapps/canyin/jsp/admin/         ----The directory for storage of JSP files that implement background management
/tomcat/webapps/canyin/WEB-INF/classes/canyin/                                                  �
/tomcat/webapps/canyin/data/   ----xml File storage directory
/tomcat/webapps/ROOT/           ---tomcat Store file storage folder, only files are stored

Document brief description:
/tomcat/webapps/canyin/data/    ---Record user information
/tomcat/webapps/canyin/data/  ---Record basic information of restaurants


/tomcat/webapps/ROOT/        ----Home page, the input box appears on the page, requiring the user to enter the user name and password


/tomcat/webapps/canyin/jsp/        ----User identity judgment page determines whether the page will be transferred to the backend management end or the frontend client based on the user name and password. In this example, once the user's identity is confirmed to have management permissions, he can enter the backend management end and jump directly to the restaurant's basic information management page to simplify the explanation process.
/tomcat/webapps/canyin/jsp/admin/admin_rest.jsp   -----Basic Restaurant Information Management Page, manages restaurant name, phone number, address and other information, etc.

/tomcat/webapps/canyin/WEB-INF/classes/canyin/  --- The backend management side detects the value of session that marks the user's identity. If you are not an administrator, jump back to the login page.
/tomcat/webapps/canyin/WEB-INF/classes/canyin/  ---Connect the xml file
/tomcat/webapps/canyin/WEB-INF/classes/canyin/  ---Write to the xml file

Detailed description of the document and accompanying code description.

/tomcat/webapps/canyin/data/    

Code:
  <?xml version="1.0" encoding="UTF-8" ?> 

- <users>
  <user name="joard" password="joard" roles="admin" /> 
  <user name="joard01" password="joard01" roles="user" /> 
  <user name="joard02" password="joard02" roles="user" /> 
  </users>

Description: The field means the user name, password and user identity

/tomcat/webapps/canyin/data/  

Code:
  <?xml version="1.0" encoding="UTF-8" ?> 
- <restaurants num="10">
- <restaurant >
<name>Shanghai Ting Fast Food Restaurant</name>
  <phone>021-76546726</phone> 
<address>Broadway Plaza Block B</address>
  </restaurant>
- <restaurant >
<name>Shangri-La Hotel</name>
  <phone>021-2312134</phone> 
<address>No. 1023 Nanjing Road</address>
  </restaurant>
  </restaurants>
Note: The <num> attribute is the number of records recorded in the file. For each new one, regardless of whether it is deleted later, the value will be increased by 1, just like the id item that is used in the database that automatically increases by 1. Used to assign a unique value to the newly added <restaurant> attribute <id>. The meaning of other fields is more obvious.
/tomcat/webapps/ROOT/

Code:
<html>
<head>
<title>oddWorld Catering System</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>

<body onload="javascript:()">
<div align="center">
  <table width="100%" border="0" cellspacing="0" cellpadding="0" height="22">
    <tr> 
      <td width="1"><img src="images/top_r1.GIF" width="62" height="22"></td>
<td width=150 align="center"> Career System Login </td>
      <td><img src="images/top_r2.GIF" width="294" height="22"></td>
    </tr>
  </table>
  <br>
  <br>
  <table width="300" border="0" cellspacing="1" cellpadding="0" >
    <tr> 
    <td height="200" valign="top" align="center"> 
      <p align="center">
        <table width="100%" border="0" cellspacing="1" cellpadding="5" bgcolor=#999999 class=a9px>
          <tr> 
<td bgcolor="#efefefef">Career System Login</td>
        </tr>
        <tr> 
            <td bgcolor="#FFFFFF" valign="top" align="center"> 
              <table width="100%" border="0" cellspacing="0" cellpadding="0">
                <form name=dataform method=post action=''canyin/jsp/''>
                  <tr> 
<td width="100"><b>Login:</b></td>
                    <td> 
                      <input maxlength=16 
              name="username" class=stedit value="joard">
                    </td>
                  </tr>
                  <tr>
<td width="100"><b>Password:</b></td>
                    <td>
                      <input  class=stedit  maxlength=16 
                  name="userpass" type=password value="oddworld">
                    </td>
                  </tr>
                </form>
              </table>
            <br>
              <table border=0 cellpadding=0 cellspacing=0>
                <tbody> 
                <tr> 
                  <td> 
<input  class=stbtm  name=update onClick="javascript:if (checkform()==false);" type=button value="Login       Record">
                  </td>
                  <td> </td>
                  <td> 
<input class=stbtm name=Submit onClick="javascript:=''?myjoke=1'';" type=button value="Modify Password">
                  </td>
                  <td> </td>
                </tr>
                </tbody> 
              </table>
              <br>
            </td>
        </tr>
      </table>
    </td>
  </tr>
</table>
</div>
</body>
</html>
     <SCRIPT language=javascript>
<!--
function checkform()

 var Checkblank = /^(\s*|(\ )|(\.))*$/;
 if (())    
{
alert("Login name cannot be empty!");
   return false; 
         } 

         if (())    
{
alert("The password cannot be empty!");
   return false; 
         } 


      ();

   }
-->

</SCRIPT>

Note: Submit the user name and user password to /tomcat/webapps/canyin/jsp/

/tomcat/webapps/canyin/WEB-INF/classes/canyin/  (The code is the corresponding java file)

package canyin;

import ;
import ;

public class checkSessionBean {

 private boolean bolCheckPass=false;
 private HttpServletRequest request = null;

 public boolean checkSessionBean(HttpServletRequest request,String strSessionName,String strCheckValue){
   public boolean checkSessionBean(HttpServletRequest request){
  HttpSession session = (false);
  return(bolCheckPass);

  if (strSessionName==null || strCheckValue==null){
   return(bolCheckPass);
  }else{
   if (session!=null && (strSessionName)!=null){
    bolCheckPass=(strSessionName).equals(strCheckValue);
   }

     return(bolCheckPass);
  }
 }
}

Description: Check whether the value of the session name passed in the parameter and the value of the field passed in the parameter are equal.

/tomcat/webapps/canyin/WEB-INF/classes/canyin/  

Code:
package canyin;

import .*;
import .*;
import ;
import ;
import org..*;

public class connXmlBean {

 private DocumentBuilderFactory factory=null;
 private DocumentBuilder builder=null;
 private Document doc=null;

 public connXmlBean(){}

 public String connXml(String xmlFileName){

  String strExc="";

  try{
   factory = ();
       builder=();
       doc=(xmlFileName);
       (); 
      }catch(Exception e){
       strExc=();
    }

    return(strExc);
 }

 public Document getXmlDoc(){
    return(doc);
 }
}

Description: Open a specified xml file

/tomcat/webapps/canyin/WEB-INF/classes/canyin/  

Code:
package canyin;

import .*;
import .*;
import ;
import ;
import ;
import org..*;

public class writeXmlBean {

 public writeXmlBean(){}

 public String writeXml(Document doc,String xmlFileName){

  String strExc="";

  try{
   TransformerFactory tfactory = (); 
   Transformer transformer = (); 

   DOMSource source = new DOMSource(doc); 

   StreamResult result = new StreamResult(new File(xmlFileName)); 

   (source,result);  
      }catch(Exception e){
       strExc=();
    }

    return(strExc);
 }

}

Description: Write the contents of dom to a specified xml file.

/tomcat/webapps/canyin/jsp/       

Code:
<%--  oddWorld Career Management System (Simplified Chinese Version) December 1, 2002
 copy right by joard ast  

Function: User identity verification, different identities of users marked in /data/ file
Decided to transfer to the backend management page or to the customer order page.
 --%>

<%@ page contentType="text/html;charset=gb2312" %>
<%@ page language="java" import=".*" %>
<%@ page import="org..*" %>
<%@ page import="canyin.*" %> 

<jsp:useBean  class="" scope="page" />

<%
(1800);


Document doc;
NodeList users;
String strExc="";
String strUsername,strPassword;

strUsername=(String)("username");
strPassword=(String)("userpass");

//Check whether the data is empty
if (strUsername=="" || strPassword=="" ){
 ("<script language=''javascript''>");
("alert(''The username or password has a null value!'');");
 ("=''/'';");
 ("</script>");
 return;
}

("webapps/canyin/data/");
doc=();

try{
 users =("user");

     for (int i=0;i<();i++){
        Element user=(Element) (i);

  String strAtrNameValue=("name").getNodeValue();       
 String strAtrPassWordValue=("password").getNodeValue();
        String strAtrRoleValue=("roles").getNodeValue(); 

       

        if ((strUsername) && (strPassword)){

         if (("admin")){
          ("<script language=''javascript''>");
("alert(''Welcome to administrators to log in to the system!'');");
    ("</script>");

//Set the session (sesUserRole) that indicates the user's identity, and the administrator's identity is admin
    ("sesUserRole","admin");

//Skip to the management page
    ("admin/admin_rest.jsp");
    return;

         }else{
//Set the session (sesUserRole) that marks the user's identity, and the administrator's identity is user
          ("sesUserRole","user");

//Skip to the ordinary user page
          ("");       
          return;
         }

        }else{
         ("<script language=''javascript''>");
("alert(''error username or password is wrong!'');");
   ("(-1);");
   ("</script>");
   return;
        }

 }
}catch(Exception e){
     strExc=();
}
%>
illustrate:.......

/tomcat/webapps/canyin/jsp/admin/admin_rest.jsp    

Code:
<%--  oddWorld Career Management System (Simplified Chinese Version) December 1, 2002
 copy right by joard ast  

admin_rest.jsp Function: Backend management page, Restaurant management page.
 --%>

<%@ page contentType="text/html;charset=gb2312" %>
<%@ page language="java" import=".*" %>
<%@ page import=".*" %>
<%@ page import="org..*" %>
<%@ page import="canyin.*" %> 

<%@ include file="../../include/sys_dialog.jsp" %>

<jsp:useBean  class="" scope="page" />
<jsp:useBean  class="" scope="page" />
<jsp:useBean  class="" scope="page" />

<%//Check the user's identity and determine whether he is an administrator
if(!(request,"sesUserRole","admin")){
(showDialog("You do not have permission to manage!","/"));
 return;
}

//Get relevant data from restaurant information files
Document doc;
NodeList restaurants;

String strAct;
int intId=0;
String strOperation="show";

//Accept external incoming parameters
strAct=(String)("act");

("webapps/canyin/data/");
doc=();
restaurants =("restaurant");

//Decide the operation of the file based on the parameters passed from outside
if (strAct!=null){
 if(("addnewDo")){

  String strName;
  String strPhone;
  String strAddress;
  Text textseg;

  strName=(String)("name").trim();
  strPhone=(String)("phone").trim();
  strAddress=(String)("address").trim();

//Data verification
  if(strName==null){
(showDialog("The restaurant name cannot be empty!"));
   return;
  }
  if(strPhone==null){
(showDialog("The restaurant phone cannot be empty!"));
   return;
  }
  /*if(strAddress==null){
(showDialog("The restaurant address cannot be empty!"));
   return;
  }*/

//Check the uniqueness of the data
  for(int i=0;i<();i++){
   Element restaurant=(Element) (i);
   if(((String)("name").item(0).getFirstChild().getNodeValue()).equals(strName)){
(showDialog("Double restaurant name!"));
    return; 
   }else{
    if(((String)("name").item(0).getFirstChild().getNodeValue()).equals(strPhone)){
(showDialog("Repeat restaurant phone!"));
     return;
    }
   }

  }

  

//Get the existing records and set a unique incremental id attribute for the newly added restaurant records.
  int intNum=0;
  Element restNum=(Element)("restaurants").item(0);
  intNum=(("num").getNodeValue()); 

  intNum+=1;

//Add 1 to the value of the restaurants attribute num
  ("num").setNodeValue((intNum));

//Add a new node
  Element newRestaurant=("restaurant");

  Attr newArrId=("id");
  //Attribute newArrId = new Attribute("id",(intNum));  
  textseg=((intNum));
  ((intNum));
  (newArrId);

  Element newName=("name");
  textseg=(strName);
  (textseg);
  (newName);

  Element newPhone=("phone");
  textseg=(strPhone);
  (textseg);
  (newPhone);

  Element newAddress=("address");
  textseg=(strAddress);
  (textseg);
  (newAddress);

  ().appendChild(newRestaurant);

//Calling bean to write the corresponding xml file
  (doc,"webapps/canyin/data/");

  (());  
  return;
 }
 if(("modiDo")){
  String strName;
  String strPhone;
  String strAddress;
  Text textseg;
  int modiId;
//Record which item of item(i) is the record to be modified
  int intI=0;

  strName=(String)("name").trim();
  strPhone=(String)("phone").trim();
  strAddress=(String)("address").trim();
  modiId=(("recordId").trim());

//Data verification
  if(strName==null){
(showDialog("The restaurant name cannot be empty!"));
   return;
  }
  if(strPhone==null){
(showDialog("The restaurant phone cannot be empty!"));
   return;
  }
  if(modiId==0){
(showDialog("You want to modify the restaurant record does not exist!"));
   return;
  }
  /*if(strAddress==null){
(showDialog("The restaurant address cannot be empty!"));
   return;
  }*/

//The flag display record exists
  boolean recordExist=false;

//Check the uniqueness of the data
  for(int i=0;i<();i++){
   Element restaurant=(Element) (i);

   if((("id").getNodeValue())==modiId){
    recordExist=true;
    intI=i;

   }

   if(((String)("name").item(0).getFirstChild().getNodeValue()).equals(strName) && (("id").getNodeValue())!=modiId ){
(showDialog("Double restaurant name!"));
    return; 
   }else{
    if(((String)("name").item(0).getFirstChild().getNodeValue()).equals(strPhone) && (("id").getNodeValue())!=modiId ){
(showDialog("Repeat restaurant phone!"));
     return;
    }
   }

  }



  if(!recordExist){
(showDialog("You want to modify the restaurant record does not exist!"));
   return;
  }else{
//Perform the operation of recording changes
   try{
    Element modiRestaurant=(Element) (intI);
    ("name").item(0).getFirstChild().setNodeValue(strName);
    ("phone").item(0).getFirstChild().setNodeValue(strPhone);
    ("address").item(0).getFirstChild().setNodeValue(strAddress);

//Calling bean to write to the corresponding xml file
    (doc,"webapps/canyin/data/");

    (());  
    return; 

   }catch(Exception e){}
  }
 }
//Document
 if(("del")){
  int delId;
//Record which item of item(i) is the record to be modified
  int intI=0;

  delId=(("recordId").trim());

  if(delId==0){
(showDialog("You want to modify the restaurant record does not exist!"));
   return;
  }

file://flag display record exists
  boolean recordExist=false;

//Check the uniqueness of the data
  for(int i=0;i<();i++){
   Element restaurant=(Element) (i);

   if((("id").getNodeValue())==delId){
    recordExist=true;
    intI=i;

   }
  }

  if(!recordExist){
(showDialog("The record you want to delete the restaurant does not exist!"));
   return;
  }else{
//Check the record and delete operation
   try{
    Node delNode=(Node)(intI);

    ("restaurants").item(0).removeChild(delNode);

//Calling bean to write to the corresponding xml file
    (doc,"webapps/canyin/data/");

    (());  
    return; 

   }catch(Exception e){}
  }

 }
}

//The corresponding processing status of the page is determined by external incoming parameters
if (strAct==null){
 strOperation="show";
}else{
 if (("modi")){
  strOperation="modi";
  intId=(("recordId"));
 }else{
  if(("addnew")){
   strOperation="addnew";
  }else{
   strOperation="show";
  }
 }
}


//If it is empty, change the page status to "Add"
if (()==0){
 strOperation="addnew";
}
%>

<html>
<head>
<title>oddWorld Catering System</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<meta http-equiv="expires" content="0">
<link rel="stylesheet" href="../../include/" type="text/css">
</head>

<body >
<div align="center">
  <table width="100%" border="0" cellspacing="0" cellpadding="0" height="22">
    <tr> 
      <td width="1"><img src="../../images/top_r1.GIF" width="62" height="22"></td>
<td width=150 align="center"> Career System Management--Restaurant Management</td>
      <td><img src="../../images/top_r2.GIF" width="294" height="22"></td>
<td width=100 align="center"><a href="/">[ Exit the system ]</a></td>
    </tr>
  </table>
  <br>
  <br>
  <table bgcolor="#999999" align=center border=0 cellpadding=1 cellspacing=1 
width="90%">
    <tbody> 
    <tr bgcolor="#efefef" align="center" valign="middle"> 
      <td class=ttTable height=30 width="20"> </td>
<td class=ttTable height=30 width="0">Restaurant Name</td>
<td class=ttTable height=30 width="0">Restaurant phone number</td>
      <td class=ttTable height=30 width="0"> 
<div align="center">restaurant address</div>
      </td>
      <td class=ttTable height=30 width="30"> 
<div align="center">Modify</div>
      </td>
      <td class=ttTable height=30 width="30"> 
<div align="center">Delete</div>
      </td>
    </tr>
<%
 for(int i=0;i<();i++)
 {
  Element restaurant=(Element) (i);

  if (strOperation=="modi" && (("id").getNodeValue())==intId){
%>
<%//Show modified format %>
    <tr align="center" bgcolor="#ffffff" valign="middle"> 
      <form name=dataform action="<%=()%>?act=modiDo" method="post"  onSubmit=''return checkform(this);'' >
        <td class=tdsmall height=25 width="20"> 
          <input type="hidden" name="recordId" value="<%=("id").getNodeValue()%>">
          <%=(i+1)%></td>
        <td class=tdsmall height=25> 
          <input name="name" class=stedit
                  style="HEIGHT: 22px; WIDTH: 150px" value="<%if(("name").item(0).hasChildNodes()){
         (("name").item(0).getFirstChild().getNodeValue());

        }%>
" maxlength="40" >
        </td>
        <td class=tdsmall height=25> 
          <input name="phone" class=stedit
                  style="HEIGHT: 22px; WIDTH: 100px" value="<%if(("phone").item(0).hasChildNodes()){
         (("phone").item(0).getFirstChild().getNodeValue());

        }%>" maxlength="20" >
        </td>
        <td class=tdsmall height=25> 
          <input name="address" class=stedit
                  style="HEIGHT: 22px; WIDTH: 200px" value="<%

                  if(("address").item(0).hasChildNodes()){
         (("address").item(0).getFirstChild().getNodeValue());

        }%>" maxlength="100" >
        </td>
        <td class=tdsmall height=25 width="25"><a href="javascript:if (checkform()==false);"><img border=0 
      height=15 src="../../images/" width=15></a></td>
        <td class=tdsmall height=25 width="25"> </td>
      </form>
    </tr>
    <% }else{ 
//Show normal format %>
    <tr align="center" bgcolor="#ffffff" valign="middle"> 
      <td class=tdsmall height=25 width="20"><%=(i+1)%></td>
      <td class=tdsmall height=25 width="0"><%if(("name").item(0).hasChildNodes()){
         (("name").item(0).getFirstChild().getNodeValue());

        }%>
</td>
      <td class=tdsmall height=25 width="0"><%if(("phone").item(0).hasChildNodes()){
         (("phone").item(0).getFirstChild().getNodeValue());

        }%></td>
      <td class=tdsmall height=25 width="0"> 
        <%
        if(("address").item(0).hasChildNodes()){
        (("address").item(0).getFirstChild().getNodeValue());

        }%>
      </td>
      <td class=tdsmall height=25 width="30"><a href="<%=()%>?act=modi&recordId=<%=("id").getNodeValue()%>"><img border=0 
        height=15 src="../../images/" width=15></a></td>
      <td class=tdsmall height=25 width="30"><img border=0 
        height=15 
onClick="javascript:if(confirm(''Are you sure that this record is deleted, and after deletion, it will be imported to the record that cannot be used?'')){=''<%=()%>?act=del&recordId=<%=("id").getNodeValue()%>'';}"
        src="../../images/" style="CURSOR: hand" width=15> </td>
    </tr>
    <% } 
}%>
    <% if (strOperation=="addnew"){
//Show new format %>
    <tr align="center" bgcolor="#ffffff" valign="middle"> 
      <form name=dataform2 action="<%=()%>?act=addnewDo" method="post"  onSubmit=''return checkform2(this);'' >
        <td class=tdsmall height=25 width="20"></td>
        <td class=tdsmall height=25> 
          <input name="name" class=stedit
                  style="HEIGHT: 22px; WIDTH: 150px" value="" maxlength="40" >
        </td>
        <td class=tdsmall height=25> 
          <input name="phone" class=stedit
                  style="HEIGHT: 22px; WIDTH: 100px" value="" maxlength="20" >
        </td>
        <td class=tdsmall height=25> 
          <input name="address" class=stedit
                  style="HEIGHT: 22px; WIDTH: 200px" value="" maxlength="100" >
        </td>
        <td class=tdsmall height=25 width="25"><a href="javascript:if (checkform2()==false);"><img border=0 
      height=15 src="../../images/" width=15></a></td>
        <td class=tdsmall height=25 width="25"> </td>
      </form>
    </tr>
    <% } %>
    </tbody> 
  </table>
  <br>
  <table align=center border=0 cellpadding=0 cellspacing=2 width="95%">
    <tbody> 
    <tr valign=center> 
      <td align=middle> <br>
        <table border=0 cellpadding=0 cellspacing=0>
          <tr>
            <td> 
              <% if (strOperation=="addnew"){
              %>
<input class=stbtm name=update onClick="javascript:if (checkform2()==false);" type=button value="Update Record">
              <% }else{
                if(strOperation=="modi"){
              %>
<input class=stbtm name=update onClick="javascript:if (checkform()==false);" type=button value="Update Record">
              <% 
                }else{
                 %>
<input class=stbtm type="button" name="Button" value="new add" onClick="javascript:=''<%=()%>?act=addnew'';"><%
                } 
               } %>
               </td>
            <td>
<input class=stbtm type="button" name="Button" value="return" onClick="javascript:='''';">
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
  <p> </p>
</div>
</body>
</html>
<SCRIPT LANGUAGE=javascript>
<!--
function checkform2()
{
 var Checkblank = /^(\s*|(\ )|(\.))*$/;

  if (())
 {
alert("The restaurant name cannot be empty!");
          ();
   return false; 
         } 

  if (())    
 {
alert("The restaurant phone cannot be empty!");
          ();
   return false; 
         }
         window.();
  }

  function checkform()
{  
 var Checkblank = /^(\s*|(\ )|(\.))*$/;
 if (())
 {
alert("The restaurant name cannot be empty!");
          ();
   return false; 
         }

         if (())
 {
alert("The restaurant phone cannot be empty!");
          ();
   return false; 
         }


         ();
  }
-->
</SCRIPT>
Note: There are many things in writing this document that are not concise, because during the development of the program, excessively concise programs often bring difficulties in later maintenance.

Development experience:

("restaurants").item(int i) returns the value of node. If it is not called its property value, there is no need to force the transformation to Element type. Can be operated directly. Due to the errors in the development reference materials, this system has adopted forced transformation. You can consider using node in future development and operate directly.

Neither trim() nor  () function can accept null values

The files on the left and right under tomcat are all directories calculated from TOMCAT. For details, please refer to the writing method of the xml path in \webapps\canyin\jsp\.


Friends who are interested in the original code, please contact me through the following mailbox, joard@