棄用了struts,,用spring mvc框架做了幾個項(xiàng)目,,感覺都不錯,而且使用了注解方式,可以省掉一大堆配置文件,。本文主要介紹使用注解方式配置的spring mvc,,之前寫的spring3.0 mvc和rest小例子沒有介紹到數(shù)據(jù)層的內(nèi)容,現(xiàn)在這一篇補(bǔ)上,。下面開始貼代碼,。
文中用的框架版本:spring 3,hibernate 3,沒有的,自己上網(wǎng)下,。 web.xml配置: <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www./2001/XMLSchema-instance" xmlns="http://java./xml/ns/javaee" xmlns:web="http://java./xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java./xml/ns/javaee http://java./xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>s3h3</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <!-- 這里在配成spring,下邊也要寫一個名為spring-servlet.xml的文件,,主要用來配置它的controller --> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> spring-servlet,主要配置controller的信息 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www./schema/beans" xmlns:xsi="http://www./2001/XMLSchema-instance" xmlns:p="http://www./schema/p" xmlns:context="http://www./schema/context" xsi:schemaLocation="http://www./schema/beans http://www./schema/beans/spring-beans-3.0.xsd http://www./schema/aop http://www./schema/aop/spring-aop-3.0.xsd http://www./schema/tx http://www./schema/tx/spring-tx-3.0.xsd http://www./schema/context http://www./schema/context/spring-context-3.0.xsd"> <context:annotation-config /> <!-- 把標(biāo)記了@Controller注解的類轉(zhuǎn)換為bean --> <context:component-scan base-package="com.mvc.controller" /> <!-- 啟動Spring MVC的注解功能,完成請求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <!-- 對模型視圖名稱的解析,,即在模型視圖名稱添加前后綴 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/view/" p:suffix=".jsp" /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8" /> </beans> applicationContext.xml代碼 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www./schema/beans" xmlns:aop="http://www./schema/aop" xmlns:context="http://www./schema/context" xmlns:p="http://www./schema/p" xmlns:tx="http://www./schema/tx" xmlns:xsi="http://www./2001/XMLSchema-instance" xsi:schemaLocation=" http://www./schema/beans http://www./schema/beans/spring-beans-3.0.xsd http://www./schema/context http://www./schema/context/spring-context-3.0.xsd http://www./schema/aop http://www./schema/aop/spring-aop-3.0.xsd http://www./schema/tx http://www./schema/tx/spring-tx-3.0.xsd"> <context:annotation-config /> <context:component-scan base-package="com.mvc" /> <!-- 自動掃描所有注解該路徑 --> <context:property-placeholder location="classpath:/hibernate.properties" /> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${dataSource.dialect}</prop> <prop key="hibernate.hbm2ddl.auto">${dataSource.hbm2ddl.auto}</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.mvc.entity</value><!-- 掃描實(shí)體類,,也就是平時所說的model --> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> <property name="dataSource" ref="dataSource" /> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${dataSource.driverClassName}" /> <property name="url" value="${dataSource.url}" /> <property name="username" value="${dataSource.username}" /> <property name="password" value="${dataSource.password}" /> </bean> <!-- Dao的實(shí)現(xiàn) --> <bean id="entityDao" class="com.mvc.dao.EntityDaoImpl"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <tx:annotation-driven mode="aspectj"/> <aop:aspectj-autoproxy/> </beans> hibernate.properties數(shù)據(jù)庫連接配置 dataSource.password=123
dataSource.username=root dataSource.databaseName=test dataSource.driverClassName=com.mysql.jdbc.Driver dataSource.dialect=org.hibernate.dialect.MySQL5Dialect dataSource.serverName=localhost:3306 dataSource.url=jdbc:mysql://localhost:3306/test dataSource.properties=user=${dataSource.username};databaseName=${dataSource.databaseName};serverName=${dataSource.serverName};password=${dataSource.password} dataSource.hbm2ddl.auto=update 配置已經(jīng)完成,下面開始例子 CREATE TABLE `test`.`student` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL, `psw` varchar(45) NOT NULL, PRIMARY KEY (`id`) ) 建好表后,,生成實(shí)體類 package com.mvc.entity;
import java.io.Serializable; import javax.persistence.Basic; 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 = "student") public class Student implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) private Integer id; @Column(name = "name") private String user; @Column(name = "psw") private String psw; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPsw() { return psw; } public void setPsw(String psw) { this.psw = psw; } } Dao層實(shí)現(xiàn) package com.mvc.dao;
import java.util.List; public interface EntityDao { public List<Object> createQuery(final String queryString); public Object save(final Object model); public void update(final Object model); public void delete(final Object model); } package com.mvc.dao;
import java.util.List; import org.hibernate.Query; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class EntityDaoImpl extends HibernateDaoSupport implements EntityDao{ public List<Object> createQuery(final String queryString) { return (List<Object>) getHibernateTemplate().execute( new HibernateCallback<Object>() { public Object doInHibernate(org.hibernate.Session session) throws org.hibernate.HibernateException { Query query = session.createQuery(queryString); List<Object> rows = query.list(); return rows; } }); } public Object save(final Object model) { return getHibernateTemplate().execute( new HibernateCallback<Object>() { public Object doInHibernate(org.hibernate.Session session) throws org.hibernate.HibernateException { session.save(model); return null; } }); } public void update(final Object model) { getHibernateTemplate().execute(new HibernateCallback<Object>() { public Object doInHibernate(org.hibernate.Session session) throws org.hibernate.HibernateException { session.update(model); return null; } }); } public void delete(final Object model) { getHibernateTemplate().execute(new HibernateCallback<Object>() { public Object doInHibernate(org.hibernate.Session session) throws org.hibernate.HibernateException { session.delete(model); return null; } }); } } Dao在applicationContext.xml注入 <bean id="entityDao" class="com.mvc.dao.EntityDaoImpl">
<property name="sessionFactory" ref="sessionFactory" /> </bean> Dao只有一個類的實(shí)現(xiàn),,直接供其它service層調(diào)用,,如果你想更換為其它的Dao實(shí)現(xiàn),也只需修改這里的配置就行了,。 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <%@ include file="/include/head.jsp"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www./TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>添加</title> <script language="javascript" src="<%=request.getContextPath()%><!-- /script/jquery.min.js"> // --></script> <style><!-- table{ border-collapse:collapse; } td{ border:1px solid #f00; } --></style><style mce_bogus="1">table{ border-collapse:collapse; } td{ border:1px solid #f00; }</style> <script type="text/javascript"><!-- function add(){ window.location.href="<%=request.getContextPath() %>/student.do?method=add"; } function del(id){ $.ajax( { type : "POST", url : "<%=request.getContextPath()%>/student.do?method=del&id=" + id, dataType: "json", success : function(data) { if(data.del == "true"){ alert("刪除成功!"); $("#" + id).remove(); } else{ alert("刪除失??!"); } }, error :function(){ alert("網(wǎng)絡(luò)連接出錯!"); } }); } // --></script> </head> <body> <input id="add" type="button" onclick="add()" value="添加"/> <table > <tr> <td>序號</td> <td>姓名</td> <td>密碼</td> <td>操作</td> </tr> <c:forEach items="${list}" var="student"> <tr id="<c:out value="${student.id}"/>"> <td><c:out value="${student.id}"/></td> <td><c:out value="${student.user}"/></td> <td><c:out value="${student.psw}"/></td> <td> <input type="button" value="編輯"/> <input type="button" onclick="del('<c:out value="${student.id}"/>')" value="刪除"/> </td> </tr> </c:forEach> </table> </body> </html> student_add.jsp <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <%@ include file="/include/head.jsp"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www./TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>學(xué)生添加</title> <mce:script type="text/javascript"><!-- function turnback(){ window.location.href="<%=request.getContextPath() %>/student.do"; } // --></mce:script> </head> <body> <form method="post" action="<%=request.getContextPath() %>/student.do?method=save"> <div><c:out value="${addstate}"></c:out></div> <table> <tr><td>姓名</td><td><input id="user" name="user" type="text" /></td></tr> <tr><td>密碼</td><td><input id="psw" name="psw" type="text" /></td></tr> <tr><td colSpan="2" align="center"><input type="submit" value="提交"/><input type="button" onclick="turnback()" value="返回" /> </td></tr> </table> </form> </body> </html> controller類實(shí)現(xiàn),,只需把注解寫上,,spring就會自動幫你找到相應(yīng)的bean,相應(yīng)的注解標(biāo)記意義,,不明白的,,可以自己查下@Service,@Controller,,@Entity等等的內(nèi)容,。 package com.mvc.controller;
import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.mvc.entity.Student; import com.mvc.service.StudentService; @Controller @RequestMapping("/student.do") public class StudentController { protected final transient Log log = LogFactory .getLog(StudentController.class); @Autowired private StudentService studentService; public StudentController(){ } @RequestMapping public String load(ModelMap modelMap){ List<Object> list = studentService.getStudentList(); modelMap.put("list", list); return "student"; } @RequestMapping(params = "method=add") public String add(HttpServletRequest request, ModelMap modelMap) throws Exception{ return "student_add"; } @RequestMapping(params = "method=save") public String save(HttpServletRequest request, ModelMap modelMap){ String user = request.getParameter("user"); String psw = request.getParameter("psw"); Student st = new Student(); st.setUser(user); st.setPsw(psw); try{ studentService.save(st); modelMap.put("addstate", "添加成功"); } catch(Exception e){ log.error(e.getMessage()); modelMap.put("addstate", "添加失敗"); } return "student_add"; } @RequestMapping(params = "method=del") public void del(@RequestParam("id") String id, HttpServletResponse response){ try{ Student st = new Student(); st.setId(Integer.valueOf(id)); studentService.delete(st); response.getWriter().print("{\"del\":\"true\"}"); } catch(Exception e){ log.error(e.getMessage()); e.printStackTrace(); } } } service類實(shí)現(xiàn) package com.mvc.service;
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.mvc.dao.EntityDao; import com.mvc.entity.Student; @Service public class StudentService { @Autowired private EntityDao entityDao; @Transactional public List<Object> getStudentList(){ StringBuffer sff = new StringBuffer(); sff.append("select a from ").append(Student.class.getSimpleName()).append(" a "); List<Object> list = entityDao.createQuery(sff.toString()); return list; } public void save(Student st){ entityDao.save(st); } public void delete(Object obj){ entityDao.delete(obj); } } OK,例子寫完,。有其它業(yè)務(wù)內(nèi)容,,只需直接新建view,,并實(shí)現(xiàn)相應(yīng)comtroller和service就行了,配置和dao層的內(nèi)容基本不變,,也就是每次只需寫jsp(view),,controller和service調(diào)用dao就行了。 怎樣,,看了這個,,spring mvc是不是比ssh實(shí)現(xiàn)更方便靈活。 完整源碼:srping mvc注解實(shí)現(xiàn)(在這篇文章的后面附件,,這個是我另一個博客的地址) |
|