实例详解springMVC之修订完善版

本文介绍如何使用SpringMVC框架与Hibernate进行整合开发,包括配置步骤、代码实现及示例演示。从web.xml配置到DAO层实现,再到Controller和服务层的编写,提供了完整的项目实践指导。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

弃用了struts,用spring mvc框架做了几个项目,感觉都不错,而且使用了注解方式,可以省掉一大堆配置文件。本文主要介绍使用注解方式配置的spring mvc,之前写的spring3.0 mvc和rest小例子没有介绍到数据层的内容,现在这一篇补上。下面开始贴代码。

文中用的框架版本:spring 3,hibernate 3,没有的,自己上网下。

web.xml配置:

<? xmlversion = " 1.0 " encoding = " UTF-8 " ?>
< web - appxmlns: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 > 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的信息

<? xmlversion="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/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/txhttp://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" />
<!-- 启动SpringMVC的注解功能,完成请求和注解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代码

<? xmlversion="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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/txhttp://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数据库

CREATETABLE`test`.`student`(
`id`int(10)unsignedNOTNULLAUTO_INCREMENT,
`name`varchar(45)NOTNULL,
`psw`varchar(45)NOTNULL,
PRIMARYKEY(`id`)
)


建好表后,生成实体类

packagecom.mvc.entity;

importjava.io.Serializable;

importjavax.persistence.Basic;
importjavax.persistence.Column;
importjavax.persistence.Entity;
importjavax.persistence.GeneratedValue;
importjavax.persistence.GenerationType;
importjavax.persistence.Id;
importjavax.persistence.Table;

@Entity
@Table(name="student")
publicclassStudentimplementsSerializable{
privatestaticfinallongserialVersionUID=1L;
@Id
@Basic(optional=false)
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id",nullable=false)
privateIntegerid;
@Column(name="name")
privateStringuser;
@Column(name="psw")
privateStringpsw;
publicIntegergetId(){
returnid;
}
publicvoidsetId(Integerid){
this.id=id;
}

publicStringgetUser(){
returnuser;
}
publicvoidsetUser(Stringuser){
this.user=user;
}
publicStringgetPsw(){
returnpsw;
}
publicvoidsetPsw(Stringpsw){
this.psw=psw;
}
}


Dao层实现

package com.mvc.dao;

import java.util.List;

public interface EntityDao {
publicList<Object>createQuery(finalStringqueryString);
publicObjectsave(finalObjectmodel);
publicvoidupdate(finalObjectmodel);
publicvoiddelete(finalObjectmodel);
}


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 {
publicList<Object>createQuery(finalStringqueryString){
return(List<Object>)getHibernateTemplate().execute(
newHibernateCallback<Object>(){
publicObjectdoInHibernate(org.hibernate.Sessionsession)
throwsorg.hibernate.HibernateException{
Queryquery
=session.createQuery(queryString);
List
<Object>rows=query.list();
returnrows;
}

}
);
}

publicObjectsave(finalObjectmodel){
returngetHibernateTemplate().execute(
newHibernateCallback<Object>(){
publicObjectdoInHibernate(org.hibernate.Sessionsession)
throwsorg.hibernate.HibernateException{
session.save(model);
returnnull;
}

}
);
}

publicvoidupdate(finalObjectmodel){
getHibernateTemplate().execute(
newHibernateCallback<Object>(){
publicObjectdoInHibernate(org.hibernate.Sessionsession)
throwsorg.hibernate.HibernateException{
session.update(model);
returnnull;
}

}
);
}

publicvoiddelete(finalObjectmodel){
getHibernateTemplate().execute(
newHibernateCallback<Object>(){
publicObjectdoInHibernate(org.hibernate.Sessionsession)
throwsorg.hibernate.HibernateException{
session.delete(model);
returnnull;
}

}
);
}

}


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代码

<% @pagelanguage="java"contentType="text/html;charset=UTF-8"
pageEncoding
="UTF-8"
%>
<% @includefile="/include/head.jsp" %>
<! DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//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:1pxsolid#f00;}
--></style><stylemce_bogus="1">table{border-collapse:collapse;}
td
{border:1pxsolid#f00;}</style>
<scripttype="text/javascript"><!--
functionadd(){
window.location.href
="<%=request.getContextPath()%>/student.do?method=add";
}


functiondel(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(
"网络连接出错!");
}

}
);
}

//--></script>
</head>
<body>

<inputid="add"type="button"onclick="add()"value="添加"/>
<table>
<tr>
<td>序号</td>
<td>姓名</td>
<td>密码</td>
<td>操作</td>
</tr>
<c:forEachitems="${list}"var="student">
<trid="<c:outvalue="${student.id}"/>">
<td><c:outvalue="${student.id}"/></td>
<td><c:outvalue="${student.user}"/></td>
<td><c:outvalue="${student.psw}"/></td>
<td>
<inputtype="button"value="编辑"/>
<inputtype="button"onclick="del('<c:outvalue="${student.id}"/>')"value="删除"/>
</td>
</tr>
</c:forEach>

</table>
</body>
</html>


student_add.jsp

<% @pagelanguage="java"contentType="text/html;charset=UTF-8"
pageEncoding
="UTF-8" %>
<% @includefile="/include/head.jsp" %>
<! DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//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" > <!--
functionturnback(){
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 {
protectedfinaltransientLoglog=LogFactory
.getLog(StudentController.
class);
@Autowired
privateStudentServicestudentService;
publicStudentController(){

}


@RequestMapping
publicStringload(ModelMapmodelMap){
List
<Object>list=studentService.getStudentList();
modelMap.put(
"list",list);
return"student";
}


@RequestMapping(params
="method=add")
publicStringadd(HttpServletRequestrequest,ModelMapmodelMap)throwsException{
return"student_add";
}


@RequestMapping(params
="method=save")
publicStringsave(HttpServletRequestrequest,ModelMapmodelMap){
Stringuser
=request.getParameter("user");
Stringpsw
=request.getParameter("psw");
Studentst
=newStudent();
st.setUser(user);
st.setPsw(psw);
try{
studentService.save(st);
modelMap.put(
"addstate","添加成功");
}

catch(Exceptione){
log.error(e.getMessage());
modelMap.put(
"addstate","添加失败");
}


return"student_add";
}


@RequestMapping(params
="method=del")
publicvoiddel(@RequestParam("id")Stringid,HttpServletResponseresponse){
try{
Studentst
=newStudent();
st.setId(Integer.valueOf(id));
studentService.delete(st);
response.getWriter().print(
"{\"del\":\"true\"}");
}

catch(Exceptione){
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
privateEntityDaoentityDao;

@Transactional
publicList<Object>getStudentList(){
StringBuffersff
=newStringBuffer();
sff.append(
"selectafrom").append(Student.class.getSimpleName()).append("a");
List
<Object>list=entityDao.createQuery(sff.toString());
returnlist;
}


publicvoidsave(Studentst){
entityDao.save(st);
}

publicvoiddelete(Objectobj){
entityDao.delete(obj);
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值