//www.springframework.org/schema/beans"
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-2.5.xsd">
8.建立相关类和包结构,如下图所示:
9.各类代码如下:
packagecom.sxt.po;
importjavax.persistence.Entity;
importjavax.persistence.GeneratedValue;
importjavax.persistence.GenerationType;
importjavax.persistence.Id;
@Entity
publicclassUser{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
privateintid;
privateStringuname;
publicintgetId(){
returnid;
}
publicvoidsetId(intid){
this.id=id;
}
publicStringgetUname(){
returnuname;
}
publicvoidsetUname(Stringuname){
this.uname=uname;
}
}
packagecom.sxt.dao;
importorg.springframework.orm.hibernate3.HibernateTemplate;
importcom.sxt.po.User;
publicclassUserDao{
privateHibernateTemplatehibernateTemplate;
publicvoidadd(Useru){
System.out.println("UserDao.add()");
hibernateTemplate.save(u);
}
publicHibernateTemplategetHibernateTemplate(){
returnhibernateTemplate;
}
publicvoidsetHibernateTemplate(HibernateTemplatehibernateTemplate){
this.hibernateTemplate=hibernateTemplate;
}
}
packagecom.sxt.service;
importcom.sxt.dao.UserDao;
importcom.sxt.po.User;
publicclassUserService{
privateUserDaouserDao;
publicvoidadd(Stringuname){
System.out.println("UserService.add()");
Useru=newUser();
u.setUname(uname);
userDao.add(u);
}
publicUserDaogetUserDao(){
returnuserDao;
}
publicvoidsetUserDao(UserDaouserDao){
this.userDao=userDao;
}
}
packagecom.sxt.action;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.web.servlet.ModelAndView;
importorg.springframework.web.servlet.mvc.Controller;
importcom.sxt.service.UserService;
publicclassUserControllerimplementsController{
privateUserServiceuserService;
@Override
publicModelAndViewhandleRequest(HttpServletRequestreq,
HttpServletResponseresp)throwsException{
System.out.println("HelloController.handleRequest()");
req.setAttribute("a","aaaa");
userService.add(req.getParameter("uname"));
returnnewModelAndView("index");
}
publicUserServicegetUserService(){
returnuserService;
}
publicvoidsetUserService(UserServiceuserService){
this.userService=userService;
}
}
10.运行测试:
http:
//locahost:
8080/springmvc01/user.do?
uname=zhangsan。
结果:
数据库中增加zhangsan的记录。
页面跳转到index.jsp上,显示:
4、基于spring2.5注解实现的springMVC项目
我们采用sprngMVC开发项目时,通常都会采用注解的方式,这样可以大大提高我们的开发效率。
实现零配置。
下面我们从零开始重新做一个springMVC的配置。
这个项目完全采用注解的方式开发。
同时,我们以后的springMVC项目也都会采用注解的方式。
1.建立web项目
2.导入jar包(spring.jar,spring-webmvc.jar,commons-logging.jar。
其他jar包为hibernate相关jar包)
3.修改web.xml,文件内容如下:
xmlversion="1.0"encoding="UTF-8"?
>
xmlns="
xmlns:
xsi="http:
//www.w3.org/2001/XMLSchema-instance"
xsi:
schemaLocation="
springmvc