spring mvc 简单搭建
文中用的框架版本:spring 3,hibernate 3,没有的,自己上网下。
web.xml配置:
</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;

publicinterface EntityDao
{
public List<Object> createQuery(final String queryString);
public Object save(final Object model);
publicvoid update(final Object model);
publicvoid 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;

publicclass 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);
returnnull;
}
});
} 
publicvoid update(final Object model)
{ 
getHibernateTemplate().execute(new HibernateCallback<Object>()
{
public Object doInHibernate(org.hibernate.Session session) 
throws org.hibernate.HibernateException
{
session.update(model);
returnnull;
}
});
} 
publicvoid delete(final Object model)
{ 
getHibernateTemplate().execute(new HibernateCallback<Object>()
{
public Object doInHibernate(org.hibernate.Session session) 
throws org.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代码

">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") 
publicclass StudentController
{
protectedfinaltransient 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") 
publicvoid 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 
publicclass 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;
}

publicvoid save(Student st)
{
entityDao.save(st);
} 
publicvoid delete(Object obj)
{
entityDao.delete(obj);
}
}OK,例子写完。有其它业务内容,只需直接新建view,并实现相应comtroller和service就行了,配置和dao层的内容基本不变,也就是每次只需写jsp(view),controller和service调用dao就行了。
spring mvc 简单搭建的更多相关文章
- spring mvc 框架搭建及详解
现 在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了.不 ...
- Spring MVC 环境搭建(一)
一.建立 JavaWeb 项目 1.建立一个 Java 项目. 2.在项目下新建一个文件夹 webapp (命名可自取,这个目录即是网站根目录),再在该文件夹下新建一个 WEB-INF 文件夹(命名固 ...
- Spring MVC 环境搭建(maven+SpringMVC+mybatis+Freemarker)
Spring MVC 环境搭建(maven+SpringMVC+mybatis+Freemarker) 一.准备工作 1.Eclipse Java EE IDE(4.4.1) 2.JDK 3.Tomc ...
- Spring MVC 项目搭建 -3- 快速 添加 spring security
Spring MVC 项目搭建 -3- 快速 添加 spring security 1.添加 spring-sample-security.xml <!-- 简单的安全检验实现 --> & ...
- Spring MVC 项目搭建 -1- 创建项目
Spring MVC 项目搭建 -1- 创建项目 1.创建 Dynamic Web project (SpringDemo),添加相关jar包 2.创建一个简单的controller类 package ...
- Spring MVC 框架搭建及具体解释
如今主流的Web MVC框架除了Struts这个主力 外.其次就是Spring MVC了,因此这也是作为一名程序猿需要掌握的主流框架.框架选择多了.应对多变的需求和业务时,可实行的方案自然就多了. 只 ...
- Spring MVC框架搭建及其详解
现在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了.不过 ...
- Spring MVC 环境搭建(二)
在Spring MVC 环境搭建(一)中我们知道 spring 的配置是通过 urlmapping 映射到控制器,然后通过实现Controller接口的handlerequest方法转向页面. 但这存 ...
- Spring mvc系列一之 Spring mvc简单配置
Spring mvc系列一之 Spring mvc简单配置-引用 Spring MVC做为SpringFrameWork的后续产品,Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块 ...
随机推荐
- 网易云课堂_C语言程序设计进阶_第三周:结构:结构、类型定义、联合
3.1 枚举 3.2 结构 3.3 类型定义 3.1 枚举 枚举是一种用户定义的数据类型,它用关键字enum以如下语法来表明: enum 枚举类型名字{名字0,...,名字n}; 枚举类型名字通常并不 ...
- jQuery插件
1. Lightbox 2: Lightbox 2 是一款很酷的图片显示插件,可以在一个平滑展开的新窗口中展现出图片,而同时页面的其余部分都变成黑色背景.使用这款插件,是为了当你的的图片过大必须 ...
- AU3学习笔记
目录 1. AU3是什么?能做什么? 2. 乱学AU3中的命令(语言相关)? 3. 通过简单示例学习AU3? 4. 正则表达式的学习(对大小写敏感) 5.对于GUI的相关学习 1. AU ...
- IEnumerable和IEnumerator 详解 【转】
初学C#的时候,老是被IEnumerable.IEnumerator.ICollection等这样的接口弄的糊里糊涂,我觉得有必要切底的弄清楚IEnumerable和IEnumerator的本质. 下 ...
- Coroutine,你究竟干了什么?
一 引子 使用Unity已经有一段时间了,对于Component.GameObject之类的概念也算是有所了解,而脚本方面从一开始就选定了C#,目前来看还是挺明智的:Boo太小众,而且支持有限:JS( ...
- SSIS之数据转换用法
当SSIS报错为:“无法在unicode和非unicode字符串数据类型之间转换”,可以考虑用数据转换器实现,很简单,如下图: 第一步,找到数据转换器: 第二步,编辑数据转换器: 第三步:编辑目标映射 ...
- floyd学习中
#include<iostream> #include<math.h> #include<stdio.h> using namespace std; //long ...
- mysql开启慢查询方法
1,配置开启 Linux: 在mysql配置文件my.cnf中增加 log-slow-queries=/var/lib/mysql/slowquery.log (指定日志文件存放位置,可以为空,系统会 ...
- crt 糟心的配置
每次要下载安装crt就要捣鼓半天,各种注册机下来各种问题,顺手记录下刚打通的一个 1.crt 下载 网上看了一遍博客: SecureCRT 7.3.4破解版(含注册机), 下载下来后里面其实是不含注册 ...
- sp<> 强指针类的用法
在android 中可以广泛看到的template<typename T>, class Sp 句柄类实际上是android 为实现垃圾回收机制的智能指针.智能指针是c++ 中的一个概念 ...