针对springmvc做的简单异常处理机制


1:运用springmvc的和spring框架打搭建需要用到的包,这边只贴出maven依赖,其中异常处理机制的包包含在spring-web.jar包中,依赖如下:

   
		4.1.6.RELEASE
		2.4.3
		UTF-8
		true
		1.8
  

   			
				org.springframework
				spring-context
				${spring.version}
			

			
				org.springframework
				spring-context-support
				${spring.version}
			

			
				org.springframework
				spring-webmvc
				${spring.version}
			

			
				org.springframework
				spring-test
				${spring.version}
			

			
				org.springframework
				spring-jdbc
				${spring.version}
			

			
				org.springframework
				spring-tx
				${spring.version}
			
			
			
			
				org.springframework
				spring-web
				${spring.version}
						
		



 
  

 
  

2:编写一个BaseController.java的抽象类,用到的是ExceptionHandler这个注解。

package com.mavenspring.demo.baseexception;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ExceptionHandler;

/**   
 * @Title: BaseController.java 
 * @Package com.mavenspring.demo.controller 
 * @Description: TODO(基础的异常处理类,一般要使用到异常处理的类都要继承这个类
 * Service层要使用这个类需要把request作为参数传入,不过一般只在控制层做最高层处理就可以) 
 * @author 
 * @date 2015年12月15日 下午3:41:32 
 * @version V1.0   
 */
public abstract class BaseController {  

    @ExceptionHandler
    public String exception(HttpServletRequest request, Exception e) {
        request.setAttribute("exceptionMessage", e.getMessage());         
        // 根据不同的异常类型进行不同处理
        if(e instanceof SQLException) 
            return "testerror";   
        else
            return "error";  
    }      
}

3:编写你所需要的Exception,不管是业务Exception还是其他异常,我这边编写了一个LoginException,继承Exception

package com.mavenspring.demo.exception;
/**   
 * @Title: LoginException.java 
 * @Package com.mavenspring.demo.exception 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @author 
 * @date 2015年12月15日 下午3:55:53 
 * @version V1.0   
 */
public class LoginException extends Exception {

	private static final long serialVersionUID = -214315462314311L;
	
	public LoginException(String message){
		super(message);
	}

}
 

4:最后在你自己的Controller里面继承这个BaseController然后抛出你自己的异常,在BaseController里面捕捉后会跳转到指定的报错页面。那个字符串就是页面路径名。以下贴出我自己的controller

package com.mavenspring.project.controller;

import java.io.IOException;
import java.util.Iterator;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.mavenspring.demo.baseexception.BaseController;
import com.mavenspring.demo.exception.LoginException;
import com.mavenspring.demo.helper.CacheCenter;
import com.mavenspring.demo.model.ProjectUser;
import com.mavenspring.demo.model.TestStudent;
import com.mavenspring.demo.model.req.AddUserReq;
import com.mavenspring.demo.model.req.ProjectUserReq;
import com.mavenspring.demo.redis.JedisTemplate;
import com.mavenspring.demo.statics.StaticResource;
import com.mavenspring.demo.util.FileUpLoadUtil;
import com.mavenspring.project.service.ProjectUserService;

/**
 * @Title: LoginController.java
 * @Package com.mavenspring.project.controller
 * @Description:用来处理用户登录等一些登录系统相关的controller
 * @author 
 * @date 2015年12月13日 下午6:52:52
 * @version V1.0
 */

@Controller
public class LoginController extends BaseController {
	
    @Autowired
    private CacheCenter cache;

	@Autowired
	private JedisTemplate jedisTemplate;
	
	private RestTemplate restTemplate = new RestTemplate();

	private static final Logger LOG = Logger.getLogger(LoginController.class);

	@Autowired
	private ProjectUserService projectUserService;

	@RequestMapping(value = "/")
	public String index(HttpServletRequest request) {
		return "login";
	}

	// 跳轉到用戶登錄界面
	@RequestMapping(value = "/login")
	public String userLoginVm(HttpServletRequest request) {
		return "login";
	}

	// 用戶登錄的時候進行驗證
	@RequestMapping(value = "/user/login", method = RequestMethod.POST)
	public String userLogined(HttpServletRequest request, Model model,
			HttpServletResponse response) throws LoginException {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");

		if ((userName != "" || userName != null)
				&& (password != null || password != "")) {
			if (projectUserService.userValidtor(userName, password)) {

				String uuid = UUID.randomUUID().toString();
				jedisTemplate.setex(StaticResource.USER_CLIENT + uuid, 60 * 60,
						userName);
				addAuthCookies(response, uuid);
				ProjectUserReq projectUserReq = new ProjectUserReq();
				projectUserReq.setAge(0);
				projectUserReq.setUserName(userName);
				model.addAttribute("userList",
						projectUserService.getAllProjectUser(projectUserReq));
				
				/*缓存*/
//				cache.put("loginUserUserName", userName, "loginUser");
//				cache.put("loginUserPassword", password, "loginUser");							
//				TestStudent testStudent = new TestStudent("张三","213");
//				cache.put("testStudent", testStudent, "testStudent");
//				TestStudent test = (TestStudent) cache.read("testStudent", "testStudent");
				/*缓存*/
				
				return "user/userlist";
			}
		}
		throw new LoginException("=========用户异常登录,请重新确认账号密码登录!==========");
	}

	
	//用户添加
	@ResponseBody
	@RequestMapping(value = "/user/added",method = RequestMethod.POST)
	public String  saveNewUser(	
			AddUserReq addUserReq, HttpServletRequest request, HttpServletResponse response)
			throws IOException, LoginException {
		
		String path = request.getSession().getServletContext().getRealPath("/")+ "downloadimgs\\";
		 CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
	        //判断 request 是否有文件上传,即多部分请求  
	        if(multipartResolver.isMultipart(request)){  
	            //转换成多部分request    
	            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
	            //取得request中的所有文件名  
	            Iterator iter = multiRequest.getFileNames(); 
	            int i=1;
	            while(iter.hasNext()){  
	            	
	                //记录上传过程起始时的时间,用来计算上传时间  
	                int pre = (int) System.currentTimeMillis();  
	                //取得上传文件  
	                MultipartFile file = multiRequest.getFile(iter.next());  
	                if(file != null){  
	                    //取得当前上传文件的文件名称                 
	                    String myFileName = file.getOriginalFilename();  
	                    System.out.println("============="+myFileName);
	                    String personLastImgUrl = FileUpLoadUtil.saveFileToServer(file,path);
	                    System.out.println("============="+personLastImgUrl);
	                    ProjectUser projectUser = new ProjectUser();
	            		projectUser.initUserByaddUserReq(addUserReq);
	            		projectUser.setPersonImgUrl(myFileName);
	            		LOG.info("========================保存文件的路径:" + personLastImgUrl + "==="+ addUserReq.getAddress());
	            		int result = projectUserService.insertProjectUser(projectUser);
	            		if (result > 0) {		
	            			return "success";
	            		}
	            		throw new LoginException("=========用户add error!==========");
	                }
	            }
	        }
	        throw new LoginException("=========用户add error!==========");
	}
	


}

注:我上面这个controller包含了一些缓存,redis的使用,大家关于这个异常处理只看抛出和继承就可以,前端传值这边没有贴代码,相信大家都会。至于想要学习redis和ehcache的可以看其他两篇博客。redis会在最近总结。谢谢!



你可能感兴趣的:(异常处理机制,异常处理,springmvc异常)