Spring MVC 背景介绍_1
Spring MVC 背景介绍
Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,可以选择是使用内置的 Spring Web 框架还是 Struts 这样的 Web 框架。通过策略接口,Spring 框架是高度可配置的,而且包含多种视图技术,例如 JavaServer Pages(JSP)技术、Velocity、Tiles、iText 和 POI。Spring MVC 框架并不知道使用的视图,所以不会强迫您只使用 JSP 技术。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。
常见MVC框架比较
运行性能上:
Jsp+servlet>struts1>spring mvc>struts2+freemarker>>struts2,ognl,值栈。
开发效率上,基本正好相反。值得强调的是,spring mvc开发效率和struts2不相上下。
Struts2的性能低的原因是因为OGNL和值栈造成的。所以,如果你的系统并发量高,可以使用freemaker进行显示,而不是采用OGNL和值栈。这样,在性能上会有相当大得提高。
基于spring2.5的采用XML配置的spring MVC项目
注:本项目全部基于XML配置。同时,集成了hibernate。采用的是:spring MVC+hibernate+spring的开发架构。
- 建立web项目
- 导入jar包(spring.jar, spring-webmvc.jar, commons-logging.jar。其他jar包为hibernate相关jar包)
- 修改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">> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/hib-config.xml,/WEB-INF/web-config.xml,/WEB-INF/service-config.xml,/WEB-INF/dao-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app> |
- 增加web-config.xml(这里包含spring mvc相关的相关配置)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://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">
<!-- Controller方法调用规则定义 --> <bean id="paraMethodResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver"> <property name="paramName" value="action"/> <property name="defaultMethodName" value="list"/> </bean>
<!-- 页面View层基本信息设定 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <!--<property name="prefix" value="/myjsp/"/>--> <property name="suffix" value=".jsp"/> </bean>
<!-- servlet映射列表,所有控制层Controller的servlet在这里定义 --> <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="user.do">userController</prop> </props> </property> </bean>
<bean id="userController" class="com.sxt.action.UserController"> <property name="userService" ref="userService"></property> </bean> </beans> |
- 在WEB-INF下增加service-config.xml(这里包含service层类的相关配置)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://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">
<bean id="userService" class="com.sxt.service.UserService"> <property name="userDao" ref="userDao"></property> </bean>
</beans> |
- 在WEB-INF下增加hib-config.xml(这里包含spring集成hibernate相关的配置)
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd "> <context:component-scan base-package="com.sxt"/> <!-- 支持aop注解 --> <aop:aspectj-autoproxy />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/myhib"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> </bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <!-- key的名字前面都要加hibernate. --> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <property name="packagesToScan"> <value>com.sxt.po</value> </property> </bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" > <property name="sessionFactory" ref="sessionFactory"></property> </bean>
<!--配置一个JdbcTemplate实例--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean>
<!-- 配置事务管理 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" > <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="txManager" /> <aop:config> <aop:pointcut expression="execution(public * com.sxt.service.impl.*.*(..))" id="businessService"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="businessService" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="txManager" > <tx:attributes> <tx:method name="find*" read-only="true" propagation="NOT_SUPPORTED" /> <!-- get开头的方法不需要在事务中运行 。 有些情况是没有必要使用事务的,比如获取数据。开启事务本身对性能是有一定的影响的--> <tx:method name="*"/> <!-- 其他方法在实务中运行 --> </tx:attributes> </tx:advice>
</beans> |
- 在WEB-INF下增加dao-config.xml(这里包含dao层类的相关配置)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://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">
<bean id="userDao" class="com.sxt.dao.UserDao"> <property name="hibernateTemplate" ref="hibernateTemplate"></property> </bean> </beans> |
- 建立相关类和包结构,如下图所示:
- 各类代码如下:
package com.sxt.po;
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id;
@Entity public class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; private String uname; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } } |
package com.sxt.dao;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.sxt.po.User;
public class UserDao { private HibernateTemplate hibernateTemplate;
public void add(User u){ System.out.println("UserDao.add()"); hibernateTemplate.save(u); }
public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; }
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; }
} |
package com.sxt.service;
import com.sxt.dao.UserDao; import com.sxt.po.User;
public class UserService {
private UserDao userDao;
public void add(String uname){ System.out.println("UserService.add()"); User u = new User(); u.setUname(uname); userDao.add(u); }
public UserDao getUserDao() { return userDao; }
public void setUserDao(UserDao userDao) { this.userDao = userDao; }
} |
package com.sxt.action;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller;
import com.sxt.service.UserService;
public class UserController implements Controller {
private UserService userService;
@Override public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception { System.out.println("HelloController.handleRequest()"); req.setAttribute("a", "aaaa"); userService.add(req.getParameter("uname")); return new ModelAndView("index"); }
public UserService getUserService() { return userService; }
public void setUserService(UserService userService) { this.userService = userService; }
} |
- 运行测试:
结果为:
基于spring 3.0mvc 框架的文件上传实现
1. spring使用了apache-commons下得上传组件,因此,我们需要引入两个jar包:
- apache-commons-fileupload.jar
- apache-commons-io.jar
2. 在springmvc-servlet.xml配置文件中,增加CommonsMultipartResoler配置:
<!-- 处理文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" > <property name="defaultEncoding" value="gbk"/> <!-- 默认编码 (ISO-8859-1) --> <property name="maxInMemorySize" value="10240"/> <!-- 最大内存大小 (10240)--> <property name="uploadTempDir" value="/upload/"/> <!-- 上传后的目录名 (WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE) --> <property name="maxUploadSize" value="-1"/> <!-- 最大文件大小,-1为无限止(-1) --> </bean> |
3. 建立upload.jsp页面,内容如下:
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>测试springmvc中上传的实现</title> </head> <body> <form action="upload.do" method="post" enctype="multipart/form-data"> <input type="text" name="name" /> <input type="file" name="file" /> <input type="submit" /> </form> </body> </html> |
4. 建立控制器,代码如下:
package com.sxt.web;
import java.io.File; import java.util.Date;
import javax.servlet.ServletContext;
import org.springframework.stereotype.Controller; 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.context.ServletContextAware; import org.springframework.web.multipart.commons.CommonsMultipartFile;
@Controller public class FileUploadController implements ServletContextAware {
private ServletContext servletContext;
@Override public void setServletContext(ServletContext context) { this.servletContext = context; }
@RequestMapping(value="/upload.do", method = RequestMethod.POST) public String handleUploadData(String name,@RequestParam("file")[微软用户2] CommonsMultipartFile file){ if (!file.isEmpty()) { String path = this.servletContext.getRealPath("/tmp/"); //获取本地存储路径 System.out.println(path); String fileName = file.getOriginalFilename(); String fileType = fileName.substring(fileName.lastIndexOf(".")); System.out.println(fileType); File file2 = new File(path,new Date().getTime() + fileType); //新建一个文件 try { file.getFileItem().write(file2); //将上传的文件写入新建的文件中 } catch (Exception e) { e.printStackTrace(); } return "redirect:upload_ok.jsp"; }else{ return "redirect:upload_error.jsp"; } } } |
5. 建立upload_ok.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> </head> <body> <h1>上传成功!</h1> </body> </html> |
6. 建立upload_error.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> </head> <body> <h1>上传失败!</h1> </body> </html> |
进入项目发布后的目录,发现文件上传成功:
处理ajax请求
spring使用了jackson类库,帮助我们在java对象和json、xml数据之间的互相转换。他可以将控制器返回的对象直接转换成json数据,供客户端使用。客户端也可以传送json数据到服务器进行直接转换。使用步骤如下:
1. 项目中需要引入如下两个jar包:
jackson-core-asl-1.7.2jar
jackson-mapper-asl-1.7.2jar
2. spring配置文件中修改:
<mvc:annotation-driven /> <!-- 支持spring3.0新的mvc注解 --> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="cacheSeconds" value="0" /> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> </list> </property> </bean> |
- 客户端代码a.jsp如下:
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <% 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>My JSP ‘index.jsp‘ starting page</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"> <script> function createAjaxObj(){ var req; if(window.XMLHttpRequest){ req = new XMLHttpRequest(); }else{ req = new ActiveXObject("Msxml2.XMLHTTP"); //ie } return req; }
function sendAjaxReq(){ var req = createAjaxObj(); req.open("get","myajax.do?method=test2&uname=张三"); req.setRequestHeader("accept","application/json"); req.onreadystatechange = function(){ eval("var result="+req.responseText); document.getElementById("div1").innerHTML=result[0].uname; } req.send(null); } </script> </head>
<body> <a href="javascript:void(0);" onclick="sendAjaxReq();">测试</a> <div id="div1"></div> </body> </html>
|
- 服务器端代码如下:
package com.sxt.web;
import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody;
import com.sxt.po.User;
@Controller @RequestMapping("myajax.do") public class MyAjaxController {
@RequestMapping(params="method=test1",method=RequestMethod.GET) public @ResponseBody List<User> test1(String uname) throws Exception{ String uname2 = new String(uname.getBytes("iso8859-1"),"gbk"); System.out.println(uname2); System.out.println("MyAjaxController.test1()"); List<User> list = new ArrayList<User>(); list.add(new User("高淇","123")); list.add(new User("马士兵","456"));
return list; }
} |
- 测试。
a) 启动服务器。输入:http://localhost:8080/springmvc03/a.jsp
Spring中的拦截器
定义spring拦截器两种基本方式
- 实现接口:org.springframework.web.servlet.HandlerInterceptor。
接口中有如下方法需要重写:
注意:参数中的Object handler是下一个拦截器。
a) public boolean preHandle
(HttpServletRequest request,HttpServletResponse response,
Object handler) throws Exception
该方法在action执行前执行,可以实现对数据的预处理,比如:编码、安全控制等。
如果方法返回true,则继续执行action。
b)
public void postHandle
(HttpServletRequest request,HttpServletResponse response,
Object handler, ModelAndView
modelAndView) throws Exception
该方法在action执行后,生成视图前执行。在这里,我们有机会修改视图层数据。
c) public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception
最后执行,通常用于释放资源,处理异常。我们可以根据ex是否为空,来进行相关的异常处理。因为我们在平时处理异常时,都是从底层向上抛出异常,最后到了spring框架从而到了这个方法中。
- 继承适配器:
org.springframework.web.servlet.handler.HandlerInterceptorAdapter
这个适配器实现了HandlerInterceptor接口。提供了这个接口中所有方法的空实现。
如下我们写出两个拦截器的示例代码,仅供大家参考:
package com.sxt.interceptor;
import javax.interceptor.Interceptors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView;
public class MyInterceptor implements HandlerInterceptor {
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("最后执行!!!一般用于释放资源!!");
}
@Override public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("Action执行之后,生成视图之前执行!!"); }
@Override public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { System.out.println("action之前执行!!!"); return true; //继续执行action }
}
|
package com.sxt.interceptor;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class MyInterceptor2 extends HandlerInterceptorAdapter {
@Override public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { System.out.println("MyInterceptor2.preHandle()"); return true; //继续执行action }
} |
- XML中如何配置。如下为示例代码:
<mvc:interceptors> <bean class="com.sxt.interceptor.MyInterceptor"></bean> <!-- 拦截所有springmvc的url! --> <mvc:interceptor> <mvc:mapping path="/user.do" /> <!--<mvc:mapping path="/test/*" />--> <bean class="com.sxt.interceptor.MyInterceptor2"></bean> </mvc:interceptor> </mvc:interceptors> |
将属性u的值赋给形参uname
一定要加。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。