为了和学习javaEE技术的朋友们一起交流,一起分享学习,我刚刚写了一个用struts2+hibernate3实现的简单购物车程序,觉得还可以,所以传上来供大家交流交流,此程序还在完善中

如下:
我用的数据库是mysql数据库
register.sql

 create table user
(
  uid varchar(32) not null primary key,
  username varchar(40)  unique,
  password varchar(40)  ,
  age int
);
create table product
(
  pid varchar(32) ,
  productname varchar(40),
  productcount int ,
  allprice int,
  uid varchar(32),
  foreign key (uid) references user(uid) on delete cascade
);
hibernate.cfg.xml
 <?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
    <property name="connection.username">root</property>
    <property name="connection.url">
        jdbc:mysql://localhost:3306/netshop
    </property>
    <property name="dialect">
        org.hibernate.dialect.MySQLDialect
    </property>
    <property name="myeclipse.connection.profile">
        org.gjt.mm.mysql.Driver
    </property>
    <property name="connection.password">1234</property>
    <property name="connection.driver_class">
        org.gjt.mm.mysql.Driver
    </property>
    <property name="show_sql">true</property>
    <mapping resource="figo/register/dao/User.hbm.xml" />
    <mapping resource="figo/register/dao/Product.hbm.xml" />

</session-factory>

</hibernate-configuration>
struts.xml
 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
   <struts>
           
           
           <package name="struts2" extends="struts-default">
               <action name="register" class="figo.action.RegisterAction">
                   <result name="input">/register.jsp</result>
                   <result name="success">/registerSuccess.jsp</result>
               </action>
               
               <action name="login" class="figo.action.LoginAction">
                   <result name="input">/login.jsp</result>
                   <result name="success">/loginSuccess.jsp</result>
               </action>
               
               <action name="shop" class="figo.action.ShopAction">
                   <result name="success">/shopSuccess.jsp</result>
               </action>
           </package>
   </struts>

在package figo包下
LoginAction.java
 package figo.action;

import com.opensymphony.xwork2.ActionSupport;

import figo.register.dao.User;
import figo.register.dao.UserOperation;

public class LoginAction extends ActionSupport {

    private String username;
    
    private String password;

    public String getUsername() {
        return username;
    }

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

    public String getPassword() {
        return password;
    }

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

    @Override
    public String execute() throws Exception {
        String result=check();
        
        return result;
    }

    @Override
    public void validate() {
        if(this.username.length()>12 ||this.username.length()<5)
        {
            this.addFieldError("username", "用户名长度必须为5到12之间");
            
        }
        if(this.password.length()>12 ||this.username.length()<5)
        {
            this.addFieldError("password", "密码长度必须在5到12之间");
        }
    }
    public String check()
    {
        UserOperation op = new UserOperation();
        User user = op.QueryByUsername(username);
        if(user == null)
        {
            this.addFieldError("username", "用户名不存在");
            return "input";
        }
        String usernameDao = user.getUsername();
        
        String passwordDao = user.getPassword();
        if(!(passwordDao.equals(this.password)))
        {
            this.addFieldError("password", "密码错误");
            return this.INPUT;
            
        }
        return this.SUCCESS;
    
    }
}


RegisterAction.java
 package figo.action;

import java.util.HashSet;

import com.opensymphony.xwork2.ActionSupport;

import figo.register.dao.Product;
import figo.register.dao.User;
import figo.register.dao.UserOperation;

public class RegisterAction extends ActionSupport {

    
    
    private String username;
    
    private String password;
    
    private String repassword;
    
    private int age;

    public String getUsername() {
        return username;
    }

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

    public String getPassword() {
        return password;
    }

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

    public String getRepassword() {
        return repassword;
    }

    public void setRepassword(String repassword) {
        this.repassword = repassword;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
    
        Persistence();
        return this.SUCCESS;
    }

    @Override
    public void validate() {
        if(!(this.password.equals(this.repassword)))
        {
            this.addFieldError("password", "两次密码必须匹配");
        }
    }
    public void Persistence()
    {
        User user = new User();
        UserOperation op = new UserOperation();
        user.setAge(age);
        user.setPassword(password);
        user.setUsername(username);
        
        Product product = null;
        user.setProduct(new HashSet());
        
        product.setUser(user);
        user.getProduct().add(product);
        op.save(user);
    }
    
        
    
    
}

ShopAction.java
 package figo.action;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import figo.register.dao.Product;
import figo.register.dao.User;
import figo.register.dao.UserOperation;
public class ShopAction extends ActionSupport{

    private String productname;
    
    private int productcount;
    
    private int allprice;
    
    
    
    public String pid;
    public String getProductname() {
        return productname;
    }

    public void setProductname(String productname) {
        this.productname = productname;
    }

    public int getProductcount() {
        return productcount;
    }

    public void setProductcount(int productcount) {
        this.productcount = productcount;
    }

    public int getAllprice() {
        return allprice;
    }

    public void setAllprice(int allprice) {
        this.allprice = allprice;
    }
    
    public String getPid() {
        return pid;
    }

    public void setPid(String pid) {
        this.pid = pid;
    }


    

    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        
        
        Persitence();
        return this.SUCCESS;
    }
    public void Persitence()
    {
        //获得session对象和
        HttpServletRequest request = (HttpServletRequest)ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_REQUEST);
        HttpSession session = request.getSession();
        String username = (String)session.getAttribute("username");
        
        
        UserOperation op = new UserOperation();
        User user = new User();
        user = op.QueryByUsername(username);
        
            Iterator it = user.getProduct().iterator();
        
            while(it.hasNext())
            {
                Product p =(Product)it.next();
                System.out.println("______--___");
                System.out.println(this.pid);
                System.out.println(p.getPid());
                System.out.println(p.getPid().equals( this.pid));
                if(p.getPid().equals( this.pid))
                {
                    System.out.println(p.getPid());
                    System.out.println(this.pid);
                    System.out.println(p.getPid()==this.pid);
                    System.out.println("。。。。。。。。。。。");                
                    p.setAllprice(p.getAllprice()+allprice);
                    p.setProductcount(p.getProductcount()+1);
                    p.setPid(pid);
                    p.setUser(user);
                    op.update(p);
                    return;
                }
            
            
        }
        
        
        Product product = new Product();        
        product.setAllprice(allprice);
        product.setProductname(productname);
        product.setProductcount(productcount);
        product.setUser(user);
        product.setPid(pid);
        System.out.println("!!!!!!!!!");
        op.save(product);
        
        
        
        
        
        
    }

    
    

    
}


RegisterAction.properties
 invalid.fieldvalue.age=Age Conversion Error!

RegisterAction-validation.xml
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.dtd">
    <validators>
        <field name="username">
            <field-validator type="requiredstring">
                <param name="trim">true</param>
                <message>用户名不能为空</message>
            </field-validator>
            <field-validator type="stringlength">
                <param name="maxLength">10</param>
                <param name="minLength">5</param>
                <message>用户名长度必须在5到10之间</message>
            </field-validator>
        </field>        
        
        <field name="password">
            <field-validator type="requiredstring">
                <message>密码不能为空!</message>
            </field-validator>
            
            <field-validator type="stringlength">
                <param name="maxLength">10</param>
                <param name="minLength">5</param>
                <message>密码长度必须在5到10之间</message>
            </field-validator>
        </field>
    
      <field name="repassword">
            <field-validator type="requiredstring">
                <message>再次密码不能为空</message>
            </field-validator>
            
            <field-validator type="stringlength">
                <param name="minLength">5</param>
                <param name="maxLength">10</param>                
                <message>密码长度必须在5到10之间</message>
            </field-validator>
        </field>
        
        <field name="age">
            <field-validator type="int">
                <param name="min">1</param>
                <param name="max">150</param>                
                <message>年龄必须在1到150之间</message>
            </field-validator>
        </field>
    </validators>    


figo.action包就这些内容

下面进入另外一个包中
figo.register.dao
这个包是用hibernate3处理后台
User.java
 package figo.register.dao;

import java.util.Set;

public class User {

    private String uid;
    
    private String username;
    
    private String password;
    
    private int age;
    
    private Set product;

    public Set getProduct() {
        return product;
    }

    public void setProduct(Set product) {
        this.product = product;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

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

    public String getPassword() {
        return password;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
}


User.hbm.xml
 <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="figo.register.dao.User" table="user" catalog="netshop">
        <id name="uid" type="java.lang.String">
            <column name="uid" length="32" />
            <generator class="uuid.hex"></generator>
        </id>
        <property name="username" type="java.lang.String">
            <column name="username" length="40" unique="true" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="password" length="40" />
        </property>
        <property name="age" type="java.lang.Integer">
            <column name="age" />
        </property>
        <set name="product" table="product" inverse="true" cascade="all">
            <key>
                <column name="uid" length="32" />
            </key>
            <one-to-many class="figo.register.dao.Product" />
        </set>
    </class>
</hibernate-mapping>


Product.java
 package figo.register.dao;

public class Product {

    private String pid;
    
    private String productname;
    
    private int productcount;
    
    private int allprice;
    
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getPid() {
        return pid;
    }

    public void setPid(String pid) {
        this.pid = pid;
    }

    public String getProductname() {
        return productname;
    }

    public void setProductname(String productname) {
        this.productname = productname;
    }

    public int getProductcount() {
        return productcount;
    }

    public void setProductcount(int productcount) {
        this.productcount = productcount;
    }

    public int getAllprice() {
        return allprice;
    }

    public void setAllprice(int allprice) {
        this.allprice = allprice;
    }
    
    
}



Product.hbm.xml
 <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="figo.register.dao.Product" table="product" catalog="netshop">
        <id name="pid" type="java.lang.String">
            <column name="pid" length="32" />
            <generator class="assigned"></generator>
        </id>
        <property name="productname" type="java.lang.String">
            <column name="productname" />
        </property>
        <property name="productcount" type="java.lang.Integer">
            <column name="productcount" />            
        </property>
        <property name="allprice" type="java.lang.Integer">
            <column name="allprice" />            
        </property>
        <many-to-one name="user" class="figo.register.dao.User">
            <column name="uid" length="32" />
        </many-to-one>
    </class>
</hibernate-mapping>



UserOperation.java

package figo.register.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

public class UserOperation {

    private Session session;
   
    public UserOperation()
    {
        this.session= new Configuration().configure().buildSessionFactory().openSession();
    }
    public void save(User user)
    {
        this.session.save(user);
        this.session.beginTransaction().commit();
    }
    public void save(Product p)
    {
        this.session.save(p);
        this.session.beginTransaction().commit();
    }
    public User QueryByUsername(String username)
    {
        String hql="from User as u where u.username=?";
        Query q = session.createQuery(hql);
        q.setString(0, username);
        List l=q.list();
        User user = null;
        if(l.size()>0)
        {
            user =(User)l.get(0);
        }
        return user;
    }
    public void update(User user)
    {
        this.session.update(user);
        this.session.beginTransaction().commit();
    }
    public void update(Product p)
    {
        this.session.update(p);
        this.session.beginTransaction().commit();
    }
}


下面就是前台展示层的内容,在web-Root下
建立jsp文件
index.jsp
 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
      
  <body>
     <a href="login.jsp">登陆</a><br>
      
      <a href="register.jsp">注册</a><br>
  </body>
</html>


login.jsp
 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'login.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
 
  <body>
   <s:fielderror></s:fielderror>
    <s:form action="login.action" method="GET">
    <s:textfield name="username" label="用户名"></s:textfield>
    <s:textfield name="password" label="密码"></s:textfield>
    <s:submit value="submit"></s:submit>
    </s:form>
    
  </body>
</html>


loginSuccess.jsp
 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'loginSuccess.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
 
  <body>
    登陆成功     <br>
    您登陆的用户名为:
    <s:property value="username"/><br>
    <%
    String username=request.getParameter("username");
   
    session.setAttribute("username",username);
     %>
   <h1>  <%out.println(session.getAttribute("username")); %></h1>
    
    <a href="shop.jsp">去商店购物</a>
  </body>
</html>


register.jsp
 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'register.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
 
  <body>
    <s:fielderror ></s:fielderror>
    
    <s:form action="register.action">
        <s:textfield name="username" label="名字"></s:textfield>
        <s:password name="password" label="密码"></s:password>
        <s:password name="repassword" label="在输入一次密码"></s:password>
        <s:textfield name="age" label="年龄" ></s:textfield>
        <s:submit value="submit"></s:submit>
    </s:form>
  </body>
</html>

registerSuccess.jsp
 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'registerSuccess.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
 
  <body>
    注册成功
    注册基本信息:
    用户名:<s:property value="username"/><br>
    密码:<s:property value="password"/><br>
    年龄:<s:property value="age"/><br>
  </body>
</html>

shop.jsp
 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'shop.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
 
  <body>
  <h1><%out.println(session.getAttribute("username")) ;%></h1>
    <table align="center" cols="4">
    
    <tr>
        <td>
        商品名
        </td>
        <td>
        商品描述
        </td>
        <td>
        价格
        </td>
        <td>
        </td>
        
    </tr>
    <tr>
        <td id="pen">
            钢笔
        </td>
        <td >
            最好的钢笔
        </td>
        <td>
        $20
        </td>
        <td>
        <a href="shop.action?productname=pen&productcount=1&allprice=20&pid=1">购买一支</a>
        </td>    
    </tr>
    <tr>
    <td id="ballpen">
    圆珠笔
    </td>
    <td>
    最好的圆珠笔
    </td>
    <td>
    $25
    </td>
    <td>
    <a href="shop.action?productname=ballpen&productcount=1&allprice=25&pid=2">购买一支</a>
    </td>
    </tr>
        
    
    
    
    
   
    
    </table>
  </body>
</html>


shopSuccess.jsp
 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'shopSuccess.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
 
  <body>
    购买成功 <br>
    <a href="shop.jsp">返回继续购买</a>
  </body>
</html>

完了,谢谢观赏
我觉得有一个地方的效率不高,我们交流交流