本项目是用xml方式使用SpringMVC框架,更常用的是annotation方式,这里仅作记录。用到的所有jar包如下:
项目的整体结构如下:
WEB_INF/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>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:
<?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:
<?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 > <bean class= "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" > <property name ="mappings"> <props > <prop key= "user.action">userController</prop > </props > </property > </bean > <bean id ="userController" class= "controller.UserController"> </bean > </beans>
4.user/user.jsp:
<%@ 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 ="/SpringMVC_xml/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 ="submit" value="提交 "/> </form > </body> </html>
5.user/userResult.jsp:
<%@ 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:
package controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import entity.User; import service.UserService; public class UserController implements Controller { private UserService userService; public UserService getUserService() { return userService; } @Resource public void setUserService(UserService userService) { this. userService = userService; } private User user; @Override public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception { System. out.println( "controller invoked"); user = new User(); user.setUname( req.getParameter( "uname")); user.setPwd( req.getParameter( "pwd")); userService.add( user); return new ModelAndView( "user/userResult"); } }
7.entity.User.java:
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:
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获取 } }