1 jndi
配置數(shù)所源
<context:property-placeholder location="jdbc.properties"/>//引入資源文件
<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.git.mm.mysql.Driver[${driverClassName}]"/>
<property name="url" value="jdbc:mysql://localhost:3306/database?useUnicode=true & characterEncoding=UTF-8[${url}]"/>
<property name="username" value="root[${username}]"/>
<property name="password" value="root[${password}]"/>
<!-- 連接池啟動(dòng)時(shí)的初始值勤 -->
<property name="initialSize" value="1[${initialSize}]"/>
<!-- 連接池的最大值 -->
<property name="maxActive" value="500[${maxActive}]"/>
<!-- 最大空閑值,當(dāng)經(jīng)過(guò)一個(gè)高峰時(shí)間后,連接池可以慢慢將已經(jīng)用不到的連接釋放一部分,一直減少到maxIdle為止 -->
<property name="maxIdle" value="2[${maxIdle}]"/>
<!-- 最小空閑值,當(dāng)連接池的連接數(shù)量少于閥值時(shí),連接池就會(huì)申請(qǐng)一些連接,以免洪峰時(shí)來(lái)不及申請(qǐng) -->
<property name="minIdle" value="1[${minIdle}]"/>
</bean>
2 bean
<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:sqlserver://127.0.0.1:1433;databaseName=somken"/>
<property name="username" value="sa"/>
<property name="password" value="123456"/>
</bean>
<bean id="sf" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<property name="mappingResources">
<list>
<value>org/somken/entity/UserInfo.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>

3 讀取hibernate.cfg.xml
<bean id="sf" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
</bean>
摘要: IOC控制反轉(zhuǎn):應(yīng)用本身不負(fù)責(zé)依賴(lài)對(duì)象的創(chuàng)建及維護(hù),依賴(lài)對(duì)象的創(chuàng)建及維護(hù)是由外部容器負(fù)責(zé)的。
依賴(lài)注入:在運(yùn)行期,由外部容器動(dòng)態(tài)地將依賴(lài)對(duì)象注入到組件中。
-----------------------------------------------------------------------------
第一個(gè)項(xiàng)目
1 spring的依賴(lài)庫(kù)
&n...
閱讀全文
摘要: 靜態(tài)代理
通過(guò)接口實(shí)現(xiàn)
動(dòng)態(tài)代理
1 編寫(xiě)java代理類(lèi)
public class SecurityHandler implements InvocationHandler {
private Object targetObject;
 ...
閱讀全文
sql
package org.epet.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import com.sun.java_cup.internal.internal_error;


public abstract class BaseDAO
{
private static final String DRIVER_CLASS = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String DATABASE_URL = "jdbc:sqlserver://localhost:1433;DatabaseName=epet";
private static final String DATABASE_USER = "sa";
private static final String DATABASE_PASSWORD = "accp";

/** *//**
* 返回連接
* @return
*/

public static Connection getConnection()
{
Connection connection=null;

try
{
Class.forName(DRIVER_CLASS);
connection = DriverManager.getConnection(DATABASE_URL,
DATABASE_USER, DATABASE_PASSWORD);
// Context tx=new InitialContext();
// DataSource ds=(DataSource)tx.lookup("java:comp/env/food");
// connection=ds.getConnection();


} catch (SQLException e)
{
e.printStackTrace();

} catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}

/** *//**
* 查詢(xún)
* @param sql
* @return
*/

public static ResultSet getDate(String sql)
{
Connection connection=getConnection();
ResultSet resultSet=null;

try
{
PreparedStatement preparedStatement=connection.prepareStatement(sql);
resultSet=preparedStatement.executeQuery();

} catch (SQLException e)
{
e.printStackTrace();
}
return resultSet;
}

public static int dele(String sql,int id)
{
int result=0;
Connection connection=getConnection();

try
{
PreparedStatement preparedStatement=connection.prepareStatement(sql);
preparedStatement.setInt(1, id);
result=preparedStatement.executeUpdate();

} catch (SQLException e)
{
e.printStackTrace();
}
return result;
}
}

mysql:

/**//*show databases;
create database aa;
use aa;
show tables;
select * from userinfo limit 1,2;
-----------------------------------------*/

public connection getConnection () throws SQLException
{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://127.0.1:3306/somken(數(shù)據(jù)庫(kù)名)";
return DriverManager.getConnection(url,"root","root");
}
1 自定義異常類(lèi) SystemException.java
public class SystemException extends RuntimeException{
//自定義key
private String key;
//自定義參數(shù)
private Object[] values;
//實(shí)現(xiàn)父類(lèi)的構(gòu)造方法
public SystemException() {
super();
}
public SystemException(String message, Throwable cause) {
super(message, cause);
}
public SystemException(String message) {
super(message);
}
public SystemException(Throwable cause) {
super(cause);
}
//自定義構(gòu)造方法
public SystemException(String message, String key) {
super(message);
this.key=key;
}
//自定義構(gòu)造方法,帶一個(gè)參數(shù)
public SystemException(String message, String key,Object value) {
super(message);
this.key=key;
this.values=new Object[]{value};
}
//自定義構(gòu)造方法,帶多個(gè)參數(shù)
public SystemException(String message, String key,Object[] values) {
super(message);
this.key=key;
this.values=values;
}
//相應(yīng)的get方法
public String getKey() {
return key;
}
public Object[] getValues() {
return values;
}
}
2 自定義異常處理器 SystemExceptionHandler.java
//作用:截獲SystemException,并根據(jù)SystemException中的信息動(dòng)態(tài)創(chuàng)建ActionMessage等這些錯(cuò)誤信息,
將其存在request中
public class SystemExceptionHandler extends ExceptionHandler{
/**
* 處理SystemException異常
*/
@Override
public ActionForward execute(Exception ex,//拋出的異常
ExceptionConfig config,//struts-config.xml中的配置信息
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws ServletException {
ActionForward forward=null;
//創(chuàng)建ActionForward
if(config.getPath()!=null){
//有path屬性,則根據(jù)path創(chuàng)建
forward=new ActionForward(config.getPath());
}else {
//沒(méi)有path屬性,則根據(jù)input屬性創(chuàng)建
forward=mapping.getInputForward();
}
if(ex instanceof SystemException){
SystemException se=(SystemException)ex;
//key可有可無(wú),所以取出key進(jìn)行判斷
String key=se.getKey();
ActionMessage error=null;
//如果自定義的key為空,用struts的
if(key==null){
//拿出error.default和message,創(chuàng)建ActionMessage對(duì)象
error=new ActionMessage(config.getKey(),se.getMessage());
}else {
//如果自定義的key有值
if(se.getValues()!=null){
error=new ActionMessage(key,se.getValues());
}else {
//如果自定義的key有值,則根據(jù)key創(chuàng)建ActionMessage對(duì)象
error=new ActionMessage(key);
}
}
//將這個(gè)ActionMessage放到request中。key為自定義的,error為ActionMessage對(duì)象
//forward是要轉(zhuǎn)到什么地方,根據(jù)path屬性創(chuàng)建。"request"為scope的一個(gè),也可以
//用config.getScope()
this.storeException(request, key, error, forward, config.getScope());
return forward;
}
return super.execute(ex, config, mapping, form, request, response);
}
}
3 編寫(xiě)配置文件 struts-config.xml
<global-exceptions>
<exception key="error.default"
type="java.lang.Exception"
scope="request"
path="/common/exception.jsp"
<!-- 自定義的異常處理類(lèi) -->
handler="org.oa.common.SystemExceptionHandler"/>
</global-exceptions>
4 編寫(xiě)資源文件 ApplicationResources.properties
error.default={0}
error.org.del=Can't Del Orgnation,id is {0}!
5 業(yè)務(wù)代碼
throw new org.oa.common.SystemException("存在子機(jī)構(gòu),不允許刪除!","error.org.del",org.getOname());
框架
面向請(qǐng)求驅(qū)動(dòng):
struts1.x,struts2.x,WebWork
面向事件驅(qū)動(dòng)的(JSF)
--------------------------------------
struts空字段測(cè)試
<input type="text" name="username"\>
ActionForm中有:
private String username;
private String password;
頁(yè)面取得值:
<%=form.getUserName()%>//結(jié)果:
<%=form.getPassWord()%>//結(jié)果:null
${requestScope.userActionForm.username}//結(jié)果:
${requestScope.userActionForm.password}//結(jié)果:
----------------------------------------------------
java國(guó)際化
1 了解缺省Locale是由操作系統(tǒng)決定的,Locale是由語(yǔ)言和國(guó)家代碼組成
2 國(guó)際化資源文件是由baseName+locale組成,一般在src目錄下就可以了,如:MessageBundle_en_US.properties
baseName是任意合法的文件名
3 native2ascii命令的位置和用法
* 位置:java_home/bin
* 使用native2ascii.exe o.properties MessagesBundle_zh_CN.properties
* DOS
D:\>native2ascii -encoding gb2312 aaa.txt bbb.txt
------------------------------------------------------------------
struts國(guó)際化
1 在struts-config.xml文件中加入:<message-resources parameter="MessageResources"/>
注意:文件默認(rèn)放在根src下,如入在其他目錄下.
如:res目錄下用"."連接<message-resources parameter="res.MessageResources"/>
2 提供不同版本的國(guó)際化文件,中文需要采用native2ascii轉(zhuǎn)換成unicode
MessageResources_en_US.properties文件
user.login.success={0},Login Success
user.title=User Login
user.name=User Name
user.password=Password
user.button.login=Login
MessageResources_zh_CN.properties文件
user.login.success={0},\u767b\u5f55\u6210\u529f
user.title=\u7528\u6237\u767b\u5f55
user.name=\u7528\u6237\
user.password=\u5bc6\u7801
user.button.login=\u767b\u5f55
3 在jsp中采用<bean:message>標(biāo)簽讀取國(guó)際化文本
<titel><bean:message key="user.title"/></title>
<bean:message key="user.name"/>:<input type="text" name="username"/>
<bean:message key="user.password"/>:<input type="password" name="password"/>
<input type="submit" value="<bean:message key="user.name"/>"/>
4 動(dòng)態(tài)設(shè)置locale
Locale currentLocale=Locale.getDefalut();得到Locale
currentLocale=new Loale("zh","CN");//建立Locale
currentLocale=new Loale("en","US");//建立Locale
request.getSession().setAttribute(Globals.LOCALE_KEY,currentLocale);
this.setLocale(request,currentLocale);//效果同上
5 動(dòng)態(tài)設(shè)置message
* 創(chuàng)建messages集合
ActionMessages messages=new ActionMessages();
* 創(chuàng)建國(guó)際化消息文本
public ActionMessage(String key,Object value)
ActionMessage message=new ActionMessage("user.login.success",username);//只不清一個(gè)參數(shù)
//ActionMessage message=new ActionMessage("user.login.success",new Object[]{username});//多個(gè)參數(shù)
messages.add("loginSuccess1",message);
* 傳遞國(guó)際化消息文本
this.saveMessages(request,messages);
錯(cuò)誤信息傳遞使用:this.saveErrors(request,messages);
* 頁(yè)面輸出
通過(guò)<html:message>標(biāo)簽顯示消息(可以顯示普通消息和錯(cuò)誤消息)
通過(guò)<html:errors>標(biāo)簽顯示消息(只能顯示錯(cuò)誤消息)
<html:messages id="msg" message="true">//html:messages標(biāo)記與ActionMessages messages集合對(duì)應(yīng)
<bean:write name="msg"/>
<html:messages>
<html:messages id="msg" message="true" property="loginSuccess1">
<bean:write name="msg"/>
<html:messages>
-------------------------------------------------------------------
JSTL國(guó)際化
<fmt:setLocale vlaue="${header['accept-language']}"/>設(shè)置locale
<fmt:setBundle basename="res.MessageResources"/>//設(shè)置資源文件
<fmt:message key="user.username"/>
---------------------------------------------------------------------
struts的路徑與模式匹配
1 建立頁(yè)面
<form action="" name="form1" enctype="multipart/form-data" method="post">
2 建ActionForm類(lèi)
private String title;
private FormFile file;//必須用apache的FormFile類(lèi)(org.apache.struts.upload.FormFile)
3 建立Action類(lèi)
UplodaActionForm uaf=(UplodaActionForm)form;
Systyem.out.println("title:"+uaf.getTitle());
FormFile file=uaf.getFile();
if(file!=null)
{
System.out.println("fileName:"+file.getFileName());
FileOutputStream fos=new FileOutputStream("c:\\"+file.getFileName());
fos.write(file.getFileData());
fos.flush();
fos.close();
}
return mapping.findForward("sessucc");
4 配置ActionForm和Action
<controller MaxFileSize="10M"></controller>該屬性可以配置上傳文件的大小等相關(guān)信息
1 ActionForm中的validate方法驗(yàn)證
1)重寫(xiě)ActionForm中的validate方法
public ActionErrors validate(ActionMapping mapping,HttpServletRequest request){
ActionErrors errors=new ActionErrors ();
if(username==null || username.length()<0){
errors.add("unameisnull",new ActionMessgae("error.validate.unull"));
}
return errors;
}
2)資源文件ApplicationResources.properties
error.validate.unull=usernaem is null
3)在config.xml的<action-mappings>中<action>加入validate="true"屬性
4)頁(yè)面標(biāo)簽
<html:errors/>
----------------------------------------------------
validate驗(yàn)證框架
1 創(chuàng)建form繼承ValidatorForm或用DynaValidatorForm
2 在WEB-INF下創(chuàng)建validator-rules.xml和validation.xml
3 在src下創(chuàng)建資源文件ApplicationResources.properties
4 要struts-config.xml中配
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
5 編寫(xiě)validation.xml文件
<formset>
<form name="userForm">
<field property="username" depends="required">
<arg key="lable.username"/>
</field>
</form>
</formset>
6 頁(yè)面使用<html:errors/>標(biāo)簽
struts標(biāo)簽的使用和配置
配置:
1 在struts-config.xml文件中加入(可以到示例中的struts-config.xml文件中復(fù)制)
<message-resources parameter="MessageResources" />
2 在示例的src下拷貝MessageResources.properties文件到項(xiàng)目src下
3 在頁(yè)面引入就可使用
<%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean"%>
說(shuō)明:第1,2步為struts的國(guó)際化資源束文件引入,第3為標(biāo)簽引入
-----------------------------------------------------------------------------
Bean標(biāo)記
bean:define
從已有的變量或者變量的屬性來(lái)定義一個(gè)新的變量。
<bean:define id="新定義的變量名" scope="原變量的scope" name="原變量名" toScope="新定義變量的scope"></bean:define>
<bean:define id="新定義的變量名" scope="原變量的scope" name="原變量名" property="原變量的屬性名" toScope="新定義變量的scope"></bean:define>
bean:write
<bean:write scope="變量的scope" name="變量名" property="變量的屬性名" filter="是否按html格式輸出(默認(rèn)true為文本輸出)" format="數(shù)字(###,###.0000)日期(yyyy-MM-dd HH:mm:ss)"/>
結(jié)構(gòu)數(shù)據(jù)中多重屬性可用"."作導(dǎo)航取出來(lái)
bean:message
相當(dāng)于jstl中<fmt:message>(國(guó)際化標(biāo)簽)
1 定義資源文件
com.itcast.ApplicationResources.properties
com.itcast.ApplicationResources_zh_CN.properties
2 在struts-config中添加:
<message-resources parameter="ApplicationResources" key="myKey" />
3 頁(yè)面中使用
<bean:message bundle="myKey" key="userName"/>
<bean:message bundle="myKey" key="password"/>
bean:size標(biāo)簽
--------------------------------------------------------------
logic標(biāo)記
logic:empty/login:notEmpty 判斷對(duì)象是否為空
<logic:empty name="對(duì)象名" property="屬性名" scope="對(duì)象的scope">
為空<br>
</logic:empty>
logic:notEmpty 判斷對(duì)象是否不為空
<logic:notEmpty name="對(duì)象名" property="屬性名" scope="對(duì)象的scope">
不為空<br>
</logic:notEmpty>
logic:present 判斷對(duì)象是否存在(用方同上)
logic:notPresent
----------------------------------------------||
例子:
request.setAtrribute("attr1",null);
request.setAtrribute("attr2","");
request.setAtrribute("attr3",new ArrayList());
<logic:empty name="attr1">
11<br>
</logic:empty>
<logic:notEmpty name="attr1">
12<br>
</logic:notEmpty>
<logic:present name="attr1">
13<br>
</logic:present>
<logic:notPresent name="attr1">
14<br>
</logic:notPresent>
<logic:empty name="attr2">
21<br>
</logic:empty>
<logic:notEmpty name="attr2">
22<br>
</logic:notEmpty>
<logic:present name="attr2">
23<br>
</logic:present>
<logic:notPresent name="attr2">
24<br>
</logic:notPresent>
<logic:empty name="attr3">
31<br>
</logic:empty>
<logic:notEmpty name="attr3">
32<br>
</logic:notEmpty>
<logic:present name="attr3">
33<br>
</logic:present>
<logic:notPresent name="attr3">
34<br>
</logic:notPresent>
結(jié)果:
11空
14不存在
21空
23存在
31空
33存在
-----------------------------------------||
html:equal/html:notEqual
html:greaterEqual大于等于
html:greaterThan大于
html:lessEqual小于等于
html:lessThan小于
-----------------------------------------||
logic:iterate(循環(huán))
name:對(duì)應(yīng)的bean,是一個(gè)集合類(lèi)型
property:對(duì)應(yīng)的集合類(lèi)型的屬性
scope:變量的scope
id:臨時(shí)變量名
offset:循環(huán)起始位置
indexId:集合中當(dāng)前無(wú)素的下標(biāo)
length:控制長(zhǎng)度
單循環(huán)
<logic:iterate id="username" scope="request" name="對(duì)應(yīng)的bean,是一個(gè)集合類(lèi)型">
output every username:${username }<br>
</logic:iterate>
雙循環(huán)
<logic:iterate id="user" scope="request" name="list" offset="2" indexId="i">
${user.username }<br>
<logic:iterate id="love" name="user" property="loves">
${love }
</logic:iterate><br>
</logic:iterate><br>
logic:
tiles標(biāo)記
----------------------------------------------------------------
html標(biāo)簽
<html:form action="/login" method="post">
username:<html:text property="username" value="123"/>
password:<html:password property="password"/>
sex:<html:radio property="sex" value="0" />男
<html:radio property="sex" value="1" />女
likes:<html:checkbox property="0" value="0">吃飯</html:checkbox>
<html:checkbox property="0" value="1">吃飯</html:checkbox>
xueli:<html:select property="xueli">
<html:option value="0">小學(xué)</html:option>
<html:option value="1">小學(xué)</html:option>
<html:optionsCollection property="qxlist" label="qx" value="qxid"/>
//<html:optionsCollection name="qxlist" label="qx" value="qxid"/>
1.
</html:select>
<html:submit value="提交"/>
</html:form>
struts validator驗(yàn)證框架
1 配置:
* 加入國(guó)際化配置在struts-config.xml文件中,如:
<message-resources parameter="MessageResources"/>
* 提供國(guó)際化資源文件
* 引入validator插件在struts-config.xml文件中,如:
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set=property
property="pathnames"
value="WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"
/>
</plug-in>
* 提供validator.xml和validator_rules.xml文件,將此文件拷貝到WEB-INF下
2 validator服務(wù)器驗(yàn)證
* 配置validation.xml文件
3 validator客戶(hù)驗(yàn)證(javascript)
* 配置validation.xml文件
* 在jsp頁(yè)面中包含<html:javascript>
* 對(duì)需要驗(yàn)證的表單定義onsubmit事件,其中事件名稱(chēng)為validate+ActionForm的名稱(chēng),如:validateLogin