SpringMVC案例3----spring3.0项目拦截器、ajax、文件上传应用

依然是项目结构图和所需jar包图:



显示配置文件hib-config.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: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-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/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  http://www.springframework.org/schema/context   
   http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<context:component-scan base-package="com.sxt"></context:component-scan>
<!-- 支持aop注解 -->
<aop:aspectj-autoproxy></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/crud"></property>
	<property name="username" value="root"></property>
	<property name="password" value="root"></property>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
	<property name="dataSource">
		<ref bean="dataSource"></ref>
	</property>
	<property name="hibernateProperties">
		<props>
			<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"></property>
</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>

再是springmvc-servlet.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"    
    xmlns:mvc="http://www.springframework.org/schema/mvc"    
    xmlns:context="http://www.springframework.org/schema/context"    
    xmlns:util="http://www.springframework.org/schema/util"    
    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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd    
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
    <!-- 対web包中的全部的类进行扫描,以完毕bean的创建和自己主动依赖输入功能 -->
    <context:component-scan base-package="com.sxt"></context:component-scan>
    <!-- 启动springmvc的注解功能,完毕请求和注解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    	<property name="cacheSeconds" value="0"></property>
    	<property name="messageConverters">
    		<list>
    			<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    			</bean>
    		</list>
    	</property>
    </bean>
    <!-- 对模型视图名称的解析,即在模型视图名称加入前后缀 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
    	<property name="suffix" value=".jsp"></property>
    	<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    </bean>
    <!-- 处理文件上传 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    	<!-- 默认编码 -->
    	<property name="defaultEncoding" value="utf-8"></property>
    	<property name="maxInMemorySize" value="10240"/><!-- 最大内存大小 -->
    	<!-- 上传后的文件夹名 -->
    	<property name="uploadTempDir" value="/upload/"></property>
    	<!-- 最大文件大小,-1为无限制 -->
    	<property name="maxUploadSize" value="-1"></property>
    	
    </bean>
    <mvc:interceptors>
    	<!-- 拦截全部springmvc的url -->
    	<bean class="com.sxt.interceptor.MyInterceptor"></bean>
    	<mvc:interceptor>
    		<mvc:mapping path="/user.do"/>
    		<bean class="com.sxt.interceptor.MyInterceptor2"></bean>
    	</mvc:interceptor>
    </mvc:interceptors>
</beans>

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>springmvc</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/springmvc-servlet.xml
			</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>
dao层的userDao

package com.sxt.dao;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.sxt.po.User;
@Repository("userDao")
public class UserDao {
	@Autowired
	private HibernateTemplate hibernateTemplate ;
	
	public void add(User u){
		System.out.println("userDao.add()");
		hibernateTemplate.save(u) ;
	}
	
}

模型层的user类

package com.sxt.po;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
	private int id ;
	private String name ;
	private String pwd ;
	public User(){}
	public User(String name,String pwd){
		this.name = name ;
		this.pwd = pwd ;
	}
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	
	
}

service层的userService类
package com.sxt.service;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sxt.dao.UserDao;
import com.sxt.po.User;
@Service("userService")
public class UserService {
	@Autowired
	private UserDao userDao ;
	public void add(String name){
		System.out.println("UserService.add()");
		User u = new User() ;
		u.setName(name) ;
		userDao.add(u) ;
	}
	
}
controller层的userController类

package com.sxt.action;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.sxt.service.UserService;
@org.springframework.stereotype.Controller("userController")
@RequestMapping("/user.do")
@SessionAttributes({"uname"})
public class UserController{
	@Autowired
	private UserService userService ;
	@RequestMapping(params="method=reg")
	public String reg(String uname){
		System.out.println("UserController.reg()");
		userService.add(uname) ;
		return "index" ;
	}
	@RequestMapping(params="method=reg2")
	public String reg2(@RequestParam("uname")String name,ModelMap map){
		System.out.println("UserController.reg2()");
		userService.add(name) ;
		map.put("b", "bbb") ;
		return "index" ;
	}
	@RequestMapping(params="method=reg3")
	public String reg3(String uname,ModelMap map){
		System.out.println("UserController.reg3()");
		userService.add(uname) ;
		System.out.println(uname);
		map.put("uname", uname) ;
		return "index" ;
	}
	@RequestMapping(params="method=reg4")
	public String reg4(String uname,ModelMap map){
		System.out.println("UserController.reg4()");
//		return "forward:user.do?

method=reg3" ; //转发,不写默认就是转发 return "redirect:http://www.baidu.com" ;//重定向 } @RequestMapping(params="method=reg5") public String reg5(String uname){ System.out.println("UserController.reg4()"); return "redirect:http://www.baidu.com" ;//重定向 } }


MyAjaxController类

package com.sxt.action;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

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.ResponseBody;

import com.sxt.po.User;
@Controller
@RequestMapping("myajax.do")
public class MyAjaxController {
	@RequestMapping(params="method=test2",method=RequestMethod.GET)
	public @ResponseBody List<User> test1(String uname) throws Exception{
		String uname2 = new String(uname.getBytes("iso8859-1"),"utf-8") ;
		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")) ;
		System.out.println(list.size());
		return list ;
	}
}

FileUoLoadController类

package com.sxt.action;

import java.io.File;
import java.util.Date;

import javax.servlet.ServletContext;

import org.apache.log4j.chainsaw.Main;
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("fileUpLoadController")
public class FileUpLoadController implements ServletContextAware{
	private ServletContext servletContext ;
	@Override
	public void setServletContext(ServletContext servletContext) {
		// TODO Auto-generated method stub
		this.servletContext = servletContext ;
	}
	@RequestMapping(value="/upload.do",method=RequestMethod.POST)
	public String handleUploadData(String name,@RequestParam("file")CommonsMultipartFile file){
		if(!file.isEmpty()){
			//获取本地存储路径,必须在项目下建立一个这种路径
			String path = this.servletContext.getRealPath("/upload/") ;
			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) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "redirect:upload_ok.jsp" ;
		}else{
			return "redirect:upload_error.jsp" ;
		}
	}
}

拦截器层的MyInterceptor类

package com.sxt.interceptor;

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 arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("最后运行,一般用于释放资源!!!");
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("action运行之后,生成视图之前!。");
	}

	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("action之前运行");
		return true;
	}

}

MyInterceptor2类

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 {
		// TODO Auto-generated method stub
		System.out.println("MyInterceptor2.preHandle()");
		return true;
	}
}

用于測试ajax的a.jsp文件

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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 'a.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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script>
		function createAjaxObj(){
			var req ;
			if(window.XMLHttpRequest){
				req = new XMLHttpRequest() ;
			}else{
				req = new ActiveXObject("Msxml2.XMLHTTP") ;
			}
			return req ;
		}
		function sendAjaxReq(){
			var req = createAjaxObj() ;
			req.open("get","myajax.do?method=test2&uname=张三") ;
			req.setRequestHeader("accept","application/json") ;
			req.onreadystatechange = function(){
				var msg = req.responseText ;
				eval("var result=" + msg) ;
				document.getElementById("div1").innerHTML = result[0].name ;
			}
			req.send(null) ;
		}
	</script>
  </head>
  
  <body>
    <a href="javascript:void(0);" onclick="sendAjaxReq();">測试</a>
    <div id="div1"></div>
  </body>
</html>

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
  	${requestScope.uname} <br />
  	${sessionScope.uname} <br />
  </body>
</html>

index2.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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 'index2.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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <form action="user.do">
    	姓名:<input type="text" name="uname"/><br />
    	<input type="hidden" name="method" value="reg3">
    	<input type="submit" value="注冊 " />
    </form>
  </body>
</html>

upload_error.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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 'upload_error.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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    	<h1>上传失败!</h1>
  </body>
</html>

upload_ok.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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 'upload_ok.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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    	<h1>上传成功!

</h1> </body> </html>


upload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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>測试springmvc中的上传的实现</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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </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>

至此整个springmvc重要的东西測试完成!


posted @ 2017-06-19 20:51  yfceshi  阅读(623)  评论(0编辑  收藏  举报