数据库的表结构:
View Code
DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` bigint(10) NOT NULL auto_increment, `username` varchar(20) default NULL, `password` varchar(20) default NULL, `age` int(4) default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=gbk;
java:
User
package com.medol; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * 实体类 * */ @Entity @Table(name="user") public class User { private long id; private String username; private String password; private int age; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) public long getId() { return id; } public void setId(long id) { this.id = id; } @Column(name="username", length=20) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Column(name="password", length=20) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Column(name="age", length=4) public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
MyHibernateDaoSupport
package com.dao; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class MyHibernateDaoSupport extends HibernateDaoSupport { @Resource(name = "sessionFactory") // 为父类 HibernateDaoSupport 注入 sessionFactory public void setSuperSessionFactory(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } }
BaseDao
package com.dao; import java.util.List; public interface BaseDao { public List getModel(String hql); public void saveModel(Object model); public List search(String hql, Object paramValue); public List search(String hql, Object[] paramValue); public Object getModelDetail(Class cl, Long id); public void deModel(Class cl, Long id); }
BaseDaoImpl
package com.dao; import java.util.List; import org.springframework.stereotype.Repository; @Repository public class BaseDaoImpl extends MyHibernateDaoSupport implements BaseDao{ public List getModel(String hql) { // TODO Auto-generated method stub return super.getHibernateTemplate().find(hql); } public void saveModel(Object model) { // TODO Auto-generated method stub super.getHibernateTemplate().save(model); } public List search(String hql, Object paramValue) { // TODO Auto-generated method stub return super.getHibernateTemplate().find(hql,paramValue); } public List search(String hql, Object[] paramValue) { // TODO Auto-generated method stub return super.getHibernateTemplate().find(hql, paramValue); } public void deModel(Class cl, Long id) { // TODO Auto-generated method stub super.getHibernateTemplate().delete(getModelDetail(cl, id)); } public Object getModelDetail(Class cl, Long id) { // TODO Auto-generated method stub return super.getHibernateTemplate().get(cl, id); } }
UserServie
package com.service; import java.util.List; import com.medol.User; public interface UserServie { public List getUser(); public void saveUser(User user); public List searchById(long id); public List searchByNameandId(Object[] paramValue); public void delUserById(Class cl,long id); }
UserServiceImpl
package com.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.dao.BaseDao; import com.medol.User; @Service("userService") public class UserServiceImpl implements UserServie { @Autowired private BaseDao baseDao; public List getUser() { // TODO Auto-generated method stub String hql = "from com.medol.User user"; return baseDao.getModel(hql); } public void saveUser(User user) { // TODO Auto-generated method stub baseDao.saveModel(user); } public List searchById(long id) { // TODO Auto-generated method stub String hql = "from com.medol.User user where id=?"; return baseDao.search(hql,id); } public List searchByNameandId(Object[] paramValue) { // TODO Auto-generated method stub String hql = "from com.medol.User user where username = ? or age = ?"; return baseDao.search(hql, paramValue); } public void delUserById(Class cl,long id) { // TODO Auto-generated method stub baseDao.deModel(cl, id); } }
UserController
package com.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.medol.User; import com.service.UserServie; @Controller public class UserController { @Autowired private UserServie userServie; /** * @ModelAttribute 此注解可以用于web请求参数和方法参数的绑定,也可用于方法的返回值作为模型数据 * (这种模型数据在类中全局有效,比如这里initUser方法绑定的模型数据在此类的任何方法中都能访问到这种模型数据)。 * */ @RequestMapping("/save.do") public ModelAndView addUser(@ModelAttribute User user){ //保存User userServie.saveUser(user); //获取User return getUserList(); } @RequestMapping("/delete.do") public ModelAndView delUserById(@RequestParam("id")long id){ userServie.delUserById(User.class, id); return getUserList(); } @RequestMapping("/search.do") public ModelAndView getUserByNameAndAge(@RequestParam("username")String username,@RequestParam("age")int age){ Object[] objects = new Object[2]; objects[0] = username; objects[1] = age; List users = userServie.searchByNameandId(objects); return new ModelAndView("users").addObject("users", users); } @RequestMapping("/list.do") public ModelAndView getUserList(){ List<User> users = userServie.getUser(); return new ModelAndView("users").addObject("users", users); } }
jsp:
users.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!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=UTF-8"> <title>注册用户信息</title> </head> <body> 注册用户信息: <form action="<%=request.getContextPath() %>/save.do" method="post"> <table width="50%" border="1px"> <tr><td width="10%">username:</td><td><input type="text" name="username"></td></tr> <tr><td>password:</td><td><input type="text" name="password"></td></tr> <tr><td>age:</td><td><input type="text" name="age"></td></tr> <tr><td></td><td><input type="submit" value="submit"><input type="reset" value="reset"></td></tr> </table> </form> <br/> <br/> 查找用户信息: <form action="<%=request.getContextPath() %>/search.do" method="post"> <table width="50%" border="1px"> <tr><td width="10%">username:</td><td><input type="text" name="username"></td></tr> <tr><td>age:</td><td><input type="text" name="age"></td></tr> <tr><td></td><td><input type="submit" value="submit"><input type="reset" value="reset"></td></tr> </table> </form> <br/> <br/> 显示用户列表:<br/> <!-- requestScope是el表达式的隐含对象,${requestScope.name}和request.getAttribute("name")是一样的 --> <c:if test="${empty requestScope.users}"> 对不起,没有要显示的记录!!!! </c:if> <c:if test="${!empty requestScope.users}"> <c:forEach items="${requestScope.users}" var="s"> <c:out value="${s.id}"/> <c:out value="${s.username}"/> <c:out value="${s.password}"/> <c:out value="${s.age}"/> <a href="<%=request.getContextPath() %>/delete.do?id=${s.id}"><c:out value="delete"/></a> <br/> </c:forEach> </c:if> </body> </html>
配置文件:
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app 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"> <!-- Spring 服务层的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <!-- spring 容器启动监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring MVC 的Servlet,它将加载WEB-INF/annomvc-servlet.xml 的 配置文件,以启动Spring MVC模块--> <servlet> <servlet-name>annomvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/annomvc-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>annomvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
annomvc-servlet.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "> <!-- ①:对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 --> <context:component-scan base-package="com.controller" /> <!-- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <!-- ③:对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/" p:suffix=".jsp" /> </beans>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" 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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!-- 自动扫描所有注解该路径 --> <context:annotation-config /> <context:component-scan base-package="com" /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" > <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:mysql://localhost:3306/mvctest</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>root</value> </property> </bean> <!-- 配置 SessionFactory,由 Spring 容器来管理 Hibernate --> <!-- 非 Annotation 时,使用 org.springframework.orm.hibernate3.LocalSessionFactoryBean, 它注入实体类的方式是 setMappingResources(),而 Hibernate Annotation 所用的 映射方式 不是 mapping resource, 而是 mapping class,这就要用到 LocalSessionFactoryBe an 的子类 AnnotationSessionFactoryBean 了.因为 AnnotationSessionFactoryBean 它支持 实体的注入 方式 setAnnotatedClasses,即对应 Hibernate 中的 mapping class.参见这两个类的 源代码. --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref local="dataSource" /> </property> <property name="annotatedClasses"> <list> <value>com.medol.User</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <!-- prop key="hibernate.dialect"> org.hibernate.dialect.Oracle9Dialect </prop> --> <prop key="hibernate.show_sql"> true </prop> <!--<prop key="hibernate.hbm2ddl.auto">update</prop>--> <!-- prop key="hibernate.default_schema"> xdb </prop--> <!-- 主要设置hibernate 缓存和批处理的大--> <prop key="hibernate.jdbc.batch_versioned_data">true</prop> <!-- <prop key="hibernate.connection.provider_class">net.sf.hibernate.connection.DatasourceConnectionProvider</prop> <prop key="hibernate.cache.provider_class">net.sf.hibernate.cache.EhCacheProvider</prop> --> <prop key="hibernate.jdbc.fetch_size">50</prop> <!-- 自动增加新表,重新启动服务时执行该命令,应用时务必注释此句(本机使用) --> <!--prop key="hibernate.hbm2ddl.auto">update</prop--> <prop key="hibernate.jdbc.batch_size">20</prop> </props> </property> </bean> <!-- 配置事务管理 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref local="sessionFactory"></ref> </property> </bean> </beans>
访问地址:http://localhost:8080/springmvc/users.jsp