首页 > 代码库 > eclipse ProductSystem运用注解完成项目

eclipse ProductSystem运用注解完成项目

第一步:导包

技术分享

第二步web.xml配置监听器和过滤器

  <display-name>news</display-name>
  <welcome-file-list>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value> <!--这里是告诉程序src里有一个应用文件-->
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

 

第三步 应用文件applicationContext.xml这里要导入一些外部文件jdbc.properties、persistence.xml、

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="    
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd  
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd  
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd  
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

    <!-- 原理:自动注入processor解析器,用来解析注解 -->
    <!-- <context:annotation-config/> -->

    <!-- 自动扫描包,也会自动注入解释器,所以不需要 context:annotation-config -->
    <context:component-scan base-package="product" /><!-- 这里扫描的是各个包的前命如product.dao、product.service、product.action、product.eitity-->


    <!-- 引入外部属性文件 -->
    <context:property-placeholder location="classpath:jdbc.properties" /><!--告诉有一个外部文件,这个外部文件是给用户使用的,用于配置连接数据库的相关信息-->

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="http://www.mamicode.com/s3s124"></property>
    </bean>
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 注入连接池,包含了数据库用户名,密码等等信息 -->
        <property name="dataSource" ref="myDataSource" />

        <!-- 配置Hibernate的其他的属性 -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.connection.autocommit">false</prop>
                <!-- 开机自动生成表 -->
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <property name="mappingResources">
            <list>
                
            </list>
        </property>
        
        <property name="packagesToScan">
            <list>
                <value>product.*</value><!--这个也是用于扫描所有包的-->
            </list>
        </property>

    </bean>

    <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="http://www.mamicode.com/${jdbc.driver}" />
        <property name="jdbcUrl" value="http://www.mamicode.com/${jdbc.url}" />
        <property name="user" value="http://www.mamicode.com/${jdbc.user}" />
        <property name="password" value="http://www.mamicode.com/${jdbc.password}" />
        <!-- 每300秒检查所有连接池中的空闲连接 -->
        <property name="idleConnectionTestPeriod" value="http://www.mamicode.com/300"></property>
        <!-- 最大空闲时间,900秒内未使用则连接被丢弃。若为0则永不丢弃 -->
        <property name="maxIdleTime" value="http://www.mamicode.com/900"></property>
        <!-- 最大连接数 -->
        <property name="maxPoolSize" value="http://www.mamicode.com/2"></property>

    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean><!--这个给注入sessionFactory事例-->

    <tx:annotation-driven transaction-manager="transactionManager"/>


</beans>
            

jdbc.properties文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/news
jdbc.user=root
jdbc.password=123456


#oracle
jdbc_oracle.driver=oracle.jdbc.driver.OracleDriver
jdbc_oracle.url=jdbc:oracle:thin@127.0.0.1:1521:orcl
jdbc_oracle.user=news
jdbc_oracle.password=123456

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
    xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence 
                        http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <!--必须要有name属性,不能为空 -->
    <persistence-unit name="s3s124" transaction-type="RESOURCE_LOCAL">
        <!--可选 -->
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <!--可选 -->
        <class>product.entity.Product</class>


        <!--厂商的特定属性 -->
        <properties>
            <!--配置Hibernate方言 -->
            <property name="hibernate.dialect" value="http://www.mamicode.com/org.hibernate.dialect.MySQL5Dialect" />
            <!--配置数据库驱动 -->
            <property name="hibernate.connection.driver_class" value="http://www.mamicode.com/com.mysql.jdbc.Driver" />
            <!--配置数据库用户名 -->
            <property name="hibernate.connection.username" value="http://www.mamicode.com/root" />
            <!--配置数据库密码 -->
            <property name="hibernate.connection.password" value="http://www.mamicode.com/123456" />
            <!--配置数据库url -->
            <property name="hibernate.connection.url" value="http://www.mamicode.com/jdbc:mysql://localhost:3306/news" />

            <property name="hibernate.show_sql" value="http://www.mamicode.com/true" />
            <!--自动输出schema创建DDL语句 -->
            <property name="hibernate.hbm2ddl.auto" value="http://www.mamicode.com/update" />
        </properties>
    </persistence-unit>


</persistence>

messageResource_en_US.properties英语

#\u4EA7\u54C1\u540D\u5B57\uFF1A
proName=Product name 
#\u4EA7\u54C1\u4EF7\u683C
proPrice=Product price
#\u4EA7\u54C1\u6570\u91CF
proCount=Product count
#\u4EA7\u54C1\u63CF\u8FF0
proDesc=Product Description

messageResource_zh_CN.properties中文

#\u4EA7\u54C1\u540D\u5B57\uFF1A
proName=\u4EA7\u54C1\u540D\u5B57
#\u4EA7\u54C1\u4EF7\u683C
proPrice=\u4EA7\u54C1\u4EF7\u683C
#\u4EA7\u54C1\u6570\u91CF
proCount=\u4EA7\u54C1\u6570\u91CF
#\u4EA7\u54C1\u63CF\u8FF0
proDesc=\u4EA7\u54C1\u63CF\u8FF0

第四步:创建四个包和内部文件

技术分享

1、product.action包的Product.java

package product.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="t_product")//这个是创表的注解,里面是对应的表名
public class Product {
    private    Integer proId;
    private String proName;
    private Float proPrice;
    private Integer proCount;
    private String proDesc;
    
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)//这个是主键
    public Integer getProId() {
        return proId;
    }
    public void setProId(Integer proId) {
        this.proId = proId;
    }
    
    @Column(name="proName",nullable=false,length=50)
    public String getProName() {
        return proName;
    }
    public void setProName(String proName) {
        this.proName = proName;
    }
    
    @Column(name="proPrice",nullable=false)
    public Float getProPrice() {
        return proPrice;
    }
    public void setProPrice(Float proPrice) {
        this.proPrice = proPrice;
    }
    
    @Column(name="proCount",nullable=false)
    public Integer getProCount() {
        return proCount;
    }
    public void setProCount(Integer proCount) {
        this.proCount = proCount;
    }
    
    @Column(name="proDesc",nullable=false,length=250)
    public String getProDesc() {
        return proDesc;
    }
    public void setProDesc(String proDesc) {
        this.proDesc = proDesc;
    }


}

2.product.dao的接口proDao

package product.dao;

import java.util.List;

import product.entity.Product;

public interface ProDao {
    public List<Product> getAllPro();
    
    public void delPro(Integer proId[]);
    
    public String addProduct(Product product);
}

proDaoImpl实现类

package product.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
//import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import product.entity.Product;

@Repository
@Scope("prototype")
public class ProDaoImpl implements ProDao {
    @Autowired
    @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;
    
    //@Autowired
    //@Qualifier("entityManagerFactory")
    //private EntityManagerFactory entityManagerFactory;//获取实例有2个方法:1.自己写代码   2.spring注入
    
    @Override
    public List<Product> getAllPro() {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from Product");
        List<Product> list = query.getResultList();
        return list;
    }

    @Override
    public void delPro(Integer proId[]) {
        // TODO Auto-generated method stub
        
        Session session = sessionFactory.getCurrentSession();
        
        Query<Product> query = session.createQuery("from Product where proId=:myid");
        //System.out.println("proId:"+proId);
        for(Integer id : proId){
            query.setParameter("myid", id);

            if(query.getResultList().size()>0){
                Product pro = query.getResultList().get(0);
                session.delete(pro);
            }

        }
    }

    @Override
    public String addProduct(Product product) {
        Session session = sessionFactory.getCurrentSession();
        session.save(product);
        return "ok";
    }

}

 

3.product.service包的接口proService

package product.service;

import java.util.List;

import product.entity.Product;

public interface ProService {
    public List<Product> getAllPro();
    
    public void delPro(Integer proId[]);
    
    public String addProduct(Product product);
}

proServiceImpl实现类

package product.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import product.dao.ProDao;
import product.entity.Product;

@Transactional
@Service
@Scope("prototype")
public class ProServiceImpl implements ProService {
    @Autowired
    private ProDao pd;
    
    @Override
    @Transactional(readOnly=true)
    public List<Product> getAllPro() {
        // TODO Auto-generated method stub
        return pd.getAllPro();
    }

    @Override
    public void delPro(Integer proId[]) {
        //System.out.println("proId:"+proId);
        pd.delPro(proId);
    }

    @Override
    public String addProduct(Product product) {
        //本例不包含其它的业务逻辑代码,直接调用dao进行保存
        
        return pd.addProduct(product);
    }

}

 

4.product.action的proAction

package product.action;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

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

import product.entity.Product;
import product.service.ProService;

@SuppressWarnings("serial")
@Controller("proAction")//这里和struts.xml里的<action>的class=“proAciton”对应
@Scope("prototype")
public class ProAction extends ActionSupport implements ModelDriven<Product>{
    @Autowired
    private ProService ps;

    private Integer[] proIds;

    public void setProIds(Integer[] proIds) {
        this.proIds = proIds;
    }

    //驱动模式
    private Product product;
    public void setProduct(Product product) {
        this.product = product;
    }

    
    
    public String showAllPro() {
        List<Product> proList = ps.getAllPro();
        ActionContext.getContext().put("proList", proList);
        return "data";
    }

    public String delPro() {
        System.out.println("123456");
        ps.delPro(proIds);
        return "deleteOK";
    }

    // 跳转到添加页面(PS.其实可以不用,直接用JSP代替也行)
    public String addProduct_view() {
        // 这里可以插入其它代码,比如:日志跟踪
        return "addProduct_view";
    }

    // 跳转到添加页面(PS.其实可以不用,直接用JSP代替也行)
    public String addProduct_deal() {
        //1.获取客户端提交上来的数据(采用字段模式,或者驱动模式,struts会自动帮我们赋值)
        System.out.println("product.getProName():"+product.getProName());
        
        
        //2.校验条件的数据是否正确(不需要写代码,服务端校验的配置文件)
             //返回错误
        //3.呼叫service,进行页面逻辑代码的处理,然后dao保存到数据库
             //返回错误
        String resutlDeal = ps.addProduct(product);
        if ("ok".equals(resutlDeal)){
            //4.成功插入到数据库后,跳转到首页的action,重新显示最新的数据
            return "addProduct_success";
        }
        else{
            //失败,跳转到失败页面去
            return "addProduct_failed";
        }
    }

    
    
    @Override
    public Product getModel() {
        this.product =new Product(); 
        return product;
    }

}

 

第五步:struts2.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <constant name="struts.objectFactory" value="http://www.mamicode.com/spring" />

    <constant name="struts.ui.theme" value="http://www.mamicode.com/simple"></constant>
    
    <constant name="struts.custom.i18n.resources" value="http://www.mamicode.com/messageResource"></constant>
    
    <!-- 第1步:先定义一个包 -->
    <package name="mypck001" extends="struts-default">
        <action name="ProAction_*" class="proAction" method="{1}"><!--这里name=“文件里的_某个”  class=“@Controller("proAction")注解里的” method=“里面的方法一般是showall……(){}”-->
            <result name="data">/WEB-INF/jsp/index.jsp</result>
            <result name="addProduct_view">/WEB-INF/jsp/addProduct.jsp</result>
            <result name="deleteOK" type="redirectAction">ProAction_showAllPro</result>
            <result name="addProduct_success" type="redirectAction">ProAction_showAllPro</result>
        </action>        
    </package>
    
    
</struts>

 

第六步:创建default.jsp、addProduct.jsp和index.jsp

1.default.jsp这个是完成跳转的该文件在WEB-INF下

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    response.sendRedirect("ProAction_showAllPro.action");
%>

2.index.jsp该文件在WEB-INF/jsp下

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>welcome</title>
</head>
<body>
    <s:form action="ProAction_delPro">
        <table border="1">
            <s:iterator value="http://www.mamicode.com/proList">
                <tr>
                    <td><s:checkbox name="proIds" value="http://www.mamicode.com/false" fieldValue="http://www.mamicode.com/%{proId}" /></td>
                    <td><s:property value="http://www.mamicode.com/proName"/></td>
                    <td><s:property value="http://www.mamicode.com/proPrice"/></td>
                    <td><s:property value="http://www.mamicode.com/proCount"/></td>
                    <td><s:property value="http://www.mamicode.com/proDesc"/></td>
                </tr>
            </s:iterator>
            <tr>
                <td colspan="5"><s:submit label="删除" /></td>
            </tr>
            <tr>
                <td colspan="5"><s:a href="http://www.mamicode.com/ProAction_addProduct_view.action">添加</s:a></td>
            </tr>
                            
            
            
        </table>
    </s:form>
</body>
</html>

3.addProduct.jsp该文件在WEB-INF/jsp下

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
添加页面
         
<s:form action="ProAction_addProduct_deal.action">
<s:text name="proName"></s:text>:<s:textfield id="proName" name="proName"></s:textfield><br>
<s:text name="proPrice"></s:text>:<s:textfield id="proPrice" name="proPrice"></s:textfield><br>
<s:text name="proCount"></s:text>:<s:textfield id="proCount" name="proCount"></s:textfield><br>
<s:text name="proDesc"></s:text>:<s:textfield id="proDesc" name="proDesc"></s:textfield><br>

<s:submit value="http://www.mamicode.com/提交"></s:submit>

</s:form>
</body>
</html>

 第六步:运行

entity注解自动创表,我们使用的是然后我们手动插入几条数据

insert into t_product(proName,proPrice,proCount,proDesc) values(aaa,123,3,xiaolj);
insert into t_product(proName,proPrice,proCount,proDesc) values(aaa,123,3,xiaolj);
insert into t_product(proName,proPrice,proCount,proDesc) values(aaa,123,3,xiaolj);
insert into t_product(proName,proPrice,proCount,proDesc) values(aaa,123,3,xiaolj);

 运行后如下

技术分享

点击添加

技术分享

输入信息

技术分享

得到

技术分享

这个就这样完成了

 

<!---->

eclipse ProductSystem运用注解完成项目