利用ajax获取网页表单数据,并存储到数据库之二(使用SSH)

时间:2024-01-21 18:33:52

上篇介绍了如何使用JDBC链接ORACLE数据库实现对数据库的增删改查,本例是使用框架SSH来对数据库的数据进行操作。

首先说框架,现在流行的框架很多,如Struts、Hibernate、Spring等,再加上各个公司自己编写的框架,可以说有很多。使用框架是为了使java语言更加规范化,或者说按照它既定的要求一步一步来建立工程,这使得程序更加简单。

利用ajax获取网页表单数据,并存储到数据库之二(使用SSH)

    图1-工程结构图

创建工程的过程已经不需要再细说了,由于使用框架就必须引入相应的jar包,这里导入spring,struts,hibernate的各种核心包。

由于这个例子与上一个例子实现的功能仙童,所以建表的过程就不再叙述了,建表完成以后首先创建两个model,这里一个是Price,另一个是User。这两个表中有各个表中的数据字段。

public class User {
private String user_id;
private String user_name;
private String user_email;
private String user_subject;
private String user_message;
//自动生成get,set方法和无参有参构造方法
}
public class Price {

    private String price_id;
private String price_name;
private String price_price;
private String price_list1;
private String price_list2;
private String price_list3;
private String price_list4;
private String price_list5;
//同样生成get,set方法与构造函数
}

两个javaBean建立以后就要建立相应的配置文件,也即建立User.hbm.xml与Price.HBM.xml两个配置文件。这主要是使用了hibernate的使用方法。在这两个配置文件中主要是对两个类中的数据字段进行配置,<hibernate-mapping>中包括其name,type等信息。不用多说,相信对大家来说so easy。

说到配置文件,再说一下这个dbConfig.properties文件,这个文件是对数据库进行配置,包括数据库的名字,用户名,密码等。

driver=oracle.jdbc.driver.OracleDriver
url=jdbc\:oracle\:thin\:@localhost\:1521\:ORACLE
userName=user2
password=12345

strut.properties文件是固定的基本不用改变。为了能够看懂我简单的注释了一些。

#是否为struts的开发模式
struts.devMode=true
#用URL扩展名来确定是否这个请求是被用作Struts action,其实也就是设置 action的后缀,例如login.do的'do'字。
struts.action.extension=action
#是否加载xml配置(true,false)
struts.configuration.xml.reload=true
#国际化信息内码
struts.i18n.encoding = utf-8
#com.opensymphony.xwork2.ObjectFactory接口(spring)
struts.objectFactory = spring
### valid values are: name, type, auto, and constructor (name is the default)
struts.objectFactory.spring.autoWire = name
#是否可以用替代的语法替代tags
struts.tag.altSyntax=true
# 不让标签自动生成html代码(没有用的,不可控的)
struts.ui.theme = simple

配置完成以后建立两个action,这两个action就是对数据库进行操作,这里PriceAction中定义了一个查询的方法,对数据库的数据进行查询并显示到html页面上。

package com.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import net.sf.json.JSONArray;
import com.model.Price;
import com.opensymphony.xwork2.ActionSupport;
import com.service.PriceService; public class PriceAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private PriceService priceService;
private List<Price> list;
private Price price; public void queryPrice() throws IOException {
list = priceService.queryPrice();
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray);
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/plain;charset=utf-8");
PrintWriter out=response.getWriter();
out.write(jsonArray.toString());
out.flush();
out.close();
} public PriceService getPriceService() {
return priceService;
} public void setPriceService(PriceService priceService) {
this.priceService = priceService;
} public List<Price> getList() {
return list;
} public void setList(List<Price> list) {
this.list = list;
} public Price getPrice() {
return price;
} public void setPrice(Price price) {
this.price = price;
}
}

这一部分的代码较长,但是总的来说就是一个queryPrice()方法。

package com.action;

import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.model.User;
import com.opensymphony.xwork2.ActionSupport;
import com.service.UserService; public class UserAction extends ActionSupport {
private UserService userService;
private List<User> list;
private User user =new User(); public UserService getUserService() {
return userService;
} public void setUserService(UserService userService) {
this.userService = userService;
} public List<User> getList() {
return list;
} public void setList(List<User> list) {
this.list = list;
} public User user() {
return user;
} public void setUser(User user) {
this.user = user;
} public void add() {
HttpServletRequest request = ServletActionContext.getRequest();
user.setUser_id(getUUID());
user.setUser_name(request.getParameter("user_name"));
user.setUser_email(request.getParameter("user_email"));
user.setUser_subject(request.getParameter("user_subject"));
user.setUser_message(request.getParameter("user_message"));
userService.addUser(user);
} public static String getUUID() {
return UUID.randomUUID().toString().replace("-", "");
}
}

UserAction代码也是一个add()方法,用于添加数据。

两个Service也是对简单服务的调用。

最主要的ajax与上一个案例一样,有想了解的请参考上一个用JDBC的案例。

SSH最重要的一系列的配置。

<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:dbConfig.properties</value>
</list>
</property>
</bean> <bean id="dataSource1" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName">
<value>${driver}</value>
</property>
<property name="url">
<value>${url}</value>
</property>
<property name="username">
<value>${userName}</value>
</property>
<property name="password">
<value>${password}</value>
</property>
</bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource">
<ref local="dataSource1"/>
</property>
<!-- hibernate实体类的配制文件 -->
<property name="mappingResources">
<list>
<value>com/model/Price.hbm.xml</value>
<value>com/model/User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.jdbc.batch_size">20</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean> <bean id="dao" class="com.dao.Dao">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean> <!-- 定义事务管理 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 定义事务管理拦截器 -->
<bean id="transactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributes">
<props>
<prop key="get*">readOnly</prop>
<prop key="query*">readOnly</prop>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
<!-- 定义代理自动管理事务 -->
<bean id="ProxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<!-- 指定需要Spring管理事务的Bean -->
<property name="beanNames">
<list>
<value>priceService</value>
<value>userService</value>
</list>
</property>
<!-- 调用事务管理拦截器 -->
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
</list>
</property>
</bean> <bean id="userAction" class="com.action.UserAction" singleton="false">
<property name="userService">
<ref local="userService"/>
</property>
</bean> <bean id="userService" class="com.service.UserService">
<property name="dao">
<ref local="dao"/>
</property>
</bean> <bean id="priceAction" class="com.action.PriceAction" singleton="false">
<property name="priceService">
<ref local="priceService"/>
</property>
</bean> <bean id="priceService" class="com.service.PriceService">
<property name="dao">
<ref local="dao"/>
</property>
</bean> </beans>

这段代码是applicationContext.xml,这其中配置了数据库,一系列的连接信息。还包括service与action,,和必要的事务管理拦截器等重要信息。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SSHWeb_demo01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- spring监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- spring集成hibernate3的过滤器 -->
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- struts2过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

web.xml配置监听器与过滤器。

总的来说,使用JDBC与SSH的区别在于:框架使得程序的结构性更强。