弃用了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/javaee http://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的信息

<?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-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/context http://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`)

)

建好表后,生成实体类

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层实现

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注入
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{ 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("网络连接出错!");

}

});

}

// --></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.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实现更方便灵活。
- 基于Spring MVC的Web应用开发(三) - Resources
基于Spring MVC的Web应用开发(3) - Resources 上一篇介绍了在基于Spring MVC的Web项目中加入日志,本文介绍Spring MVC如何处理资源文件. 注意到本项目的we ...
- Spring MVC第一课:用IDEA构建一个基于Spring MVC, Hibernate, My SQL的Maven项目
作为一个Spring MVC新手最基本的功夫就是学会如何使用开发工具创建一个完整的Spring MVC项目,本文站在一个新手的角度讲述如何一步一步创建一个基于Spring MVC, Hibernate ...
- 基于Spring MVC 实现拦截器
Spring MVC 拦截器 一,具体内容: 在所有的开发之中拦截器属于一个重要的组件,可以说几乎所有的项目都会提供的概念应用,不管是Spring MVC,还是Struts 2.x都是提供有拦截器的, ...
- Spring MVC学习总结(2)——Spring MVC常用注解说明
使用Spring MVC的注解及其用法和其它相关知识来实现控制器功能. 02 之前在使用Struts2实现MVC的注解时,是借助struts2-convention这个插件,如今我们使 ...
- java spring mvc 全注解
本人苦逼学生一枚,马上就要毕业,面临找工作,实在是不想离开学校.在老师的教导下学习了spring mvc ,配置文件实在繁琐,因此网上百度学习了spring mvc 全注解方式完成spring的装配工 ...
- 基于spring mvc的图片验证码实现
本文实现基于spring mvc的图片验证码,分后台代码和前端页面的展现以及验证码的验证. 首看后台实现代码: @RequestMapping({"authCode"}) publ ...
- [翻译]Spring MVC RESTFul Web Service CRUD 例子
Spring MVC RESTFul Web Service CRUD 例子 本文主要翻译自:http://memorynotfound.com/spring-mvc-restful-web-serv ...
- spring mvc常用注解总结
1.@RequestMapping@RequestMappingRequestMapping是一个用来处理请求地址映射的注解(将请求映射到对应的控制器方法中),可用于类或方法上.用于类上,表示类中的所 ...
- Spring MVC 基础注解之@RequestMapping、@Controller、(二)
我现在学的是spring4.2 今天主要学习了Spring MVC注解 引入注解可以减少我们的代码量,优化我们的代码. @Controller:用于标识是处理器类: @RequestMapping:请 ...
随机推荐
- UESTC 876 爱管闲事 --DP
题意:即求给定n个数字(a1,a2,……an),不改变序列,分成M份,使每一份和的乘积最大. 思路:dp[i][j]表示把前i个数字,分成j份所能得到的最大乘积. 转移方程:dp[i][j] = ma ...
- hydra爆破用法
-R 根据上一次进度继续破解 -S 使用SSL协议连接 -s 指定端口 -l 指定用户名 -L 指定用户名字典(文件) -p 指定密码破解 -P 指定密码字典(文件) -e 空密码探测和指定用户密码探 ...
- JS的Document属性和方法
Attributes 存储节点的属性列表(只读)childNodes 存储节点的子节点列表(只读)dataType 返回此节点的数据类型Definition 以DTD或XML模式给出的节点的定义(只读 ...
- css3d
立方体:http://sandbox.runjs.cn/show/1h6zvghj 原理分析:(左负右正) x:与屏幕水平:(在屏幕上) y:与屏幕水平方向垂直(在屏幕上) z:垂直于屏幕(在屏幕外) ...
- POJ 1182 食物链
G - 食物链 Time Limit:1000MS Memory Limit:10000KB 64bit IO Format:%I64d & %I64u Submit Stat ...
- 如何将NTFS格式的移动硬盘挂接到Mac OS上进行读写(Read/Write)操作
现在硬盘便宜,很多同学都有移动硬盘,如果你同时使用Windows与Mac OS的话,移动硬盘最好不要使用NTFS文件系统,否则在Mac OS上,你只能读你的移动硬盘,不能写. 但是实际上的情况是,移动 ...
- ASP.NET错误处理的方式(总结)
转载至: http://www.cnblogs.com/chinhr/archive/2007/06/26/795947.html ASP.NET错误处理的方式(整理&总结)英文文章研究:ht ...
- REST签名认证
139 开放平台与应用之间以REST协议进行通讯,为了保证通信的安全性,开放平台加入签名认证机制.应用一旦创建,系统生成唯一并且不公开的secretkey,只有应用的拥有者和开放平台知道.因此,当应用 ...
- [iOS翻译]《iOS7 by Tutorials》系列:在Xcode 5里使用单元测试(上)
简介: 单元测试是软件开发的一个重要方面.毕竟,单元测试可以帮你找到bug和崩溃原因,而程序崩溃是Apple在审查时拒绝app上架的首要原因. 单元测试不是万能的,但Apple把它作为开发工具包的一部 ...
- Easyui Combotree问题及其相关
Easyui的setValue方法无效 今天在开发项目的时候,遇到第一个很奇怪的问题:EasyUI的setValue方法无效. $('#department_parent').combotree('s ...