现在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了。不过要想灵活运用Spring MVC来应对大多数的Web开发,就必须要掌握它的配置及原理。
一、下载spring源包
spring地址:http://www.springsource.org/download
我下的是spring-framework-3.1.0.RELEASE-with-docs.zip
下载依赖包:spring-framework-3.0.5.RELEASE-dependencies.zip
注意官网上3.0.3版本以后同版本依赖包不提供下载
二、导入所需jar包
引入dist目录下除了下面三个其余所有包
org.springframework.web.struts-3.1.0.RELEASE.jar
org.springframework.spring-library-3.1.0.RELEASE.libd
org.springframework.web.portlet-3.1.0.RELEASE.jar
引入依赖包下com.springsource.org.apache.commons.logging-1.1.1.jar及com.springsource.org.aopalliance-1.0.0.jar
三、spring框架配置
1、web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!--配置Sring MVC的核心控制器DispatcherServlet -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 为DispatcherServlet建立映射 -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:/log4j.properties</param-value>
</context-param>
<!-- 配置log4j.xml监听器 -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- 解决工程编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
2、应用上下文配置
spring-servlet.xml即配置用于开启基于注解的springMVC功能,照web.xml中设定,路径为WEB-INF下<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- 加载config.properties 文件-->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:config.properties</value>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置数据源
<bean id="userDao" class="com.examp.dao.UserDao">
<property name="dataSource" ref="dataSource"/>
</bean>-->
<!-- 配置数据源 -->
<bean id="userDao" class="com.examp.dao.impl.UserDaoImpl">
<property name="sqlMapClient" ref="sqlMapClient"></property>
</bean>
<!-- 配置spring 加载sqlmap文件-->
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation">
<value>classpath:/sqlmap-config.xml</value>
</property>
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 定义视图 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.InternalResourceView</value>
</property>
</bean>
<!-- 定义事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="baseTransactionProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
abstract="true">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="add*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="insertOrUpdate*">PROPAGATION_REQUIRED</prop>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
</beans>
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- 连接数据库配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>${db.dirverClass}</value>
</property>
<property name="url">
<value>${db.url}</value>
</property>
<property name="username">
<value>${db.username}</value>
</property>
<property name="password">
<value>${db.password}</value>
</property>
</bean>
</beans>
4、业务逻辑控制层配置 spring-action.xml
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- 定义映射 -->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="helloWorld.html">helloWorldAction</prop>
<prop key="userAction.html">userAction</prop>
</props>
</property>
</bean>
<!-- 定义控制器 -->
<bean id="helloWorldAction" class="com.examp.ch23.HelloWorldAction">
<property name="helloWorld">
<value>${helloWorld}</value>
</property>
<property name="helloWorld1">
<value>${name}</value>
</property>
<property name="viewPage">
<value>${toUrl}</value>
</property>
</bean>
<!-- 根据请求参数决定方法 userAction.html?action=toDetail -->
<bean id="userAction" class="com.examp.ch23.UserAction">
<property name="userDao" ref="userDao"></property>
<!-- <property name="dao" ref="userDao"></property> -->
<property name="methodNameResolver">
<bean class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<!-- 指定参数名为action -->
<property name="paramName" value="action" />
</bean>
</property>
</bean>
</beans>
5、编写DAO接口层
package com.examp.dao;
import java.util.List;
import com.examp.po.UserPO;
/**
* @author Administrator
*
*/
public interface IUserDao {
public List<UserPO> getAllUsers();
public UserPO getUserByID(UserPO user);
public void addUser(UserPO user);
}
package com.examp.dao.impl;
import java.util.List;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import com.examp.dao.IUserDao;
import com.examp.po.UserPO;
public class UserDaoImpl extends SqlMapClientDaoSupport implements IUserDao{
public List<UserPO> getAllUsers() {
return this.getSqlMapClientTemplate().queryForList("user.GET-ALL-USER");
}
public UserPO getUserByID(UserPO user) {
return (UserPO) this.getSqlMapClientTemplate().queryForObject("user.GET-USER-BY-ID",user);
}
public void addUser(UserPO user) {
//this.getSqlMapClientTemplate().insert("user.ADD-USER", user);
}
}
6、编写业务实体类PO UserPO.java
package com.examp.po;
import java.io.Serializable;
public class UserPO implements Serializable {
private String id;
private String name;
private String password;
private int type;
private String email;
private String phone;
private int sex;
private String qq;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
}
7、编写控制层 Action
package com.examp.ch23;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.util.WebUtils;
import com.examp.dao.IUserDao;
import com.examp.dao.UserDao;
import com.examp.po.UserPO;
//public class UserAction implements Controller{
public class UserAction extends MultiActionController{
private static final Log logger = LogFactory.getLog(UserAction.class);
private UserDao dao;
private IUserDao userDao;
private UserPO userPO;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ModelAndView list(HttpServletRequest request,
HttpServletResponse response) throws Exception {
logger.info("UserAction list 方法...");
Map<String,Object> model = new HashMap<String,Object>();
/*Collection<UserPO> list = dao.doquery();
List<UserPO> users = new ArrayList<UserPO>();
for (UserPO userPO : list) {
UserPO user = new UserPO();
user.setId(userPO.getId());
user.setName(userPO.getName());
user.setSex(userPO.getSex());
user.setEmail(userPO.getEmail());
users.add(user);
} */
List<UserPO> result = userDao.getAllUsers();
model.put("list", result);
return new ModelAndView("userList",model);
}
public ModelAndView detail(HttpServletRequest req,HttpServletResponse res) throws Exception{
String id = req.getParameter("id");
UserPO userPO = null;
if(userPO == null){
userPO = new UserPO();
}
userPO.setId(id);
Map<String,Object> model = new HashMap<String,Object>();
userPO = userDao.getUserByID(userPO);
model.put("user", userPO);
return new ModelAndView("userDetail",model);
}
/**
* 通向新增用户页面
* @param req
* @param res
* @return
* @throws Exception
*/
public ModelAndView toAddUser(HttpServletRequest req,HttpServletResponse res) throws Exception{
Map<String,Object> model = new HashMap<String,Object>();
return new ModelAndView("addUser",model);
}
/**
* 新增用户
* @param req
* @param res
* @return
* @throws Exception
*/
/*public void addUser(HttpServletRequest req,HttpServletResponse res) throws Exception{
String name = WebUtils.findParameterValue(req, "name");
String email = WebUtils.findParameterValue(req, "email");
String msg = "";
logger.info("用户名: "+ name + " 邮件: " + email);
if(userPO == null){
userPO = new UserPO();
userPO.setName(name);
userPO.setEmail(email);
}
Map<String,Object> model = new HashMap<String,Object>();
//userDao.addUser(userPO);
msg = "1";
//text 格式
res.getWriter().print(msg);
}**/
public void addUser(HttpServletRequest req,HttpServletResponse res) throws Exception{
String name = WebUtils.findParameterValue(req, "name");
String email = WebUtils.findParameterValue(req, "email");
String json = "",msg = "成功";
logger.info("用户名: "+ name + " 邮件: " + email);
if(userPO == null){
userPO = new UserPO();
}
//json格式
/*json = "{\"success\":true,\"msg\":\"1\"}";
res.getWriter().print(json);*/
Map<String, Object> map = new HashMap<String,Object>();
map.put("status", msg);
JSONObject result = JSONObject.fromObject(map);
res.setContentType("text/html;charset=utf-8");
res.getWriter().print(result.toString());
}
public UserDao getDao() {
return dao;
}
public void setDao(UserDao dao) {
this.dao = dao;
}
public IUserDao getUserDao() {
return userDao;
}
public void setUserDao(IUserDao userDao) {
this.userDao = userDao;
}
public UserPO getUserPO() {
return userPO;
}
public void setUserPO(UserPO userPO) {
this.userPO = userPO;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<settings cacheModelsEnabled="true"
errorTracingEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
useStatementNamespaces="true"
statementCachingEnabled="true"/>
<sqlMap resource="sqlmap/sqlmap-t_user.xml"/>
</sqlMapConfig>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="user">
<typeAlias alias="userPO" type="com.examp.po.UserPO" />
<resultMap class="userPO" id="user">
<result property="id" column="id" />
<result property="name" column="name" />
<result property="email" column="email" />
<result property="sex" column="sex" />
</resultMap>
<select id="GET-ALL-USER" parameterClass="string" resultClass="userPO">
<![CDATA[
SELECT T.ID,T.NAME,T.EMAIL,T.SEX FROM T_USER T
]]>
</select>
<select id="GET-USER-BY-ID" parameterClass="userPO" resultClass="userPO">
<![CDATA[
SELECT T.ID,T.NAME,T.EMAIL,T.SEX FROM T_USER T
WHERE 1=1
]]>
<isNotNull property="id" prepend="AND">
<![CDATA[id = #id#]]>
</isNotNull>
</select>
<!-- <insert id="ADD-USER" parameterClass="userPO">
<![CDATA[
INSERT INTO t_user(id,name,password,nick_name,type,email,phone,sex
,real_name,idno,head_portrait,province,city,is_auth,is_bound_phone
,is_protected,bound_phone,reg_time,status,login_time,is_del
,qq,birthday,office_tel,office_adr,office_zip,home_adr,home_zip
,remark,operator,opt_time,regist_type,verify_status,auth_url_up,payment_pas,auth_url_dw,corporate_name,organization_code,rand_no,relate_sale_id,relate_service_id,reg_source,law_person,law_personnum,loan_comp_type,ip,class)
VALUES(
#id#,#name#,#password#,#nickName#,#type#,#email#,#phone#,#sex#
,#realName#,#idNo#,#headPortrait#,#province#,#city#,#isAuth#,#isBoundPhone#
,#isProtected#,#boundPhone#,#regTime#,#status#,#loginTime#,#isDel#
,#qq#,#birthday#,#officeTel#,#officeAdr#,#officeZip#,#homeAdr#,#homeZip#
,#remark#,#operator#,#optTime#,#registType#,#verifyStatus#,#authUrlUp#,#paymentPas#,#authUrlDw#,#corporateName#,#organizationCode#,#randNo#,#relateSaleId#,#relateServiceId#,#regSource#,#lawPerson#,#lawPersonnum#,#loanCompType#,#ip#,#userClass#)
]]>
</insert> -->
</sqlMap>
9、编写JSP页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="com.examp.po.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>用户列表</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<%
String str = (String)request.getAttribute("helloWorld");
//List list = (List)request.getAttribute("list");
%>
<body>
<table>
<tr>
<td colspan="4" align="center"><a href="/ch23/userAction.html?action=toAddUser">添加用户</a></td>
</tr>
<tr>
<td>
用户ID
</td>
<td>
用户名
</td>
<td>
性别
</td>
<td>
邮件
</td>
</tr>
<c:forEach var="user" items="${list}">
<tr>
<td><a href="/ch23/userAction.html?action=detail&id=${user.id}">${user.id}</a></td>
<td>${user.name}</td>
<td>
<c:if test="${user.sex == 0}">
保密
</c:if>
<c:if test="${user.sex == 1}">
男
</c:if>
<c:if test="${user.sex == 2}">
女
</c:if>
</td>
<td>${user.email}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
![](https://i-blog.csdnimg.cn/blog_migrate/0111be5e6c966dfb67df279e6ab60928.jpeg)