web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" 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">
<display-name>Spring</display-name>
<filter>
<filter-name>characterEncodingFilter</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>-->
<!--<filter-name>openSessionInViewFilter</filter-name>-->
<!--<filter-class>org.springframework.orm.hibernate4.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>-->
<!--<init-param>-->
<!--<param-name>flushMode</param-name>-->
<!--<param-value>AUTO</param-value>-->
<!--</init-param>-->
<!--</filter>-->
<!---->
<!--<filter-mapping>-->
<!--<filter-name>openSessionInViewFilter</filter-name>-->
<!--<url-pattern>/*</url-pattern>-->
<!--</filter-mapping>-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- spring需要拦截的url -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:dispatcher-servlet.xml,
/WEB-INF/applicationContext.xml
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.json</url-pattern>
</servlet-mapping>
<jsp-config>
<taglib>
<taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/tld/c.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://java.sun.com/jsp/jstl/fmt</taglib-uri>
<taglib-location>/WEB-INF/tld/fmt.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://www.ccstarsoft.com/taglib</taglib-uri>
<taglib-location>/WEB-INF/tld/cs.tld</taglib-location>
</taglib>
</jsp-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
springmvc 的配置文件 dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- 异常处理 -->
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 根据不同的Exception跳转到不同的页面去 -->
<prop key="java.sql.sqlException">exsql</prop>
<prop key="java.sql.IOException">exio</prop>
</props>
</property>
</bean>
<!-- 视图解析 -->
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="html" value="text/html" />
<entry key="json" value="application/json" />
</map>
</property>
<property name="viewResolvers">
<list>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean id="jsonView"
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
</bean>
</list>
</property>
</bean>
<!--
国际化 context.getMessage("key",obj,Locale.US); 其中obj代表配置文件中的参数
如:useruser=user {0} login at {1}
-->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>messages</value>
</property>
</bean>
<!-- 设置action默认执行的方法 -->
<bean id="paraMethodResolver"
class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName">
<value>method</value>
</property>
<property name="defaultMethodName">
<value>list</value>
</property>
</bean>
<!-- url映射配置 -->
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/hellouser.do">helloAction</prop>
<prop key="/usercontroller.do">userController</prop>
<prop key="/usercontroller.json">jsonController</prop>
</props>
</property>
</bean>
<!-- action配置 -->
<bean id="helloAction" class="com.tao.test.HelloAction">
<property name="helloWord">
<value>Hello!</value>
</property>
<!--
基于前面的设置,这里只要指定名称就可以 自动定位到/WEB-INF/jsp/index.jsp
-->
<property name="viewPage">
<value>test</value>
</property>
</bean>
<bean id="userController" class="com.hebsun.controller.UserController">
<property name="methodNameResolver">
<ref bean="paraMethodResolver" />
</property>
<property name="userService" ref="userServiceImpl"></property>
</bean>
<bean id="jsonController" class="com.hebsun.controller.JsonController">
<property name="methodNameResolver">
<ref bean="paraMethodResolver" />
</property>
<property name="userService" ref="userServiceImpl"></property>
</bean>
</beans>
applicationContext.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:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
xmlns:tool="http://www.springframework.org/schema/tool" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tool
http://www.springframework.org/schema/tool/spring-tool.xsd"
default-lazy-init="true" default-autowire="byName">
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="oracle.jdbc.driver.OracleDriver">
</property>
<property name="jdbcUrl" value="jdbc:oracle:thin:@127.0.0.1:1521:xe">
</property>
<property name="user" value="ecdev"></property>
<property name="password" value="ecdev"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionfactorybean"
scope="prototype">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.Oracle10gDialect
</prop>
<prop key="hibernate.show_sql">
true
</prop>
<prop key="hibernate.current_session_context_class">
org.springframework.orm.hibernate4.SpringSessionContext
</prop>
<prop key="hibernate.hbm2ddl.auto">
update
</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="transactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager">
<ref local="transactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="register">PROPAGATION_required</prop>
<!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到 -->
<prop key="get*">PROPAGATION_required,readOnly</prop>
<prop key="find*">PROPAGATION_required,readOnly</prop>
<prop key="select*">PROPAGATION_required,readOnly</prop>
<prop key="query*">PROPAGATION_required,readOnly</prop>
<prop key="sync*">PROPAGATION_required</prop>
<prop key="finish*">PROPAGATION_required</prop>
<prop key="add*">PROPAGATION_required</prop>
<prop key="insert*">PROPAGATION_required</prop>
<prop key="edit*">PROPAGATION_required</prop>
<prop key="update*">PROPAGATION_required</prop>
<prop key="save*">PROPAGATION_required</prop>
<prop key="remove*">PROPAGATION_required</prop>
<prop key="delete*">PROPAGATION_required</prop>
<prop key="*">PROPAGATION_required,-java.lang.Exception</prop>
</props>
</property>
</bean>
<!--autoproxy 自动创建代理-->
<bean id="ProxyCreator"
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>*Dao</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
</list>
</property>
<property name="proxyTargetClass" value="true" />
</bean>
<bean id="userDaoImpl" class="com.hebsun.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="userServiceImpl" class="com.hebsun.service.impl.UserServiceImpl">
<property name="userDao" ref="userDaoImpl"></property>
</bean>
</beans>
hibernate.xml
<?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>
<!--<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>-->
<!--<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:xe</property>-->
<!--<property name="connection.username">ecdev</property>-->
<!--<property name="connection.password">ecdev</property>-->
<!--<property name="connection.pool_size">1</property>-->
<!--<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>-->
<!--<property name="current_session_context_class">thread</property>-->
<!--<property name="current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</property>-->
<!--<property name="show_sql">true</property>-->
<!--<property name="hbm2ddl.auto">update</property>-->
<property name="hibernate.temp.use_jdbc_Metadata_defaults">false</property>
<mapping resource="com/hebsun/model/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
说明:不能在hibernate里配置数据库连接.必须使用datasource来搞定.有人说暂时spirng还没整合4.0以上.org.springframework.orm.hibernate4.LocalSessionfactorybean不支持在hibernate的配置文件里配置数据库.如果有谁有解决办法,还请不吝赐教
package com.hebsun.dao.impl;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.sqlQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import com.hebsun.dao.UserDao;
import com.hebsun.model.User;
public class UserDaoImpl implements UserDao{//extends HibernateDaoSupport
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public void insertUser(User user) {
this.sessionFactory.getCurrentSession().saveOrUpdate(user);
}
@Override
public void updateUser(User user) {
// TODO Auto-generated method stub
}
@Override
public void deleteUser(User user) {
// TODO Auto-generated method stub
}
public List<User> findAll(){
Session session = sessionFactory.openSession();
Transaction tran = session.beginTransaction();
Query query = session.createsqlQuery(SELECT_ALL_USER).addEntity(User.class);
tran.commit();
List<User> list = query.list();
return list;
}
}
package com.hebsun.service.impl;
import java.util.ArrayList;
import java.util.List;
import com.hebsun.dao.UserDao;
import com.hebsun.model.User;
import com.hebsun.service.UserService;
public class UserServiceImpl implements UserService{
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public List<User> findUsers() {
// TODO Auto-generated method stub
List<User> list = userDao.findAll();
return list;
}
}
接口的就不贴了,我猜只要做java的,不会不知道接口和实现类的关系吧?
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.hebsun.model.User" table="test_user">
<id name="id" type="java.lang.Integer">
<column name="id"></column>
<generator class="increment"></generator>
</id>
<property name="username" type="java.lang.String">
<column name="username" length="50" />
</property>
<property name="password" type="java.lang.String">
<column name="password" length="50"/>
</property>
<property name="address" type="java.lang.String">
<column name="address" length="50"/>
</property>
<property name="age" type="java.lang.Integer">
<column name="age" length="3"/>
</property>
</class>
</hibernate-mapping>
package com.hebsun.model;
public class User {
private int id;
private String username;
private String password;
private String address;
private Integer age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
package com.hebsun.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.hebsun.model.User;
import com.hebsun.service.UserService;
public class UserController extends MultiActionController{
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public ModelAndView list(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
// TODO Auto-generated method stub
//List<User> userList = userService.findUsers();
//ModelAndView类在SpringMVC中是一个很重要的概念
//控制器执行方法都必须返回一个ModelAndView,ModelAndView对象保存了视图以及视图显示的模型数据
//第一个参数:视图组件的逻辑名称。这里视图的逻辑名称是userlist,视图解析器会使用该名称查找实际的View对象
//第二个参数:传递给视图的,模型对象的名称
//第三个参数:传递给视图的,模型对象的值
//return new ModelAndView("userlist","users",userList);
return new ModelAndView("userlist");
}
}
package com.hebsun.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.hebsun.model.User;
import com.hebsun.service.UserService;
public class JsonController extends MultiActionController{
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public ModelAndView list(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
List<User> userList = userService.findUsers();
return new ModelAndView("test1","items",userList);
}
}
还有写的测试类:
package com.tao.test;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class HelloAction extends AbstractController{
private String helloWord;
private String viewPage;
public String getHelloWord() {
return helloWord;
}
public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
public String getViewPage() {
return viewPage;
}
public void setViewPage(String viewPage) {
this.viewPage = viewPage;
}
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
// TODO Auto-generated method stub
System.out.println("ppppppp--->"+helloWord);
System.out.println("ppppppp--->"+viewPage);
return new ModelAndView(viewPage,helloWord);
}
}
package com.tao.test;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import com.hebsun.model.User;
public class TestMain {
/**
* @param args
*/
public static void main(String[] args) {
Session session = new Configuration().configure().buildSessionFactory().openSession();
User user11 = new User();
session.beginTransaction();
user11.setId((int)Math.random()*10000);
user11.setUsername("张起灵");
user11.setPassword("02200059");
user11.setAddress("阴山古楼");
user11.setAge(27);
session.save(user11);
session.getTransaction().commit();
session.close();
}
}
package com.tao.test;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.hebsun.dao.UserDao;
import com.hebsun.model.User;
public class TestSpring {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx = new FileSystemXmlApplicationContext(
"/WebContent/WEB-INF/applicationContext.xml");
UserDao userDao = (UserDao)ctx.getBean("userDaoImpl");
List<User> list = userDao.findAll();
System.out.print("list-->"+list);
}
}
/web-inf/jsp/userlist.jsp
<%@ page language="java" contentType="text/html; charset=GBK"
pageEncoding="GBK"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!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=GBK">
<title>Insert title here</title>
<style type="text/css">
@import "dojoroot/dojox/grid/resources/tundraGrid.css";
@import "dojoroot/dijit/themes/tundra/tundra.css";
@import "dojoroot/dojo/resources/dojo.css";
</style>
<script type="text/javascript" src=\'#\'" /dojo/dojo.js"
djconfig="parSEOnLoad:true"></script>
<script>
dojo.require("dojo.parser");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojox.grid.DataGrid");
</script>
</head>
<body class="tundra">
<div dojoType="dojo.data.ItemFileReadStore" jsId="wishStore" url="usercontroller.json"></div>
<table dojoType="dojox.grid.DataGrid" store="wishStore" style ="width:500px;height:600px">
<thead>
<tr>
<th field="id">序号</th>
<th field="username">姓名</th>
<th field="password">密码</th>
<th field="age">年龄</th>
<th field="address">地址</th>
<th field="address">地址</th>
</tr>
</thead>
</table>
</body>
</html>
好了,基本就是这样了