1. 程式人生 > >SpringMVC案例3----spring3.0項目攔截器、ajax、文件上傳應用

SpringMVC案例3----spring3.0項目攔截器、ajax、文件上傳應用

his water aop pro 文件夾 創建 adapt 後綴 實現

依然是項目結構圖和所需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重要的東西測試完成!


SpringMVC案例3----spring3.0項目攔截器、ajax、文件上傳應用