转载:
http://download.csdn.net/source/245338
1. Jdbc的六个编程步骤
1. 注册一个驱动
注册驱动程序有三种方式: 方式一:Class.forName(“oracle.jdbc.driver.OracleDriver”);
JAVA 规范中明确规定:所有的驱动程序必须在静态初始化代码块中将驱动
注册到驱动程序管理器中。
方式二:Driver drv = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(drv);
方式三:编译时在虚拟机中加载驱动
javac –Djdbc.drivers = oracle.jdbc.driver.OracleDriver xxx.java
java –D jdbc.drivers=驱动全名 类名
使用系统属性名,加载驱动 -D 表示为系统属性赋值
附 : mysql 的 Driver 的全名 com.mysql.jdbc.Driver
SQLServer 的 Driver 的全名 com.microsoft.jdbc.sqlserver.SQLServerDriver
2. 取得一个连接
Conn = DriverManager.getConnection(jdbcURL,userName,password);
3. 获得一个Statement声明对象
Statement st = conn.createStatement();
PreparedStatement ps = conn.prepareStatement(sql);
CallableStatemetn cs = conn.prepareCall(sql);
4. 通过Statement对象执行Sql语句
sta.execute(String sql); 如果返回一个结果集则返回true,否则返回false。
sta.executeQuery(String sql);返回一个查询结果集。
sta.executeUpdate(String sql);返回值为 int 型,表示影响记录的条数。
将 sql 语句通过连接发送到数据库中执行,以实现对数据库的操作。
5. 若有结果集ResultSet则处理结果集
ResultSetMetaDate rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
While(rs.next()){
for(int i = 1; i <= columnCount; i++)
{
if(i != 1) System.out.print(",");
String name = rsmd.getColumnName(i); //取得第i列的列名称
String value = rs.getString(i); //取得第i列的值
System.out.print(name + "=" + value);
}
}
6. 关闭资源
2. 第一个Jdbc程序
public class AccountDaoBad
{
public void select()
{
Connection con = null;
Statement st = null;
ResultSet rs = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
/** static init block in OracleDriver*/
String jdbcURL = “jdbc:oracle:thin:@192.168.0.5:1521:tarena”;
con = DriverManager.getConnection(jdbcURL, "sd0703", "sd0703");
st = con.createStatement();
System.out.println(st.getFetchSize());
String sql = "select id,no,owner,pwd,cdate,balance from sd0703_account";
rs = st.executeQuery(sql);
while(rs.next())
{
System.out.print("id=" + rs.getInt(1));
System.out.print(",no=" + rs.getString(2));
System.out.print(",owner=" + rs.getString(3));
System.out.print(",pwd=" + rs.getString(4));
System.out.print(",cdate=" + rs.getDate(5));
System.out.println(",balance=" + rs.getDouble(6));
}
}catch(SQLException e)
{
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}catch(ClassNotFoundException e)
{
e.printStackTrace();
throw new RuntimeException(e.getMessege());
}finally
{
try{ con.close();}catch(Exception e) {e.printStatckTrace();}
}
}
3. 常用类
1. Connection, Statement, ResultSet,
4. 2.0新特性
(1)事务管理与图片的存储
public class ImageLibraryService
{
public void addImage(long id, String imageName, String path) throws SQLException
{
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
con = ConnectionFactory.getConnection();
con.setAutoCommit(false);
String sql = "insert into ImageLibrary(id, name, image)";
sql += " VALUES(?, ?, empty_blob())";
ps = con.prepareStatement(sql);
ps.setLong(1, id);
ps.setString(2, imageName);
ps.executeUpdate();
ps.close();
ps = con.prepareStatement("select image from ImageLibrary WHERE id = ? for update ");
ps.setLong(1, id);
rs = ps.executeQuery();
if (rs.next())
{
Blob image = rs.getBlob(1);
OutputStream out = image.setBinaryStream(0);
BufferedOutputStream bufferedOut = new BufferedOutputStream(out);
BufferedInputStream bufferedIn = new BufferedInputStream(new FileInputStream(path));
int c;
while ((c = bufferedIn.read()) != -1)
{
bufferedOut.write(c);
}
bufferedIn.close();
bufferedOut.close();
}
con.commit();
} catch (Exception e)
{
e.printStackTrace();
try
{
con.rollback();
} catch (SQLException se) { }
throw new SQLException(e.getMessage());
} finally
{
JdbcUtil.close(rs, ps, con);
}
}
//以下代码没有进行细致的异常捕获
public void restoreImage(long id, String filename) throws Exception
{
Connection con = ConnectionFactory.getConnection();
Statement st = con.createStatement();
String sql = "SELECT image From ImageLibrary Where id = " + id;
ResultSet rs = st.executeQuery(sql);
while (rs.next())
{
Blob image = rs.getBlob("image");
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
BufferedInputStream in = new BufferedInputStream(image.getBinaryStream());
int c;
while ((c = in.read()) != -1) out.write(c);
in.close();
out.close();
}
}
}
(2)结果集游标的上下游动
con = ConnectionFactory.getConnection();
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
String sql = "select id,no,owner,pwd,cdate,balance from sd0703_account";
rs = st.executeQuery(sql);
rs.afterLast(); //将光标移动到此 ResultSet 对象的末尾,正好位于最后一行之后。
while(rs.previous())
{
System.out.print("id=" + rs.getInt(1));
System.out.print(",no=" + rs.getString(2));
System.out.print(",owner=" + rs.getString(3));
System.out.print(",pwd=" + rs.getString(4));
System.out.print(",cdate=" + rs.getDate(5));
System.out.println(",balance=" + rs.getDouble(6));
}
注:ResultSet静态常量字段(参见javax.sql.ResultSet)
ResultSet.TYPE_SCROLL_INSENSITIVE
该常量指示可滚动但通常不受 ResultSet 底层数据更改影响的 ResultSet 对象的类型。
ResultSet.CONCUR_READ_ONLY
该常量指示不可以更新的 ResultSet 对象的并发模式。
Hibernate部分
1. 两种配置文件
Hibernate配置文件如下:
<?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">
<hibernate-configuration>
<session-factory>
<!-- MySQL connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1:3306/shopping_cart</property>
<property name="connection.username">chujq</property>
<property name="connection.password">7729</property>
<!--使用数据源-->
<!-->
<property name="connection.datasource">java:comp/env/jdbc/mysql</property>
-->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider</property>
<mapping resource="com/chu/shopping/model/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
在以上的配置文件中的内容包括以下部分:
(1) 配置数据库连接的信息以及数据库使用的言
(2) 运行中SQL语句的显示与格示
(3) 是否使用缓存
(4) 映射类配置文件
(5) 若在META-INF的context.xml中配置数据源则使用:
<property name="connection.datasource">java:comp/env/jdbc/mysql</property>
Context.xml文件如下:
<Context>
<Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource"
maxActive="10" maxIdle="5" maxWait="-1"
username="root" password="1234" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=gbk"/>
</Context>
类映射文件Student.hbm.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.allanlxf.hbn.o2o">
<class name="Car" table="car_o2o_pk">
<id name="id" column="id" type="integer">
<generator class="native" />
</id>
<property name="name" column="name" type="string"/>
<property name="manufacture" column="manufacture" type="string"/>
<one-to-one name="engine" class="Engine" cascade="all"/>
</class>
</hibernate-mapping>
2. Hibernate的编程步骤
具体可以分为以下七个步骤:
1.Configuration = new Configuration();
2.SessionFactory sessionFactory = config.configure().buildSessionFactory();
3.Session session = sessionFactory.openSession();
4.Transaction trans = session.beginTrasation();
5.Session.save(),session.update(),session.createQuery(hql).executeUpdate()等
6.trans.commit()或发生异常时执行trans.rollback()
7.session.close()
说明:其中第五步的session操作可以按以下两种方式进行:
(1)先得到一个Query,再通过Query来执行相关操作,如query.list(), query.setString().executeUpdate()
hql = "delete from Order where id = :id";
session.createQuery(hql).setInteger("id", 1).executeUpdate();
(2)直接操作session.save(),session.update(),session.delete(),session.get().
session.load(),session.saveOrUpdate()
String hql = "update Employee e set e.salary = e.salary + 1000";
query.executeUpdate(hql);
3. 5种ID策略
下面以表一个用户名为例:
<id name=”id” column=”id” type=”integer”>
<!-- Id的相关生成策略,有时需要相应参数à
<generator class=”XXX” > //ID的生成方式
</generator>
</id>
其中配置文件中的ID生成策略有:
1.通用策略
<generator class="native" />
说明:Mysql中应将id列定义为auto_increment, SQL Server中定义为identity(1,1)
Oracle中应有名为Hibernate_sequence的sequence。
2.<generator class=”identity”/>
说明:仅适用于Mysql和SQL server.
Mysql中应将id列定义为auto_increment, SQL Server中定义为identity(1,1)
3. <generator class=”hilo”>
<param name=”table”>id_values</param>
<param name=”column”>current_id</param>
<param name=”max_lo”>10</param>
</generator>
说明:在数据库有一个单行单列(current_id)的表(id_values)用于存储一个高位值。
4. <generator class=”sequence”>
<param name=”sequence”>users_sc_se</param>
</generator>
说明:仅适用于支持sequence的数据库,如:Oracle,DB2
5.<generator class="seqhilo">
<param name="sequence">users_sc_se</param>
<param name="max_lo">10</param>
</generator>
说明:(1)sequence的作用相当于使用hilo中表id_values中所存储的currentid,
(2)适用于支持sequence的数据库,如:Oracle,DB2
4. 3种映射关系
1. 一对一关联
1.1 共享主键
一个表使用的主键引用另一个表的主键,而不是自己产生的。也就是说一个表主键的产生要依赖另外一个表的主键。所以:
对表中记录而言,只有主表中有相应记录,其从表才可以有记录并使用主表的主键
对类对象而言只有被参照的对象存在了,才能创建参照对象
(1)建表
假设有汽车和引擎两个实体,它们存在着一对一的关系,我们可以通过共享主键来建立两者的关系。其DDL语名如下:
(2)写对象关系映射文件car.hbm.xml和Engine.hbm.xml
汽车类的配置文件:Car.hbm.xml
<hibernate-mapping package="com.allanlxf.hbn.o2o">
<class name="Car" table="car_o2o_pk">
<id name="id" column="id" type="integer">
<generator class="native" />
</id>
<property name="name" column="name" type="string"/>
<property name="manufacture" column="manufacture" type="string"/>
<one-to-one name="engine" class="Engine" cascade="all"/>
</class>
</hibernate-mapping>
引擎类的配置文件:Engine.hbm.xml
<hibernate-mapping package="com.allanlxf.hbn.o2o">
<class name="Engine" table="engine_o2o_pk">
<id name="id" column="id" type="integer">
<generator class="foreign">
<param name="property">car</param>
</generator>
</id>
<property name="model" column="model" type="string"/>
<property name="manufacture" column="manufacture" type="string"/>
<one-to-one name="car" class="Car" constrained="true" foreign-key="fk_engine_car_pk"/>
</class>
</hibernate-mapping>
说明:id产生器中指明了使用foreign方式产生,参数指出使用属性car的相关内容。
在<one-to-one>节中的car属性就是generator参数中的car.该节把类Car对应的表与Engine对就的表关联起来。注意配置文件的依据依然是Car类与Engine类定义的各个属性。
1.2 使用外键关联
(1)建表
(2) 写对象关系映射文件
汽车类的配置文件:Car.hbm.xml
<hibernate-mapping package="com.allanlxf.hbn.o2o">
<class name="Car" table="car_o2o_fk">
<id name="id" column="id" type="integer">
<generator class="native" />
</id>
<property name="name" column="name" type="string"/>
<property name="manufacture" column="manufacture" type="string"/>
<one-to-one name="engine" class="Engine" property-ref="car" cascade="save-update"/>
</class>
</hibernate-mapping>
注:其中property-ref="car" 指定关联类Engine类的car属性与本类主键对应。如果没有指定,会使用对方关联类 Engine的主键关联。它是可选的。
Cascade=”save_update”指出删除不级联。
引擎类的配置文件:Engine.hbm.xml
<hibernate-mapping package="com.allanlxf.hbn.o2o">
<class name="Engine" table="engine_o2o_fk">
<id name="id" column="id" type="integer">
<generator class="native" />
</id>
<property name="model" column="model" type="string"/>
<property name="manufacture" column="manufacture" type="string"/>
<many-to-one name="car" class="Car" column="carid"/>
</class>
</hibernate-mapping>
本身属性car可以多对一。但时在表中使用了Unique限制,且在Car.hbm.xml中也使用了<one-to-one>进行了限制.
2. 一对多关联
使用订单(Order)与订单项(Item)作为模型来讨论。一个订单包含多个订单项。
单向关联:在单的一方不需要设置存放多方的集合属性。
双向关联:在单的一方需要有一个set属性来存储多的一方
(1)建表
(2)写对象关系映射文件
<hibernate-mapping package="com.allanlxf.hbn.o2m">
<class name="Order" table="order_o2m">
<id name="id" column="id" type="integer">
<generator class="sequence">
<param name="sequence">order_o2m_seq</param>
</generator>
</id>
<property name="no" column="no" type="string"/>
<property name="owner" column="owner" type="string"/>
<property name="sendDate" column="sdate" type="date"/>
<set name="items" cascade="all" inverse="true">
<key column="orderid" />
<one-to-many class="Item"/>
</set>
</class>
</hibernate-mapping>
注意:一定要加上inverse=”true”,来说明关联(那外键约束)只需一方来维护。当关联类Iitem改变时,不会调用Update来更新本类的主键。
建立关联时,只要在关联类中加入属性OrderId作为关联类表的外键,并以此来与本类关联。
<hibernate-mapping package="com.allanlxf.hbn.o2m">
<class name="Item" table="item_m2o">
<id name="id" column="id" type="integer">
<generator class="sequence">
<param name="sequence">item_m2o_seq</param>
</generator>
</id>
<property name="product" column="product" type="string"/>
<property name="price" column="price" type="double"/>
<property name="amount" column="amount" type="integer"/>
<many-to-one name="order" class="Order" column="orderid"/>
</class>
</hibernate-mapping>
3. 多对多关联
这时选择班级(TarenaClass)与课程(Course)的对应关系作为讲座多对多关系的模型,不同的班级开设不同的课程。
实质上多对多的关系就相当于两个一对多的关系。
(1)建表
(2) 写对象关系映射文件
<hibernate-mapping package="com.allanlxf.hbn.m2m">
<class name="Course" table="course_m2m">
<id name="id" column="id" type="integer">
<generator class="native" />
</id>
<property name="name" column="name" type="string"/>
<set name="classes" table="cl_cou_m2m" inverse="true">
<key column="courseid" />
<many-to-many class="TarenaClass" column="classid"/>
</set>
</class>
</hibernate-mapping>
<hibernate-mapping package="com.allanlxf.hbn.m2m">
<class name="TarenaClass" table="class_m2m">
<id name="id" column="id" type="integer">
<generator class="native" />
</id>
<property name="name" column="name" type="string"/>
<set name="courses" table="cl_cou_m2m">
<key column="classid" />
<many-to-many class="Course" column="courseid"/>
</set>
</class>
</hibernate-mapping>
说明: a.多对多有双向关联。
b. 多对多引用的是集合对象
c.需要用第三张表来维持多对多关系。
d.写配置文件的时候many-to-many标签要放在set标签内, <key column =””>总是和本类的主键id对应
d. 同样也要加上inverse=”true”,在多对多关联时,如果一方改变,则会另一方也会执行额外的操作来维护外键约束.应让一方来维护数据库的完整性即可。
Servlet部分
1. 第一个Servlet程序
package com.allanlxf.serv.basic;
import javax.servlet.*;
import java.io.*;
public class TimeServlet implements Servlet
{
private ServletConfig config;
public TimeServlet()
{
System.out.println("TimeServlet()");
}
public void init(ServletConfig config) throws ServletException
{
this.config = config;
System.out.println("init(" + config + ")");
}
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{
System.out.println(this);
System.out.println("service(" + request + "," + response + ")");
getServletConfig();
PrintWriter out = response.getWriter();
out.println("<h1>");
out.println(new java.util.Date());
out.println("</h1>");
out.close();
}
public void destroy()
{
System.out.println("destroy");
}
public String getServletInfo()
{
return "time servlet by allan version 1.0";
}
public ServletConfig getServletConfig()
{
return config;
}
}
2. 编写及布署Servlet类
(1)编写一个类继承自HttpServlet
package com.allanlxf.serv.basic;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HttpTimeServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>currentTime</title>");
out.println("</head>");
out.println("<body>");
out.println("<h3 align=\"center\">Current Time is</h3>");
out.println("<hr>");
out.println(new java.util.Date());
out.println("</body>");
out.println("</html>");
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}
(2)在Tomcat中布署一个myFirst-app web应用
---Tomcat
---webapps
---myFirst-app
---WEB-INF
---classes
---web.xml
---shoppingCart
(3)配置Web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<servlet>
<servlet-name>ActionServlet</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>time</servlet-name>
<servlet-class>com.allanlxf.serv.basic.TimeServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>HttpTimeServlet</servlet-name>
<servlet-class>com.allanlxf.serv.basic.HttpTimeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ActionServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>time</servlet-name>
<url-pattern>/basic/time</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>HttpTimeServlet</servlet-name>
<url-pattern>/basic/http/time</url-pattern>
</servlet-mapping>
<listener>
<listener-class>com.chu.shoppingCart.web.shoppingCartListner</listener-class>
</listener>
</web-app>
3. 常用类介绍
(1)Filter类
public class CharacterEncodingFilter implements Filter
{
private FilterConfig config;
public void init(FilterConfig config) throws ServletException
{
this.config = config;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
String encoding = config.getInitParameter("encoding");
if(encoding == null)
{
encoding = "gbk";
}
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
public void destroy()
{
}
}
Jsp部分
<%@page contentType="text/html;charset=gbk" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>ums-modify</title>
<link href="${pageContext.request.contextPath}/style/style.css" ref="stylesheet" type="text/css">
<script language="javascript" src="${pageContext.request.contextPath}/js/calendar.js">
</script>
<script languge="javascript">
<!--
function validate()
{
var element = getElementByName("realName");
if(element.value.length == 0)
{
alert("请输入真实姓名!");
element.focus();
return false;
}
return true;
}
-->
</script>
</head>
<body>
<jsp:include page="/header.jsp" />
<form onsubmit="return validate()" method="post" action="${pageContext.request.contextPath}/user/modify.do">
<table>
<td>${userInfo.userName}</td>
<td>男<input type="radio" name="gender" value="1" ${userInfo.gender == "1" ? "checked" : ""}> </td>
<td>
读书<input type="checkbox" name="hobbies" value="1" ${fn:contains(userInfo.hobbies,"1") ? "checked" : ""}>
足球<input type="checkbox" name="hobbies" value="2" ${fn:contains(userInfo.hobbies,"2") ? "checked" : ""}>
<td>
</table>
</form>
<table>
<c:forEach items="${users}" var="user" varStatus="status">
<tr><td aling="center">
${status.count} </td></tr>
<tr><td aling="center">
${user.userName}</td></tr>
<tr><td aling="center">
${user.gender == "1" ? "男" : "女"}</td></tr>
<tr><td aling="center">
<a href="${pageContext.request.contextPath}/admin/user/remove.do?id=${user.id}" onclick="return confirm('真的要删除该用户吗?')">删除</a>
</td>
</tr>
</c:forEach>
<c:if test="${empty users}">
<tr><td aling="center">
没有符合条件的用户 </td></tr>
</c:if>
</table>
<center>
<input class="button" type="button" value="返 回" onclick="self.location='${pageContext.request.contextPath}/admin/user/toquery.do'">
<input type="button" class="button" value="取 消" onclick="history.back()">
</center>
<jsp:include page="/footer.jsp" />
</body>
</html>
Struts部分
1.Stuts配置文件struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<action-mappings>
<action path="/listProduct" type="com.chu.shoppingCart.web.ProductAction">
<forward name="listProduct" path="/common/listProduct.jsp"/>
</action>
<action path="/cart/viewItems" type="com.chu.shoppingCart.action.CartAction" parameter="viewItems" >
<forward name="viewCart" path="/common/cart.jsp"/>
</action>
<action path="/cart/clearCart" type="com.chu.shoppingCart.action.CartAction" parameter="clearCart">
<forward name="viewCart" path="/cart/viewItems.do"/>
</action>
</action-mappings>
</struts-config>
2.实现类ProductAction.java
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;
import com.chu.shoppingCart.entity.*;
import com.chu.shoppingCart.service.*;
import com.chu.shoppingCart.service.impl.*;
public class CartAction extends MappingDispatchAction
{
public ActionForward viewItems(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
{
Cart cart = (Cart) request.getSession().getAttribute("cart");
if(cart == null){
cart = new Cart();
request.getSession().setAttribute("cart",cart);
}
CartService cartService = new CartServiceImpl(cart);
Collection<Item> items = cartService.getAllItems();
request.setAttribute("items", items);
return mapping.findForward("viewCart");
}
//方法名应与struts-config.xml中Action节中parameter="viewItems"相匹配
public ActionForward clearCart(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
{
}
}
3.
Web编程中常用代码片段
1. 工具类
1. ObjectFactory
public class ObjectFactory
{
private static Properties config = new Properties();
static{
InputStream in = ObjectFactory.class.getResourceAsStream("database-cfg.properties");
if(in == null) {
throw new ExceptionInInitializerError("no file:database-cfg.properties found error!");
}
try {
config.load(in);
in.close();
}catch(IOException e)
{
e.printStackTrace();
throw new ExceptionInInitializerError("failed to load file!");
}
}
public static Object newInstance(Class className)
{
return newInstance(className.getName());
}
public static Object newInstance(String className)
{
Object instance = null;
String configValue = config.getProperty(className);
try
{
instance = Class.forName(configValue).newInstance();
}catch(Exception e)
{
e.printStackTrace();
throw new RuntimeException("failed to create instance of Database");
}
return instance;
}
}
2. ConnectonFactoryForJdbc.java
package com.terana.jdbc.util;
import java.sql.*;
import java.io.*;
import java.util.Properties;
public class ConnectionFactory
{
private static Properties config = new Properties();
static
{
InputStream in = ConnectionFactory.class.getResourceAsStream("db-config.properties");
if(in == null)
{
throw new ExceptionInInitializerError("no file:db-config.properties found error!");
}
try
{
config.load(in);
in.close();
}catch(IOException e)
{
e.printStackTrace();
throw new ExceptionInInitializerError("failed to load file!");
}
}
public static Connection getConnection() throws SQLException
{
try
{
String driverClassName = config.getProperty("driverClassName");
String jdbcURL = config.getProperty("jdbcURL");
String userName = config.getProperty("userName");
String password = config.getProperty("password");
Class.forName(driverClassName);
return DriverManager.getConnection(jdbcURL, userName, password);
}catch(ClassNotFoundException e)
{
e.printStackTrace();
throw new SQLException(e.getMessage());
}
}
}
3. ResultSetUtil.java
public class ResultSetUtil
{
public static void printResult(ResultSet rs) throws SQLException
{
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
while(rs.next())
{
for(int i = 1; i <= columnCount; i++)
{
if(i != 1)
{
System.out.print(",");
}
String name = rsmd.getColumnName(i);
String value = rs.getString(i);
System.out.print(name + "=" + value);
}
System.out.println();
}
}
}
4. Hibernate分页代码
public Collection<Order> findByPage(int pageNo)
{
Session session = null;
Transaction trans = null;
Collection orders = null;
try
{
session = HibernateUtil.getSession();
trans = session.beginTransaction();
String hql = "from Order o order by o.id asc";
Query query = session.createQuery(hql);
query.setFirstResult((pageNo - 1) * ROW_PER_PAGE);
query.setMaxResults(ROW_PER_PAGE);
orders = query.list();
trans.commit();
} catch (Exception e)
{
e.printStackTrace();
trans.rollback();
} finally
{
session.close();
}
return orders;
}
5. HibernateUtil.java
public class HibernateUtil
{
private static SessionFactory sessionFactory;
static
{
try
{
Configuration config = new Configuration();
sessionFactory = config.configure().buildSessionFactory();
}catch(Throwable t)
{
t.printStackTrace();
throw new ExceptionInInitializerError();
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static Session getSession()
{
return sessionFactory.openSession();
}
}
6. shoppingCartListner
配置:web.xml中
<listener>
<listener-class>com.chu.shoppingCart.web.shoppingCartListner</listener-class>
</listener>
实现:
public class shoppingCartListner implements HttpSessionListener
{
public void sessionCreated(HttpSessionEvent envent)
{
HttpSession session = envent.getSession();
if (session.getAttribute("cart") == null)
{
Cart cart = new Cart();
session.setAttribute("cart", cart);
}
}
public void sessionDestroyed(HttpSessionEvent envent)
{
HttpSession session = envent.getSession();
session.removeAttribute("cart");
session.invalidate();
}
}
7. 重复提交问题
当用记注册时,先访问此页面,由此页面订位到注册页面
<%@page import="java.util.Random" %>
<%!
private int generateToken()
{
int token = Math.abs(new Random().nextInt() % 10000);
if(token < 1000)
{
token = token + 1000;
}
return token;
}
%>
<%!
private void saveToken(HttpServletRequest request)
{
String token = String.valueOf(generateToken());
request.getSession().setAttribute("token", token);
}
private boolean isTokenValid(HttpServletRequest request)
{
String originalToken = (String)request.getSession().getAttribute("token");
request.getSession().removeAttribute("token");
String token = request.getParameter("token");
if(token == null)
{
return false;
}
if(originalToken == null)
{
return false;
}
if(!token.equals(originalToken))
{
return false;
}
return true;
}
%>
<%
String path = "";
String action = request.getParameter("action");
if(action == null)
{
action = "toregister";
}
if(action.equals("toregister"))
{
saveToken(request);
path = "register.jsp";
}else if(action.equals("register"))
{
if(isTokenValid(request))
{
//save user to database.
request.setAttribute("message", "success");
}else
{
request.setAttribute("message", "token invalid");
}
path = "message.jsp";
}
%>
<jsp:forward page="<%= path%>" />
注册页面:registe.jsp
<form method="post" action="registerAction.jsp">
<input type="hidden" name="action" value="register">
userName:<input type="text" name="userName">
<input type="hidden" name="token" value="${token}">
<input type="submit" value="register">
</form>
8. JdbcUtilForContex.java
public static Connection getJndiConnection() throws SQLException
{
try
{
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/" + config.getProperty("jndiName"));
return ds.getConnection();
}catch(Exception e)
{
e.printStackTrace();
throw new SQLException(e.getMessage());
}
}