来源:http://itlab.idcquan.com/Java/Hibernate/962179.html
弃用了struts,用spring mvc框架做了几个项目,感觉都不错,而且使用了注解方式,可以省掉一大堆配置文件。本文主要介绍使用注解方式配置的spring mvc,之前写的 spring3.0 mvc和rest小例子没有介绍到数据层的内容,现在这一篇补上。下面开始贴代码。
文中用的框架版本:spring 3,hibernate 3,没有的,自己上网下。
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 " xmlns:web=" http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd " xsi:schemaLocation=" http://java.sun.com/xml/ns/javaeehttp://java.sun.com/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> </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.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/beanshttp://www.springframework.org/schema/beans/spring-beans-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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config /> <!-- 把标记了@Controller注解的类转换为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.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/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> <!-- 扫描实体类,也就是平时所说的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的实现 --> <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数据库连接配置
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
配置已经完成,下面开始例子
先在数据库建表,例子用的是mysql数据库
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`) )
建好表后,生成实体类
packagecom.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层实现
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只有一个类的实现,直接供其它service层调用,如果你想更换为其它的Dao实现,也只需修改这里的配置就行了。
开始写view页面,WEB-INF/view下新建页面student.jsp,WEB-INF/view这路径是在spring-servlet.xml文件配置的,你可以配置成其它,也可以多个路径。student.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.w3.org/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 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.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title> 学生添加 </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类实现,只需把注解写上,spring就会自动帮你找到相应的bean,相应的注解标记意义,不明白的,可以自己查下@Service,@Controller,@Entity等等的内容。
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类实现
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,例子写完。有其它业务内容,只需直接新建view,并实现相应comtroller和service就行了,配置和dao层的内容基本不变,也就是每次只需写jsp(view),controller和service调用dao就行了。
怎样,看了这个,spring mvc是不是比ssh实现更方便灵活。
相关推荐
内容概要:本文详细介绍了LabVIEW控件的设计与实现,尤其是一些由经验丰富的老工程师精心打造的控件。LabVIEW是一款图形化编程语言,广泛应用于数据采集、仪器控制和工业自动化领域。文中通过具体实例展示了如何利用LabVIEW创建美观且功能强大的控件,如滑动条、波形图、金属质感旋钮、动态波形图表以及智能选项卡等。作者强调了LabVIEW控件在灵活性和美观度方面的优势,并分享了许多实用的技术细节和优化方法。 适合人群:具有一定编程基础并希望深入了解LabVIEW控件设计的开发者和技术爱好者。 使用场景及目标:适用于需要进行高效的数据展示和交互设计的应用场景,如工业控制系统、实验室设备操作界面等。目标是帮助用户掌握LabVIEW控件的高级特性,提高开发效率和用户体验。 其他说明:文章不仅提供了具体的代码示例,还探讨了控件美学背后的设计理念和技术实现,鼓励读者探索更多可能性。
Delphi 12.3控件之unidac_10.4.0_d27pro.exe
11.盛趣自闭面(还是自己太菜).txt
58面经面试过程和题目.txt
电大操作系统课后习题解答
人工智能技术与应用演讲【61页PPT】
chromedriver-mac-arm64-135.0.7049.41.zip
内容概要:本文详细介绍了QPSK(四相移键控)调制方法及其在瑞利信道和高斯白噪声信道下的误码率(BER)性能分析。首先展示了QPSK星座图的绘制方法,接着构建了一个简化的QPSK发射机模型,用于将二进制比特流映射到相应的星座点。随后,分别实现了两种信道模型:高斯白噪声信道(AWGN)和瑞利信道,并解释了它们的工作原理以及如何向传输信号添加噪声。文中还提供了详细的误码率测试脚本,通过大量随机比特进行仿真,最终得到了不同信噪比条件下的误码率曲线。此外,作者还讨论了QPSK与其他调制方式如BPSK、16QAM之间的性能差异,强调了频谱效率与抗噪能力之间的权衡关系。 适合人群:对无线通信系统感兴趣的科研人员、研究生以及从事通信工程领域的工程师。 使用场景及目标:①帮助读者理解QPSK的基本原理及其在不同信道环境中的行为特性;②提供实用的Python代码片段,便于快速搭建仿真环境并验证理论结果;③探讨各种调制方式的选择依据,指导实际应用中的优化决策。 其他说明:文中多次提到‘骚操作’,意指一些巧妙但非传统的编程技巧,有助于提高代码执行效率或简化复杂度。同时提醒读者注意仿真过程中可能出现的问题,如
新建 Microsoft Word 文档 (9).docx
计算机科学与技术- 软件开发工具 培训资料
bitcount统计每个元素中设置的位数 B = bitcount(A) Counts the number '1' bits in each element B = bitcount(A, bitValue) "bitValue" = 1 = default = counts the occurance of '1' if bitValue = 0; counts the number '0' The total bits to verify is [8,16,32,or 64] based on the maximal value of A B = bitcount(A, bitValue, maxBits) the total # of bits to examine
MOM生产运营管理平台解决方案【35页PPT】
deli-数码录音电话机-HCD6238(28)P-TSD-使用说明书
Java项目基于ssm框架的课程设计,包含LW+ppt
Delphi 12.3控件之Tsilang 7.5.0.0 D12.7z
ios+UIButton分类+UIButton+UIButton图片文字位置
项目已获导师指导并通过的高分毕业设计项目,可作为课程设计和期末大作业,下载即用无需修改,项目完整确保可以运行。 该系统功能完善、界面美观、操作简单、功能齐全、管理便捷,具有很高的实际应用价值。 项目都经过严格调试,确保可以运行!可以放心下载
Java项目基于ssm框架的课程设计,包含LW+ppt
Delphi 12.3控件之TextEditorPro64.7z
尝试给OpenHarmony4.0增加可以在动态库中使用的日志模块 文章使用的资源,防止gitee资源丢失