本項目基於Annotation方式的SpringMVC4+Sping4+Hibernate4。用到的全部jar包以下:html
項目的總體結構以下:java
WEB_INF/web.xml:mysql
<?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>SpringMVC_xml</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> < filter> <filter-name >encodingFilter </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-mapping> <filter-name >encodingFilter </filter-name > <url-pattern >/* </url-pattern > <!--該過濾器也要布前面,否則不起做用 --> </ filter-mapping> <!-- <filter> <filter-name>openSessionInViewFilter</filter-name> 該過濾器必定要布在struts2過濾器前面,否則不起做用 <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init- param> <param-name>flushMode</param-name> <param-value>AUTO</param-value> 默認flushMode是NEVER,有些狀況下會報異常,故設置爲AUTO </init- param> <init- param> <param-name>singleSession</param-name> <param-value>false</param-value> </init- param> </filter> --> <servlet > <servlet-name >springmvc</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet</servlet-class > <init-param > <param-name >contextConfigLocation </param-name > <param-value >classpath:spring-mvc.xml </param-value > </init-param > <load-on-startup >1 </load-on-startup > </servlet > <servlet-mapping > <servlet-name >springmvc</servlet-name> <url-pattern >*.action </url-pattern > </servlet-mapping > <listener > <listener-class> org.springframework.web.context.ContextLoaderListener</listener-class > </listener > <context-param > <param-name >contextConfigLocation </param-name > <param-value >classpath:beans.xml </param-value > </context-param > </web-app>
2.src/beans.xml:web
<?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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd "> <context:annotation-config ></context:annotation-config > <tx:annotation-driven transaction-manager="transactionManager" /> <bean id ="userService" class="service.UserServiceImpl"> </bean > <bean id ="userDao" class="dao.UserDaoImpl"> </bean > <bean id ="dataSource" class= "org.apache.commons.dbcp.BasicDataSource" > <property name ="driverClassName" value= "com.mysql.jdbc.Driver"/> <property name ="url" value= "jdbc:mysql://localhost:3306/spring" /> <property name ="username" value="root"/> <property name ="password" value="*******"/> </bean > <bean id ="transactionManager" class ="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name ="sessionFactory" ref="sessionFactory" /> </bean > <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 > <prop key ="hibernate.show_sql"> true</ prop> <prop key ="hibernate.hbm2ddl.auto"> update</ prop> <prop key ="hibernate.format_sql"> true</ prop> </props > </property > <property name ="packagesToScan"> <list > <value >entity </value > </list > </property > </bean > <!-- 配置HibernateTemplate Bean --> <bean id ="hibernateTemplate" class= "org.springframework.orm.hibernate4.HibernateTemplate" > <property name ="sessionFactory" ref= "sessionFactory"></property > </bean > </beans>
3.src/spring-mvc.xml:spring
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"> <!-- if you use annotation you must configure following setting --> <mvc:annotation-driven /> <!-- scan the package and the sub package --> <context:component-scan base-package="controller"/> <!-- configure the InternalResourceViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
4.user/user.jsp:sql
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!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>Insert title here</title> </head> <body> <form action="user.action" method="post"><br> uname:<input type="text" name="uname"/><br> pwd:<input type="password" name="pwd"/><br> repwd<input type="password" name="repwd"/><br> <input type="hidden" name="method" value="log2"/> 提交:<input type="submit" value="提交 "/> </form> </body> </html>
5.user/userResult.jsp:apache
<%@ page language ="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@page import= "entity.User" %> <!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> Insert title here</ title> </head> <body> <h1 >註冊成功 </h1 > uname:<%= request.getParameter("uname" ) %> 寫入成功 </body> </html>
6.controller.UserController.java:spring-mvc
package controller; import javax.annotation.Resource; import org.springframework.web.bind.annotation.RequestMapping; import entity.User; import service.UserService; import org.springframework.stereotype.Controller; @Controller @RequestMapping("user/user.action") public class UserController{ private UserService userService; public UserService getUserService() { return userService; } @Resource public void setUserService(UserService userService) { this.userService = userService; } private User user; @RequestMapping(params="method=log") public String log(String uname,String pwd){ System.out.println("log() invoked"); System.out.println(uname+pwd); user = new User(); user.setUname(uname); user.setPwd(pwd); userService.add(user); return "user/userResult"; } @RequestMapping(params="method=log2") public String log2(User user){//相似Struts2的模型驅動,可自動將頁面提交的uname和pwd封裝進該User對象 System.out.println("log2() invoked"); System.out.println(user.getUname()+user.getPwd()); userService.add(user); return "user/userResult"; } }
7.entity.User.java:session
package entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class User { private int id; private String uname; private String pwd; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }
8.service.UserService.java:mvc
package service; import java.util.List; import entity.User; public interface UserService { boolean exists(User user); void add(User user); List<User> getUsers(); User getUser(int id); }
9.service.UserServiceImpl.java:
package service; import java.util.List; import javax.annotation.Resource; import org.springframework.transaction.annotation.Transactional; import dao.UserDao; import entity.User; public class UserServiceImpl implements UserService { private UserDao userDao; public UserDao getUserDao() { return userDao; } @Resource public void setUserDao(UserDao userDao) { this.userDao = userDao; } /* (non-Javadoc) * @see service.UserService#exists(entiey.User) */ @Override public boolean exists(User user) { return userDao.checkUserExistsByUname(user.getUname()); } /* (non-Javadoc) * @see service.UserService#add(entiey.User) */ @Override @Transactional public void add(User user) { System.out.println("add成功"); userDao.save(user); } @Override public List<User> getUsers() { return userDao.getUsers(); } @Override public User getUser(int id) { return userDao.getUser(id); } }
10.dao.UserDao.java:
package dao; import java.util.List; import entity.User; public interface UserDao { boolean checkUserExistsByUname(String uname); void save(User user); List<User> getUsers(); User getUser(int id); }
11.dao.UserDaoImpl.java:
package dao; import java.util.List; import javax.annotation.Resource; import org.springframework.orm.hibernate4.HibernateTemplate; import entity.User; public class UserDaoImpl implements UserDao { private HibernateTemplate hibernateTemplate; public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } @Resource public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } /* (non-Javadoc) * @see dao.UserDao#checkUserExistsByUname(java.lang.String) */ @Override public boolean checkUserExistsByUname(String uname){ //String sql = "select count(*) from User where uname = '"+uname+"'"; String sql = "from User where uname = '"+uname+"'"; List list = (List) hibernateTemplate.find(sql); if(list!=null&&list.size()>0){ return true; } return false; } /* (non-Javadoc) * @see dao.UserDao#save(entiey.User) */ @Override public void save(User user){ hibernateTemplate.save(user); } @Override public List<User> getUsers() { return (List<User>) hibernateTemplate.find("from User"); } @Override public User getUser(int id) { return hibernateTemplate.load(User.class, id); //使用load()時,會報LazyInitializationException,這時需在web.xml中配置過濾器openSessionInViewFilter //return hibernateTemplate.get(User.class, id);獨立表格或小數據量的可以使用get獲取 } }