JavaWeb项目开发案例精粹-第6章报价管理系统-002辅助类及配置文件

时间:2023-03-08 23:32:51
JavaWeb项目开发案例精粹-第6章报价管理系统-002辅助类及配置文件

1.

 <?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 配置哪些包下的类需要自动扫描 -->
<context:component-scan base-package="com.sanqing"/> <!-- 这里的jun要与persistence.xml中的 <persistence-unit name="jun" transaction-type="RESOURCE_LOCAL">
中的name值要一致,这样才能找到相关的数据库连接
-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="jun"/>
</bean>
<!-- 配置事物管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- 配置使用注解来管理事物 -->
<tx:annotation-driven transaction-manager="transactionManager"/> </beans>

2.

 <?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>
<constant name="struts.enable.DynamicMethodInvocation"
value="false" />
<constant name="struts.devMode" value="false" />
<!-- 与spring集成 -->
<constant name="struts.objectFactory" value="spring" />
<!-- 改变后缀名 -->
<constant name="struts.action.extension" value="do" />
<!-- 配置国际化资源文件 -->
<constant name="struts.custom.i18n.resources"
value="globalMessages" />
<!-- 处理编码问题 -->
<constant name="struts.i18n.encoding" value="GBK" />
<!-- 当修改配置文件不需要重启服务,开发比较有用 -->
<constant name="struts.configuration.xml.reload" value="true" />
<!-- 报表 -->
<!--
<package name="lee" namespace="/" extends="jasperreports-default">
<action name="jasper" class="jasperAction">
<result name="success" type="jasper">
<param name="location">report\jasper\order.jrxml</param>
<param name="format">HTML</param>
<param name="dataSource">order</param>
</result>
</action>
</package>
-->
<!-- 用户登录 -->
<package name="san" namespace="/" extends="struts-default">
<action name="login" class="loginAction" >
<result name="success">/back_index.html</result>
<result name="input">/index.jsp</result>
</action>
</package>
<!-- 控制相关模块 -->
<package name="qing" namespace="/control" extends="struts-default">
<interceptors><!--配置拦截器 -->
<interceptor name="loginIntercepter"
class="com.sanqing.intercepter.LoginIntercepter" /><!--配置登录判断拦截器-->
<interceptor-stack name="mydefault"><!--配置拦截器栈-->
<interceptor-ref name="defaultStack" /><!--Struts 2默认拦截器 -->
<interceptor-ref name="loginIntercepter" /><!--登录判断拦截器 -->
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="mydefault" /><!--配置默认拦截器-->
<global-results>
<result name="pub_add_success">/share/pub_add_success.jsp</result>
<result name="pub_update_success">/share/pub_update_success.jsp</result>
<result name="pub_del_success">/share/pub_del_success.jsp</result>
<result name="input">/index.jsp</result>
</global-results>
<!-- 客户显示 -->
<action name="customer" class="customerAction">
<result name="success">
/customer/customer_list.jsp
</result>
</action>
<!-- 客户管理 -->
<action name="customermanage_*" class="customerManageAction" method="{1}">
<result name="add">/customer/customer_add.jsp</result>
<result name="update">/customer/customer_update.jsp</result>
<result name="query">/customer/customer_query.jsp</result>
</action>
<!-- 产品类别显示 -->
<action name="producttype" class="productTypeAction">
<result name="success">
/product/producttype_list.jsp
</result>
</action>
<!-- 产品类别管理 -->
<action name="producttypemanage_*" class="productTypeManageAction" method="{1}">
<result name="add">/product/producttype_add.jsp</result>
<result name="update">/product/producttype_update.jsp</result>
<result name="query">/product/producttype_query.jsp</result>
</action>
<!-- 产品显示 -->
<action name="product" class="productAction">
<result name="success">
/product/product_list.jsp
</result>
</action>
<!-- 产品管理 -->
<action name="productmanage_*" class="productManageAction" method="{1}">
<result name="add">/product/product_add.jsp</result>
<result name="update">/product/product_update.jsp</result>
<result name="query">/product/product_query.jsp</result>
</action>
<!-- 订单显示 -->
<action name="order" class="orderAction">
<result name="success">
/order/order_list.jsp
</result>
</action>
<!-- 订单管理 -->
<action name="ordermanage_*" class="orderManageAction" method="{1}">
<result name="add">/order/order_add.jsp</result>
<result name="update">/order/order_update.jsp</result>
<result name="query">/order/order_query.jsp</result>
</action>
<!-- 报价显示 -->
<action name="quotation" class="quotationAction">
<result name="success">
/quotation/quotation_list.jsp
</result>
</action>
<!-- 报价管理 -->
<action name="quotationmanage_*" class="quotationManageAction" method="{1}">
<result name="add">/quotation/quotation_add.jsp</result>
<result name="update">/quotation/quotation_update.jsp</result>
<result name="query">/quotation/quotation_query.jsp</result>
</action>
<!-- 用户显示 -->
<action name="user" class="userAction">
<result name="success">
/user/user_list.jsp
</result>
</action>
<!-- 用户管理 -->
<action name="usermanage_*" class="userManageAction" method="{1}">
<result name="add">/user/user_add.jsp</result>
<result name="update">/user/user_update.jsp</result>
<result name="query">/user/user_query.jsp</result>
</action>
</package>
</struts>

3.

 <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>hibernate的jpa实现</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
<!-- 对Spring容器进行实例化 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- 把jpa的EntityManager设为开启状态 解决延迟加载的问题-->
<filter>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<filter-class>
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 利用的spring的过滤器来设置编码方式 -->
<filter>
<filter-name>Spring character encoding filter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Spring character encoding filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- struts2.1配置 start 注意我们陪着struts2的时候一定把这个过滤器ActionContextCleanUp陪在FilterDispatcher的前面-->
<display-name>Struts Blank</display-name>
<filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ActionContextCleanUp
</filter-class>
</filter>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<display-name>Struts Blank</display-name>
<!-- struts2.1 end -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

4.META-INF/persistence.xml

 <?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="jun" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQLDialect"/><!--数据库方言-->
<property name="hibernate.connection.driver_class"
value="com.mysql.jdbc.Driver"/><!--数据库驱动类-->
<property name="hibernate.connection.username" value="root"/><!--数据库用户名-->
<property name="hibernate.connection.password" value="1234"/>
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost:3306/quote"/><!--数据库连接URL-->
<property name="hibernate.max_fetch_depth" value="3"/><!--外连接抓取树的最大深度 -->
<property name="hibernate.hbm2ddl.auto" value="update"/><!-- 自动输出schema创建DDL语句 -->
<property name="hibernate.jdbc.fetch_size" value="18"/><!-- JDBC的获取量大小 -->
<property name="hibernate.jdbc.batch_size" value="10"/><!-- 开启Hibernate使用JDBC2的批量更新功能 -->
<property name="hibernate.show_sql" value="true"/><!-- 在控制台输出SQL语句 -->
</properties>
</persistence-unit>
</persistence>

5.

 package com.sanqing.intercepter;

 import java.util.Map;

 import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.sanqing.po.User; public class LoginIntercepter extends AbstractInterceptor {
private static final long serialVersionUID = 6203506362291764836L;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext ctx=invocation.getInvocationContext();//获得ActionContext对象
Map session=ctx.getSession(); //获得session对象
User user = (User)session.get("user");//获得用户登录信息
if(user != null) { //如果不为空,则表示已经登录
return invocation.invoke();//继续执行后面的操作
}
return "input";//跳转到登录页面
}
}

6.

 package com.sanqing.util;

 import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map; import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter; public class DateConverter extends DefaultTypeConverter {
private static final DateFormat[] ACCEPT_DATE_FORMATS = {
new SimpleDateFormat("dd/MM/yyyy"),
new SimpleDateFormat("yyyy-MM-dd"),
new SimpleDateFormat("yyyy/MM/dd") }; // 支持转换的日期格式
@SuppressWarnings("unchecked")
public Object convertValue(Map context, Object value, Class toType) {
if (toType == Date.class) { //进行String到Date的转换
Date date = null;
String dateString = null;
String[] params = (String[]) value; //获得参数列表
dateString = params[0]; //获取日期的字符串
for (DateFormat format : ACCEPT_DATE_FORMATS) {
try {
date = format.parse(dateString);//对字符串进行转换
return date; //返回Date类型日期
} catch (Exception e) {
continue;
}
}
return null;
} else if (toType == String.class) { //进行Date到String的转换
Date date = (Date) value;//强制类型转换
return new SimpleDateFormat("yyyy-MM-dd").format(date);//返回String类型日期
}
return null;
}
}

7.

 package com.sanqing.util;

 import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
* 泛型工具类
*
*/
public class GenericsUtils {
/**
* 通过反射,获得指定类的父类的泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer>
*
* @param clazz clazz 需要反射的类,该类必须继承范型父类
* @param index 泛型参数所在索引,从0开始.
* @return 范型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getSuperClassGenricType(Class clazz, int index) {
Type genType = clazz.getGenericSuperclass();//得到泛型父类
//如果没有实现ParameterizedType接口,即不支持泛型,直接返回Object.class
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
//返回表示此类型实际类型参数的Type对象的数组,数组里放的都是对应类型的Class, 如BuyerServiceBean extends DaoSupport<Buyer,Contact>就返回Buyer和Contact类型
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class) params[index];
}
/**
* 通过反射,获得指定类的父类的第一个泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer>
*
* @param clazz clazz 需要反射的类,该类必须继承泛型父类
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getSuperClassGenricType(Class clazz) {
return getSuperClassGenricType(clazz,0);
}
/**
* 通过反射,获得方法返回值泛型参数的实际类型. 如: public Map<String, Buyer> getNames(){}
*
* @param Method method 方法
* @param int index 泛型参数所在索引,从0开始.
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getMethodGenericReturnType(Method method, int index) {
Type returnType = method.getGenericReturnType();
if(returnType instanceof ParameterizedType){
ParameterizedType type = (ParameterizedType) returnType;
Type[] typeArguments = type.getActualTypeArguments();
if (index >= typeArguments.length || index < 0) {
throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
}
return (Class)typeArguments[index];
}
return Object.class;
}
/**
* 通过反射,获得方法返回值第一个泛型参数的实际类型. 如: public Map<String, Buyer> getNames(){}
*
* @param Method method 方法
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getMethodGenericReturnType(Method method) {
return getMethodGenericReturnType(method, 0);
} /**
* 通过反射,获得方法输入参数第index个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> maps, List<String> names){}
*
* @param Method method 方法
* @param int index 第几个输入参数
* @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合
*/
@SuppressWarnings("unchecked")
public static List<Class> getMethodGenericParameterTypes(Method method, int index) {
List<Class> results = new ArrayList<Class>();
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (index >= genericParameterTypes.length ||index < 0) {
throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
}
Type genericParameterType = genericParameterTypes[index];
if(genericParameterType instanceof ParameterizedType){
ParameterizedType aType = (ParameterizedType) genericParameterType;
Type[] parameterArgTypes = aType.getActualTypeArguments();
for(Type parameterArgType : parameterArgTypes){
Class parameterArgClass = (Class) parameterArgType;
results.add(parameterArgClass);
}
return results;
}
return results;
}
/**
* 通过反射,获得方法输入参数第一个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> maps, List<String> names){}
*
* @param Method method 方法
* @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合
*/
@SuppressWarnings("unchecked")
public static List<Class> getMethodGenericParameterTypes(Method method) {
return getMethodGenericParameterTypes(method, 0);
}
/**
* 通过反射,获得Field泛型参数的实际类型. 如: public Map<String, Buyer> names;
*
* @param Field field 字段
* @param int index 泛型参数所在索引,从0开始.
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getFieldGenericType(Field field, int index) {
Type genericFieldType = field.getGenericType(); if(genericFieldType instanceof ParameterizedType){
ParameterizedType aType = (ParameterizedType) genericFieldType;
Type[] fieldArgTypes = aType.getActualTypeArguments();
if (index >= fieldArgTypes.length || index < 0) {
throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
}
return (Class)fieldArgTypes[index];
}
return Object.class;
}
/**
* 通过反射,获得Field泛型参数的实际类型. 如: public Map<String, Buyer> names;
*
* @param Field field 字段
* @param int index 泛型参数所在索引,从0开始.
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getFieldGenericType(Field field) {
return getFieldGenericType(field, 0);
}
}

8.

 package com.sanqing.util;

 public class PageIndex {
private long startindex;
private long endindex; public PageIndex(long startindex, long endindex) {
this.startindex = startindex;
this.endindex = endindex;
}
public long getStartindex() {
return startindex;
}
public void setStartindex(long startindex) {
this.startindex = startindex;
}
public long getEndindex() {
return endindex;
}
public void setEndindex(long endindex) {
this.endindex = endindex;
} public static PageIndex getPageIndex(long viewpagecount, int currentPage, long totalpage){
long startpage = currentPage-(viewpagecount%2==0? viewpagecount/2-1 : viewpagecount/2);
long endpage = currentPage+viewpagecount/2;
if(startpage<1){
startpage = 1;
if(totalpage>=viewpagecount) endpage = viewpagecount;
else endpage = totalpage;
}
if(endpage>totalpage){
endpage = totalpage;
if((endpage-viewpagecount)>0) startpage = endpage-viewpagecount+1;
else startpage = 1;
}
return new PageIndex(startpage, endpage);
}
}

9.

 package com.sanqing.util;

 import java.util.List;

 public class PageView<T> {
/** 分页数据 **/
private List<T> records;
/** 页码开始索引和结束索引 **/
private PageIndex pageindex;
/** 总页数 **/
private long totalpage = 1;
/** 每页显示记录数 **/
private int maxresult = 12;
/** 当前页 **/
private int currentpage = 1;
/** 总记录数 **/
private long totalrecord;
/** 页码数量 **/
private int pagecode = 10;
/** 要获取记录的开始索引 **/
public int getFirstResult() {
return (this.currentpage-1)*this.maxresult;
}
public int getPagecode() {
return pagecode;
} public void setPagecode(int pagecode) {
this.pagecode = pagecode;
} public PageView(int maxresult, int currentpage) {
this.maxresult = maxresult;
this.currentpage = currentpage;
} public void setQueryResult(QueryResult<T> qr){
setTotalrecord(qr.getTotalrecord());
setRecords(qr.getResultlist());
} public long getTotalrecord() {
return totalrecord;
}
public void setTotalrecord(long totalrecord) {
this.totalrecord = totalrecord;
setTotalpage(this.totalrecord%this.maxresult==0? this.totalrecord/this.maxresult : this.totalrecord/this.maxresult+1);
}
public List<T> getRecords() {
return records;
}
public void setRecords(List<T> records) {
this.records = records;
}
public PageIndex getPageindex() {
return pageindex;
}
public long getTotalpage() {
return totalpage;
}
public void setTotalpage(long totalpage) {
this.totalpage = totalpage;
this.pageindex = PageIndex.getPageIndex(pagecode, currentpage, totalpage);
}
public int getMaxresult() {
return maxresult;
}
public int getCurrentpage() {
return currentpage;
}
}

10.

 package com.sanqing.util;

 import java.util.List;
/**
* 分页实体类封装
*
*/
public class QueryResult<T> {
/** 获得结果集 **/
private List<T> resultlist;
/** 获得总的记录数 **/
private long totalrecord; public List<T> getResultlist() {
return resultlist;
}
public void setResultlist(List<T> resultlist) {
this.resultlist = resultlist;
}
public long getTotalrecord() {
return totalrecord;
}
public void setTotalrecord(long totalrecord) {
this.totalrecord = totalrecord;
}
}

11.

 ### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file hibernate.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=d:/crm.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=warn, stdout,file #log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug ### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug ### log just the SQL
#log4j.logger.org.hibernate.SQL=debug ### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug ### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug ### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug ### log cache activity ###
#log4j.logger.org.hibernate.cache=debug ### log transaction activity
#log4j.logger.org.hibernate.transaction=debug ### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug ### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
log4j.logger.com.quote = debug