使用SSH框架时,找不到sessionFactory

maaaa5566 2012-11-15 02:01:42
在使用SSH框架的时候,运行时遇到这么一个错:Property 'sessionFactory' is required
我猜测是配置有问题,但不知道错在哪。
异常信息:
Messages: Property 'sessionFactory' is required
File: org/springframework/orm/hibernate3/HibernateAccessor.java
Line number: 314

Eclipse下 Struts2.3 + Spring3.0 + Hibernate3.6 ,这是导入的jar包:


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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="jdbcUrl" value="jdbc:sqlserver://localhost:1433;databaseName=test"></property>
<property name="user" value="sa"></property>
<property name="password" value="123"></property>
</bean>
<!-- Hibernate sessionFactory创建 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- Hibernate属性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<!-- 映射文件 -->
<property name="mappingResources">
<list>
<value>../User.hbm.xml</value>
</list>
</property>
</bean>

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<constructor-arg>
<ref local="sessionFactory" />
</constructor-arg>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="userDao" class="com.test.dao.impl.UserDaoImpl" scope="prototype">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="registerAction" class="com.test.actions.RegisterAction" scope="prototype">
<property name="ud" ref="userDao"></property>
</bean>
</beans>



UserDaoImpl.java
package com.test.dao.impl;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.test.entity.vo.User;
import com.test.interfaces.UserDao;

public class UserDaoImpl implements UserDao{

private HibernateTemplate hibernateTemplate = null;
private SessionFactory sessionFactory ;

public SessionFactory getSessionFactory() {
return sessionFactory;
}

public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

public HibernateTemplate getHibernateTemplate() {
if(hibernateTemplate == null){
hibernateTemplate = new HibernateTemplate(sessionFactory);
}
return hibernateTemplate;
}

@Override
public Long addUser(User user) {
// TODO Auto-generated method stub
return (Long)getHibernateTemplate().save(user);
}
}


RegisterAction.java
package com.test.actions;

import com.opensymphony.xwork2.ActionSupport;
import com.test.dao.impl.UserDaoImpl;
import com.test.entity.vo.User;
import com.test.interfaces.UserDao;

public class RegisterAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String password;
private UserDao ud = new UserDaoImpl();

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 UserDao getUd() {
return ud;
}
public void setUd(UserDao ud) {
this.ud = ud;
}

public String execute() throws Exception{
User user = new User();
user.setUsername(username);
user.setPassword(password);
ud.addUser(user);
return SUCCESS;
}
}
...全文
364 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
maaaa5566 2012-11-16
  • 打赏
  • 举报
回复
引用 6 楼 maaaa5566 的回复:
引用 1 楼 twqllq98849577 的回复: 让userDaoImpl继承HibernateDaoSupport public class userDaoImpl extends HibernateDaoSupport 再注入sessionfactory 加上以后,在调用getHibernateTemplate().save(user)时报了异常java.lang.NullPoin……
终于找到哪里错了,因为我最先用的是struts2,在配置struts.xml时,registerAction的class是com.test.actions.RegisterAction,而后来加入spring以后,需要把这个class和applicationContext.xml里registerAction的id改成一样的。。。问题解决。。。 多谢各位大虾!
dengxiong90 2012-11-16
  • 打赏
  • 举报
回复
配置文件里 <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <constructor-arg> <ref local="sessionFactory" /> </constructor-arg> </bean> 用<property>标签包含“sessionFactory”试试 如果继承了HibernateDaoSupport就可以直接Session session=getSession();貌似就不需要管SessionFactory了
dengxiong90 2012-11-16
  • 打赏
  • 举报
回复
配置文件里 <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <constructor-arg> <ref local="sessionFactory" /> </constructor-arg> </bean> 用<property>标签包含“sessionFactory”试试 如果继承了HibernateDaoSupport就可以直接Session session=getSession();貌似就不需要管SessionFactory了
maaaa5566 2012-11-16
  • 打赏
  • 举报
回复
引用 1 楼 twqllq98849577 的回复:
让userDaoImpl继承HibernateDaoSupport public class userDaoImpl extends HibernateDaoSupport 再注入sessionfactory
加上以后,在调用getHibernateTemplate().save(user)时报了异常java.lang.NullPointerException
zxj828282 2012-11-16
  • 打赏
  • 举报
回复
top top top
s478853630 2012-11-15
  • 打赏
  • 举报
回复

package com.unite.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import com.unite.dao.BaseDao;
import com.unite.dao.PageDao;
import com.unite.entity.PageModel;

/**
 * @see 访问数据库的基类dao实现类
 * @version 1.0
 * */
public abstract class BaseDaoImpl<T extends Serializable> extends PageDao implements BaseDao<T>  {
	
	@Autowired
	private SessionFactory sessionFactory;
	private Session session;
	
	// 保存记录
	public T add(T entity) {
		getSession().save(entity);
		return entity;
	}
	
	// 修改记录
	public T edit(T entity) {
		getSession().update(entity);
		return entity;
	}

	// 删除记录
	public T del(Serializable id) {
		T entity = get(id);
		getSession().delete(entity);
		return entity;
	}

	// 根据ID获得记录
	@SuppressWarnings("unchecked")
	public T get(Serializable id) {
		try {
			return (T) getSession().get(getThisClass(), id);
		} catch (Exception e) {
			return null;
		}
	}
	
	// 获得表中的所有的实体
	@SuppressWarnings("unchecked")
	public List<T> getBeans() {
		String class1 = getThisClass().toString();
		String entity = class1.substring(class1.lastIndexOf(".") + 1);
		return (List<T>) getList("from " + entity + " order by id", null);
	}
	
	// 获得表中的下一个ID的值
	public Long getNextId() {
		Long result = 0l;
		try {
			String class1 = getThisClass().toString();
			String entity = class1.substring(class1.lastIndexOf(".") + 1);
			Object value = getObject("select max(id) from " + entity, null);
			if (null != value) {
				result = Long.parseLong(value.toString()) + 1;
			} else {
				result = 1l;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * @see 从数据库中获得一个实体类的集合或一列值
	 * @param hql hql语句
	 * @param args 参数列表(可以为null)
	 * @return List  不会为null
	 */
	@SuppressWarnings("unchecked")
	public List getList(String hql, Object[] args) {
		try {
			return getQuery(hql, args).list();
		} catch (Exception e) {
			e.printStackTrace();
			return new ArrayList();
		}
	}

	/**
	 * @see 从数据库中获得一个实体或一个值
	 * @param hql hql语句
	 * @param args 参数列表(可以为null)
	 * @return Object
	 */
	@SuppressWarnings("unchecked")
	public Object getObject(String hql, Object[] args) {
		List list = getList(hql, args);
		if (list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	/**
	 * @see 判断真假(数据库是否有这个记录)
	 * @param hql hql语句必须是select count(*) from ...
	 * @param args 参数列表(可以为null)
	 * @return Boolean
	 */
	public Boolean validate(String hql, Object[] args) {
		try {
			Object value = getObject(hql, args);
			if (null != value && Integer.parseInt(value.toString()) > 0) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * @see 获得分页
	 * @param hql hql语句必须是select * from ...或者from ...
	 * @param args 参数列表(可以为null)
	 * @param pageIndex 当前页数
	 * @param radix 分页的基数
	 * @return PageModel
	 * */
	public PageModel getPage(String hql, Object[] args, int pageIndex, int radix) {
		try {
			String countHql = "";
			if (hql.indexOf("*") != -1) {
				countHql = hql.replace("*", "count(*)");
			} else {
				countHql = "select count(*) " + hql;
			}
			Integer amount = Integer.parseInt(getObject(countHql, args).toString());
			PageModel model = getPageModel(amount, pageIndex, radix, radix);
			Query query = getQuery(hql, args);
			query.setFirstResult(model.getStart());
			query.setMaxResults(radix);
			model.setList(query.list());
			return model;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * @see 其他操作(增删改返回受影响的行数)
	 * @param hql hql语句
	 * @param args 参数列表(可以为null)
	 * @return Object
	 */
	public Integer other(String hql, Object[] args) {
		try {
			return getQuery(hql, args).executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}
	
	/**
	 * @see 搜索引擎
	 * @param hql hql语句
	 * @return List
	 */
	@SuppressWarnings("unchecked")
	public List<String> self(String hql) {
		try {
			Query query = getQuery(hql, null);
			query.setFirstResult(0);
			query.setMaxResults(15);
			return query.list();
		} catch (Exception e) {
			e.printStackTrace();
			return new ArrayList<String>();
		}
	}
	
	// 获得session
	private Session getSession() {
		if (null == session) {
			session = SessionFactoryUtils.getSession(sessionFactory, true);
		}
		return session;
	}
	
	// 获得Query
	private Query getQuery(String hql, Object[] args) {
		Query query = getSession().createQuery(hql);
		if (null != args && args.length > 0) {
			for (int i = 0; i < args.length; i++) {
				query.setParameter(i, args[i]);
			}
		}
		return query;
	}

	// 获得class
	@SuppressWarnings("unchecked")
	private Class<T> getThisClass() {
		return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
}

package com.unite.dao.impl;

import java.util.List;
import org.springframework.stereotype.Service;
import com.unite.dao.UserDao;
import com.unite.entity.PageModel;
import com.unite.entity.User;

/**
 * @version 1.0
 * 用户的dao接口实现类
 */
@Service
public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {

	// 用户登录
	public Boolean login(String userName, String password) {
		return validate("select count(*) from User where userName=? and password=?", new Object[]{ userName, password });
	}

	// 所有用户分页查询
	public PageModel getPage(Integer pageIndex, Integer radix) {
		return getPage("from User", null, pageIndex, radix);
	}

	// 更新用户
	public Integer updation(User user) {
		return other("update User set userName=?,password=? where id=?", new Object[]{ user.getUserName(), user.getPassword(), user.getId() });
	}

	// 检索用户名
	public List<String> selfion(String word) {
		return self("select userName from User where userName like '" + word + "%'");
	}

	// 根据用户名获得用户
	public User getUser(String userName) {
		return (User) getObject("from User where userName=?", new Object[]{ userName });
	}
	
}


<?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:context="http://www.springframework.org/schema/context" 
		xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
						http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
						http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
						http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
						http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd
						" default-lazy-init="true" default-autowire="byName">
	
	<context:component-scan base-package="com.unite" />
	
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		<property name="driverClass" value="com.mysql.jdbc.Driver" />
		<property name="jdbcUrl" value="jdbc:mysql://localhost/test?characterEncoding=UTF-8" />
		<property name="user" value="root" />
		<property name="password" value="123456" />
		<property name="autoCommitOnClose" value="true" />
		<property name="maxStatements" value="100" />
		<property name="checkoutTimeout" value="5000" />
		<property name="idleConnectionTestPeriod" value="3000" />
		<property name="initialPoolSize" value="3" />
		<property name="minPoolSize" value="3" />
		<property name="maxPoolSize" value="8" />
		<property name="maxIdleTime" value="7200" />
		<property name="acquireIncrement" value="5" />
		<property name="maxIdleTimeExcessConnections" value="1800" />
	</bean>
	
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingDirectoryLocations">
			<list>
				<value>classpath:/config/hibernate</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<value>
				hibernate.jdbc.batch_size=30
				hibernate.show_sql=true
				hibernate.format_sql=false
				hibernate.cache.use_query_cache=false
				hibernate.cache.use_second_level_cache=false
				hibernate.dialect=org.hibernate.dialect.MySQLDialect
				<!-- hibernate.hbm2ddl.auto=update -->
			</value>
		</property>
	</bean>

	<tx:annotation-driven transaction-manager="transactionManager" />
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	
	<!--  -->
	<dwr:configuration />
	<dwr:controller id="dwrController" debug="true" />
	<dwr:url-mapping />
	<dwr:annotation-scan base-package="com.unite" scanRemoteProxy="true" />
	
</beans>
Fly_m 2012-11-15
  • 打赏
  • 举报
回复
private UserDao ud = new UserDaoImpl(); public UserDao getUd() { return ud; } public void setUd(UserDao ud) { this.ud = ud; } 修改为 private UserDao userDao;//这里一定不要使用 new UserDaoImpl() public void setUserDao(UserDao userDao) { xxxxx } xxxGetUserDao
桃园闲人 2012-11-15
  • 打赏
  • 举报
回复
Dao 要继承 HibernateDaoSupport类。
twqllq98849577 2012-11-15
  • 打赏
  • 举报
回复
让userDaoImpl继承HibernateDaoSupport public class userDaoImpl extends HibernateDaoSupport 再注入sessionfactory
弃用了struts,用spring mvc框架做了几个项目,感觉都不错,而且使用了注解方式,可以省掉一大堆配置文件。本文主要介绍使用注解方式配置的spring mvc,之前写的spring3.0 mvc和rest小例子没有介绍到数据层的内容,现在这一篇补上。下面开始贴代码。 文中用的框架版本:spring 3,hibernate 3,没有的,自己上网下。 先说web.xml配置: [java] view plaincopy 01.<?xml version="1.0" encoding="UTF-8"?> 02. 03. s3h3 04. 05. contextConfigLocation 06. classpath:applicationContext*.xml 07. 08. 09. org.springframework.web.context.ContextLoaderListener 10. 11. 12. 13. spring 14. org.springframework.web.servlet.DispatcherServlet 15. 1 16. 17. 18. spring <!-- 这里在配成spring,下边也要写一个名为spring-servlet.xml的文件,主要用来配置它的controller --> 19. *.do 20. 21. 22. index.jsp 23. 24. spring-servlet,主要配置controller的信息 [java] view plaincopy 01.<?xml version="1.0" encoding="UTF-8"?> 02. 09. 10. 11. <!-- 把标记了@Controller注解的类转换为bean --> 12. 13. <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> 14. 15. 16. <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> 17. 19. 20. 23. applicationContext.xml代码 [java] view plaincopy 01.<?xml version="1.0" encoding="UTF-8"?> 02. 11. 12. 13. <!-- 自动扫描所有注解该路径 --> 14. 15. 16. 17. 19. 20. 21. 22. ${dataSource.dialect} 23. ${dataSource.hbm2ddl.auto} 24. update 25. 26. 27. 28. 29. com.mvc.entity<!-- 扫描实体类,也就是平所说的model --> 30. 31. 32. 33. 34. 36. 37. 38. 39. 40. 42. 43. 44. 45. 46. 47. <!-- Dao的实现 --> 48. 49. 50. 51. 52. 53. 54. 55. hibernate.properties数据库连接配置 [java] view plaincopy 01.dataSource.password=123 02.dataSource.username=root 03.dataSource.databaseName=test 04.dataSource.driverClassName=com.mysql.jdbc.Driver 05.dataSource.dialect=org.hibernate.dialect.MySQL5Dialect 06.dataSource.serverName=localhost:3306 07.dataSource.url=jdbc:mysql://localhost:3306/test 08.dataSource.properties=user=${dataSource.username};databaseName=${dataSource.databaseName};serverName=${dataSource.serverName};password=${dataSource.password} 09.dataSource.hbm2ddl.auto=update 配置已经完成,下面开始例子 先在数据库建表,例子用的是mysql数据库 [java] view plaincopy 01.CREATE TABLE `test`.`student` ( 02. `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 03. `name` varchar(45) NOT NULL, 04. `psw` varchar(45) NOT NULL, 05. PRIMARY KEY (`id`) 06.) 建好表后,生成实体类 [java] view plaincopy 01.package com.mvc.entity; 02. 03.import java.io.Serializable; 04. 05.import javax.persistence.Basic; 06.import javax.persistence.Column; 07.import javax.persistence.Entity; 08.import javax.persistence.GeneratedValue; 09.import javax.persistence.GenerationType; 10.import javax.persistence.Id; 11.import javax.persistence.Table; 12. 13.@Entity 14.@Table(name = "student") 15.public class Student implements Serializable { 16. private static final long serialVersionUID = 1L; 17. @Id 18. @Basic(optional = false) 19. @GeneratedValue(strategy = GenerationType.IDENTITY) 20. @Column(name = "id", nullable = false) 21. private Integer id; 22. @Column(name = "name") 23. private String user; 24. @Column(name = "psw") 25. private String psw; 26. public Integer getId() { 27. return id; 28. } 29. public void setId(Integer id) { 30. this.id = id; 31. } 32. 33. public String getUser() { 34. return user; 35. } 36. public void setUser(String user) { 37. this.user = user; 38. } 39. public String getPsw() { 40. return psw; 41. } 42. public void setPsw(String psw) { 43. this.psw = psw; 44. } 45.} Dao层实现 [java] view plaincopy 01.package com.mvc.dao; 02. 03.import java.util.List; 04. 05.public interface EntityDao { 06. public List<Object> createQuery(final String queryString); 07. public Object save(final Object model); 08. public void update(final Object model); 09. public void delete(final Object model); 10.} [java] view plaincopy 01.package com.mvc.dao; 02. 03.import java.util.List; 04. 05.import org.hibernate.Query; 06.import org.springframework.orm.hibernate3.HibernateCallback; 07.import org.springframework.orm.hibernate3.support.HibernateDaoSupport; 08. 09.public class EntityDaoImpl extends HibernateDaoSupport implements EntityDao{ 10. public List<Object> createQuery(final String queryString) { 11. return (List<Object>) getHibernateTemplate().execute( 12. new HibernateCallback<Object>() { 13. public Object doInHibernate(org.hibernate.Session session) 14. throws org.hibernate.HibernateException { 15. Query query = session.createQuery(queryString); 16. List<Object> rows = query.list(); 17. return rows; 18. } 19. }); 20. } 21. public Object save(final Object model) { 22. return getHibernateTemplate().execute( 23. new HibernateCallback<Object>() { 24. public Object doInHibernate(org.hibernate.Session session) 25. throws org.hibernate.HibernateException { 26. session.save(model); 27. return null; 28. } 29. }); 30. } 31. public void update(final Object model) { 32. getHibernateTemplate().execute(new HibernateCallback<Object>() { 33. public Object doInHibernate(org.hibernate.Session session) 34. throws org.hibernate.HibernateException { 35. session.update(model); 36. return null; 37. } 38. }); 39. } 40. public void delete(final Object model) { 41. getHibernateTemplate().execute(new HibernateCallback<Object>() { 42. public Object doInHibernate(org.hibernate.Session session) 43. throws org.hibernate.HibernateException { 44. session.delete(model); 45. return null; 46. } 47. }); 48. } 49.} Dao在applicationContext.xml注入 Dao只有一个类的实现,直接供其它service层调用,如果你想更换为其它的Dao实现,也只需修改这里的配置就行了。 开始写view页面,WEB-INF/view下新建页面student.jsp,WEB-INF/view这路径是在spring-servlet.xml文件配置的,你可以配置成其它,也可以多个路径。student.jsp代码 [xhtml] view plaincopy 01.<%@ page language="java" contentType="text/html; charset=UTF-8" 02. pageEncoding="UTF-8"%> 03.<%@ include file="/include/head.jsp"%> 04. 05.<html> 06.<head> 07.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 08.<title>添加</title> 09. 11.// --><!-- 13.table{ border-collapse:collapse; } 14.td{ border:1px solid #f00; } 15.--><style mce_bogus="1">table{ border-collapse:collapse; } 16.td{ border:1px solid #f00; }</style> 17.<!-- 18.function add(){ 19. [removed].href="<%=request.getContextPath() %>/student.do?method=add"; 20.} 21. 22.function del(id){ 23.$.ajax( { 24. type : "POST", 25. url : "<%=request.getContextPath()%>/student.do?method=del&id;=" + id, 26. dataType: "json", 27. success : function(data) { 28. if(data.del == "true"){ 29. alert("删除成功!"); 30. $("#" + id).remove(); 31. } 32. else{ 33. alert("删除失败!"); 34. } 35. }, 36. error :function(){ 37. alert("网络连接出错!"); 38. } 39.}); 40.} 41.// --> 47. 48. 序号 49. 姓名 50. 密码 51. 操作 52. 53. 54. "> 55. 56. 57. 58. 59. <input type="button" value="编辑"/> 60. <input type="button" value="${student.id}"/>')" value="删除"/> 61. 62. 63. 64. 65. 66.</body> 67.</html> student_add.jsp [xhtml] view plaincopy 01.<%@ page language="java" contentType="text/html; charset=UTF-8" 02. pageEncoding="UTF-8"%> 03.<%@ include file="/include/head.jsp"%> 04. 05.<html> 06.<head> 07.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 08.<title>学生添加</title> 09.<!-- 10.function turnback(){ 11. [removed].href="<%=request.getContextPath() %>/student.do"; 12.} 13.// --> 17.
18. 19. 20. 21. 22.
姓名<input id="user" name="user" type="text" /></td>
密码<input id="psw" name="psw" type="text" /></td>
<input type="submit" value="提交"/><input type="button" value="返回" />
23. 24.</form> 25.</body> 26.</html> controller类实现,只需把注解写上,spring就会自动帮你到相应的bean,相应的注解标记意义,不明白的,可以自己查下@Service,@Controller,@Entity等等的内容。 [java] view plaincopy 01.package com.mvc.controller; 02. 03.import java.util.List; 04. 05.import javax.servlet.http.HttpServletRequest; 06.import javax.servlet.http.HttpServletResponse; 07. 08.import org.apache.commons.logging.Log; 09.import org.apache.commons.logging.LogFactory; 10.import org.springframework.beans.factory.annotation.Autowired; 11.import org.springframework.stereotype.Controller; 12.import org.springframework.ui.ModelMap; 13.import org.springframework.web.bind.annotation.RequestMapping; 14.import org.springframework.web.bind.annotation.RequestMethod; 15.import org.springframework.web.bind.annotation.RequestParam; 16.import org.springframework.web.servlet.ModelAndView; 17. 18.import com.mvc.entity.Student; 19.import com.mvc.service.StudentService; 20. 21.@Controller 22.@RequestMapping("/student.do") 23.public class StudentController { 24. protected final transient Log log = LogFactory 25. .getLog(StudentController.class); 26. @Autowired 27. private StudentService studentService; 28. public StudentController(){ 29. 30. } 31. 32. @RequestMapping 33. public String load(ModelMap modelMap){ 34. List<Object> list = studentService.getStudentList(); 35. modelMap.put("list", list); 36. return "student"; 37. } 38. 39. @RequestMapping(params = "method=add") 40. public String add(HttpServletRequest request, ModelMap modelMap) throws Exception{ 41. return "student_add"; 42. } 43. 44. @RequestMapping(params = "method=save") 45. public String save(HttpServletRequest request, ModelMap modelMap){ 46. String user = request.getParameter("user"); 47. String psw = request.getParameter("psw"); 48. Student st = new Student(); 49. st.setUser(user); 50. st.setPsw(psw); 51. try{ 52. studentService.save(st); 53. modelMap.put("addstate", "添加成功"); 54. } 55. catch(Exception e){ 56. log.error(e.getMessage()); 57. modelMap.put("addstate", "添加失败"); 58. } 59. 60. return "student_add"; 61. } 62. 63. @RequestMapping(params = "method=del") 64. public void del(@RequestParam("id") String id, HttpServletResponse response){ 65. try{ 66. Student st = new Student(); 67. st.setId(Integer.valueOf(id)); 68. studentService.delete(st); 69. response.getWriter().print("{/"del/":/"true/"}"); 70. } 71. catch(Exception e){ 72. log.error(e.getMessage()); 73. e.printStackTrace(); 74. } 75. } 76.} service类实现 [java] view plaincopy 01.package com.mvc.service; 02. 03.import java.util.List; 04. 05.import org.springframework.beans.factory.annotation.Autowired; 06.import org.springframework.stereotype.Service; 07.import org.springframework.transaction.annotation.Transactional; 08. 09.import com.mvc.dao.EntityDao; 10.import com.mvc.entity.Student; 11. 12.@Service 13.public class StudentService { 14. @Autowired 15. private EntityDao entityDao; 16. 17. @Transactional 18. public List<Object> getStudentList(){ 19. StringBuffer sff = new StringBuffer(); 20. sff.append("select a from ").append(Student.class.getSimpleName()).append(" a "); 21. List<Object> list = entityDao.createQuery(sff.toString()); 22. return list; 23. } 24. 25. public void save(Student st){ 26. entityDao.save(st); 27. } 28. public void delete(Object obj){ 29. entityDao.delete(obj); 30. } 31.} OK,例子写完。有其它业务内容,只需直接新建view,并实现相应comtroller和service就行了,配置和dao层的内容基本不变,也就是每次只需写jsp(view),controller和service调用dao就行了。 怎样,看了这个,spring mvc是不是比ssh实现更方便灵活。

81,091

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧