配置文件:
web.xml
<?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>ssh</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- spring上下文监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 加载Spring和hibernate的配置文件 ioc容器--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/applicationContext.xml</param-value> </context-param> <!-- 前端控制器 配置SpringMvc--> <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--加载spring-mvc配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!--编码过滤器 --> <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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
spring-mvc.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:context="http://www.springframework.org/schema/context" 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"> <!-- 注解配置 自动扫描controller --> <context:component-scan base-package="com.controller" /> <!-- 注解扫描包,只扫描@Controller的部分 --> <!-- <context:component-scan base-package="com.controller"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> --> <!--完成请求和注解POJO的映射 --> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /> <!-- 定义视图解析器 --> <!-- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 自动扫描dao和service包(自动注入) --> <context:component-scan base-package="com.dao.*" /> <context:component-scan base-package="com.service.*" /> <!-- 只解析除controller之外的注解(即解析service、dao), 避免重复加载导致事务失效 --> <!-- annotation为spting-mvc中解析的内容 --> <!-- <context:component-scan base-package="com"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> --> <!-- 1.数据源配置 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/com?Unicode=true&characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <!-- 2.配置SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <!-- 其实这个hibernate.hbm2ddl.auto参数的作用主要用于:自动创建,更新,验证数据库表结构。如果不是此方面的需求建议set value="none"。 --> <prop key="hibernate.hbm2ddl.auto">none</prop> <!--是否在控制台打印sql语句 --> <prop key="hibernate.show_sql">true</prop> <!--输出格式化后的sql,更方便查看 --> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop> </props> <!-- 注解方式配置, --> </property> <property name="packagesToScan"> <list> <!-- 此处可添加多个entity --> <value>com.entity</value> </list> </property> </bean> <!-- 3.事务管理器配置 --> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 4.事务通知配置 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="*" /> </tx:attributes> </tx:advice> <!-- 5.事务切面配置 --> <aop:config> <!-- 只对业务逻辑层(service层)实施事务 --> <aop:pointcut id="serviceCut" expression="execution(* com.service.*Service.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceCut" /> </aop:config> </beans>
controller(控制层)
package com.controller; import java.io.IOException; import java.util.List; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.entity.User; import com.service.UserService; @Controller @RequestMapping("/userController") public class UserController { private UserService userService; @Autowired public void setUserService(UserService userService) { this.userService = userService; } @RequestMapping(params = "toUserList") public String selectList(HttpServletRequest req){ List<User> userList=userService.selectList(); req.setAttribute("userList", userList); return "user/userList.jsp"; } @RequestMapping(params = "doDel") @ResponseBody public void doDel(User user,HttpServletResponse response) throws IOException{ Boolean ok=userService.delete(user); if(ok){ String result= "{\"result\":\"成功\"}"; response.getWriter().write(result); }else{ String result= "{\"result\":\"失败\"}"; response.getWriter().write(result); } } @RequestMapping(params = "toAdd") public String toAdd(User user,HttpServletRequest req){ if(user.getId()!=null && !"".equals(user.getId())){ user=userService.selectById(user); req.setAttribute("u", user); } return "user/addOrUpdUser.jsp"; } @RequestMapping(params = "doAdd") public String doAdd(User user,HttpServletResponse response,HttpServletRequest req){ if(user.getId()!=null && !"".equals(user.getId())){ userService.doUpdate(user); }else{ user.setId(UUID.randomUUID().toString().replace("-", "")); userService.doAdd(user); } return "redirect:userController.do?toUserList"; } }
service(服务层)
package com.service; import java.util.List; import com.entity.User; public interface UserService { List<User> selectList(); Boolean delete(User user); void doAdd(User user); User selectById(User user); void doUpdate(User user); }
package com.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.dao.UserDao; import com.entity.User; import com.service.UserService; @Service public class UserServiceImpl implements UserService{ private UserDao userDao; @Autowired public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public List<User> selectList() { // TODO Auto-generated method stub return userDao.selectList(); } @Override public Boolean delete(User user) { return userDao.delete(user); } @Override public void doAdd(User user) { userDao.doAdd(user); } @Override public User selectById(User user) { return userDao.selectById(user); } @Override public void doUpdate(User user) { userDao.doUpdate(user); } }
dao(持久层)
package com.dao; import java.util.List; import com.entity.User; public interface UserDao { List<User> selectList(); Boolean delete(User user); void doAdd(User user); User selectById(User user); void doUpdate(User user); }
package com.dao.impl; 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.stereotype.Repository; import com.dao.UserDao; import com.entity.User; @Repository public class UserDaoImpl implements UserDao { private SessionFactory sessionFactory; @Autowired public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Session getSession(){ return sessionFactory.getCurrentSession(); } @Override public List<User> selectList() { //hql String hql = " from User"; Query query = getSession().createSQLQuery(hql); //原生sql String sql="select * from user"; List<User> userList = getSession().createSQLQuery(sql).addEntity(User.class).list(); return userList;//query.list(); } @Override public Boolean delete(User user) { // String hql="delete User u where u.id = ?"; // Query query = sessionFactory.getCurrentSession().createQuery(hql); // query.setString(0, user.getId()).executeUpdate(); String sql="delete from user where id=‘"+user.getId()+"‘"; return getSession().createSQLQuery(sql).executeUpdate()>0; } @Override public void doAdd(User user) { //getSession().save(user); String sql="insert into user values(‘"+user.getId()+"‘,‘"+user.getUserName()+"‘)"; getSession().createSQLQuery(sql).executeUpdate(); } @Override public User selectById(User user) { String hql = "from User u where u.id=?"; Query query =getSession().createQuery(hql); query.setString(0, user.getId()); //return (User) query.uniqueResult(); String sql="select * from user where id=‘"+user.getId()+"‘"; return (User) getSession().createSQLQuery(sql).addEntity(User.class).uniqueResult(); } @Override public void doUpdate(User user) { getSession().update(user);; // String sql="update user set userName=‘"+user.getUserName()+"‘ where id=‘"+user.getId()+"‘"; // getSession().createSQLQuery(sql).executeUpdate(); } }
entity(实体)
package com.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name = "user") public class User { private String id; private String userName; @Id @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid") @Column(length = 32) public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name = "userName", length = 50) public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>userList</title> </head> <script type="text/javascript" src="/ssh/js/jquery-1.10.2.js"></script> <style type="text/css"> .tab{ width:50%; height:30%; text-align:center; border-collapse:collapse; } </style> <body> <button onclick="toAdd()">添加</button> <table class="tab" border="1"> <tr> <td>编号</td> <td>姓名</td> <td>操作</td> </tr> <c:forEach var="user" items="${userList}"> <tr> <td>${user.id}</td> <td>${user.userName}</td> <td> <a href="/ssh/userController.do?toAdd&id=${user.id }">编辑</a> <a href="javascript:del(‘${user.id }‘)">删除</a> </td> </tr> </c:forEach> </table> </body> <script type="text/javascript"> function del(id){ $.ajax({ type: "POST", url: "/ssh/userController.do?doDel", data: { id : id }, dataType: "json", success: function(data){ location.reload(); alert(data.result); } }); } function toAdd(){ location.href="/ssh/userController.do?toAdd"; } </script> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>addOrUpdUser</title> </head> <body> <form action="/ssh/userController.do?doAdd" method="post"> 编号:<input type="text" name="id" value="${u.id}" readonly="readonly"> 姓名:<input type="text" name="userName" value="${u.userName}"> <button type="submit">确定</button> </form> </body> </html>