springmvc和stuts2相同是实现mvc的优秀框架,进行业务逻辑控制。最大的差别就是struts2通过filter拦截请求到Action。而spring用的是servlet获取请求到controller。再一个是springmvc不用过多进行配置,能够通过注解非常方便简单的进行开发。
SpringMVC+Spring+Hibernate环境搭建:
1 导入相应jar包:
2 在web.xml配置Spring的监听器,指定配置。配置SpringMVC的核心Servlet,指定哪些请求由SpringMVC的Controller处理。同一时候常常设置Spring的一个编码过滤器。指定编码格式防止乱码;
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_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SpringMVC</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> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <filter> <filter-name>Character Encoding</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>Character Encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
3 指定结果视图,须要指定controller所在的包,配置在web.xml的同级文件夹下
springmvc-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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.mvc.controller"></context:component-scan> <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
4 配置spring的applicationContext.xml.这里配置的是hibernate和spring整合的内容
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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.mvc.dao,com.mvc.service,com.mvc.entity"></context:component-scan> <tx:annotation-driven transaction-manager="transactionManager" /> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:c3p0.properties</value> </property> </bean> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${driverClass}"></property> <property name="jdbcUrl" value="${jdbcUrl}"></property> <property name="user" value="${user}"></property> <property name="password" value="${password}"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="packagesToScan"> <list> <value>com.mvc.entity</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans>
c3p0.properties
driverClass=oracle.jdbc.driver.OracleDriver jdbcUrl=jdbc:oracle:thin:@localhost:1521:XE user=orcl password=newsnews
5 dao层代码
package com.mvc.dao; import java.util.List; import com.mvc.entity.Goods; public interface GoodsDao { void save(Goods goods); List<Goods> findAll(); Goods findById(Integer id); void update(Goods goods); void delete(Goods goods); }
package com.mvc.dao; import java.util.List; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Repository; import com.mvc.entity.Goods; @Repository(value="goodsDao") public class GoodsDaoImpl extends HibernateDaoSupport implements GoodsDao { @Resource public void setOne(SessionFactory sessionFactory){ super.setSessionFactory(sessionFactory); } @Override public void save(Goods goods) { this.getHibernateTemplate().save(goods); } @Override public List<Goods> findAll() { // TODO Auto-generated method stub return this.getHibernateTemplate().find("from Goods g"); } @Override public Goods findById(Integer id) { // TODO Auto-generated method stub return this.getHibernateTemplate().get(Goods.class, id); } @Override public void update(Goods goods) { this.getHibernateTemplate().update(goods); } @Override public void delete(Goods goods) { this.getHibernateTemplate().delete(goods); } }
6 service层代码
package com.mvc.service; import java.util.List; import com.mvc.entity.Goods; public interface GoodsService { void save(Goods goods); List<Goods> findAll(); Goods findById(Integer id); void update(Goods goods); void delete(Goods goods); }
package com.mvc.service; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.mvc.dao.GoodsDao; import com.mvc.entity.Goods; @Service(value="goodsService") @Transactional public class GoodsServiceImpl implements GoodsService { private GoodsDao goodsDao; public GoodsDao getGoodsDao() { return goodsDao; } @Resource public void setGoodsDao(GoodsDao goodsDao) { this.goodsDao = goodsDao; } @Override public void save(Goods goods) { goodsDao.save(goods); } @Override public List<Goods> findAll() { // TODO Auto-generated method stub return goodsDao.findAll(); } @Override public Goods findById(Integer id) { // TODO Auto-generated method stub return goodsDao.findById(id); } @Override public void update(Goods goods) { // TODO Auto-generated method stub goodsDao.update(goods); } @Override public void delete(Goods goods) { goodsDao.delete(goods); } }
7 controller层代码,这里是被重定向的 RequestMapping须要设置GET方式
package com.mvc.controller; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.mvc.entity.Goods; import com.mvc.service.GoodsService; @Controller @RequestMapping(value="/Goods") public class GoodsController { private GoodsService goodsService; @Resource public void setGoodsService(GoodsService goodsService) { this.goodsService = goodsService; } @RequestMapping(value="/saveGoods.do",method=RequestMethod.POST) public String saveGoods(@ModelAttribute Goods goods){ System.out.println("in save"); goodsService.save(goods); return "redirect:findAllGoods.do"; } @RequestMapping(value="/findAllGoods",method=RequestMethod.GET) public String findAllGoods(@ModelAttribute Goods goods,Model model){ System.out.println("in findAll"); List<Goods> goodss=goodsService.findAll(); System.out.println(((Goods)goodss.get(0)).getGoodsName()); model.addAttribute("goodss",goodss); return "goods_list"; } @RequestMapping(value="/updateGoods.do",method=RequestMethod.GET) public String updateGoods(@ModelAttribute Goods goods,Model model){ System.out.println("in update"); Goods goods1=goodsService.findById(goods.getGoodsId()); model.addAttribute("goods", goods1); return "goods_detail"; } @RequestMapping(value="/updateGoodsDo.do",method=RequestMethod.POST) public String updateGoodsDo(@ModelAttribute Goods goods){ System.out.println("in updatedo"); goodsService.update(goods); return "redirect:findAllGoods.do"; } @RequestMapping(value="/deleteGoods.do",method=RequestMethod.GET) public String deleteGoodsDo(@ModelAttribute Goods goods){ System.out.println("in updatedo"); Goods g=goodsService.findById(goods.getGoodsId()); goodsService.delete(g); return "redirect:findAllGoods.do"; } }
8 jsp,在springmvc的controller里,假设给类加上RequestMapping,jsp跳进去总是存在和struts2的namespace类似路径问题。解决方案同样。就是在jsp中增加
<%
String path=request.getContextPath();
String basePath=request.getScheme()+"://"+request.getServerName()+":"
+request.getServerPort()+path+"/";
%>
<base href="<%=basePath %>">
来解决。
index.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="Goods/findAllGoods.do" method="get"> <input type="submit" value="go"> </form> </body> </html>
goods_list.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path=request.getContextPath(); String basePath=request.getScheme()+"://"+request.getServerName()+":" +request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <base href="<%=basePath %>"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <table> <tr> <td>商品名称</td><td>商品数量</td><td>编辑</td><td>删除</td> </tr> <c:forEach items="${goodss}" var="goods"> <tr> <td>${goods.goodsName}</td><td>${goods.goodsNumber}</td><td><a href="Goods/updateGoods.do?goodsId=${goods.goodsId }">编辑</a></td> <td><a href="Goods/deleteGoods.do?goodsId=${goods.goodsId }">删除</a></td> </tr> </c:forEach> </table> <a href="goods_save.jsp">add</a> </body> </html>
goods_save.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="Goods/saveGoods.do" method="post"> 商品名称:<input type="text" name="goodsName"/><br> 商品数量:<input type="text" name="goodsNumber"/><br> <input type="submit" value="go"> </form> </body> </html>
goods_detail.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path=request.getContextPath(); String basePath=request.getScheme()+"://"+request.getServerName()+":" +request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <base href="<%=basePath %>"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="Goods/updateGoodsDo.do" method="post"> <input type="hidden" name="goodsId" value="${goods.goodsId }"/> 商品名称:<input type="text" name="goodsName" value="${goods.goodsName }"/><br/> 商品数量:<input type="text" name="goodsNumber" value="${goods.goodsNumber }"><br/> <input type="submit" value="update"> </form> </body> </html>