springMVC的高级数据绑定,以及json交互,全局异常配置,

一.窄化请求映射javascript

 

1.在class上添加@RequestMapping(url)指定通用请求前缀, 限制此类下的全部方法请求url必须以请求前缀开头,经过此方法对url进行分类管理。html

以下:前端

 

@Controllerjava

 

@RequestMapping("/item")   //放在类名上边,设置请求前缀,必须带前缀才能访问git

2.请求方法限定web

 

若是没有限定请求的方法,默认是支持全部的方法(get,post,put,deleteajax

 

u限定GET方法spring

 

@RequestMapping(method = RequestMethod.GET)  加在方法上,表示只能用get方式请求;apache

若是用post请求择报错:  HTTP Status 405 - Request method 'POST' not supportedjson

method能够是一个数组配置多个

GETPOST均可以

@RequestMapping(method={RequestMethod.GET,RequestMethod.POST})

package com.ssm.controller;

import java.io.File;
import java.util.List;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
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 org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ssm.pojo.Item;
import com.ssm.pojo.QueryVo;
import com.ssm.service.IItemService;
import com.ssm.utils.MD5Utils;
import com.ssm.utils.UploadUtils;

@Controller
@RequestMapping("/item")  表示必须在/item下才能访问到,如http://localhost:8080/item/list.action
public class ItemController {
    @Resource
    private IItemService itemService;
   
//
查询全部商品 @RequestMapping(value="/list.action",method={RequestMethod.GET,RequestMethod.POST}) public ModelAndView findItemByAll() throws Exception{ ModelAndView modelAndView = new ModelAndView(); List<Item> list = itemService.findItemByAll(); modelAndView.addObject("itemList", list); modelAndView.setViewName("itemList"); return modelAndView; }
}

controller的返回值能够有三种

第一种:

返回ModelAndView

package com.ssm.controller;

import java.io.File;
import java.util.List;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
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 org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ssm.pojo.Item;
import com.ssm.pojo.QueryVo;
import com.ssm.service.IItemService;
import com.ssm.utils.MD5Utils;
import com.ssm.utils.UploadUtils;

@Controller
//@RequestMapping("/item")  表示必须在/item下才能访问到,如http://localhost:8080/item/list.action
public class ItemController {
    @Resource
    private IItemService itemService;
    
    //查询全部商品
    @RequestMapping(value="/list.action",method={RequestMethod.GET,RequestMethod.POST})
    public ModelAndView findItemByAll() throws Exception{
        ModelAndView modelAndView = new ModelAndView();
            List<Item> list = itemService.findItemByAll();
            modelAndView.addObject("itemList", list);
            modelAndView.setViewName("itemList");
        return  modelAndView;
    }

}

第二种

返回void

controller方法形参上能够定义requestresponse,使用requestresponse指定响应结果:

 

1、使用request转向页面,以下:

request.getRequestDispatcher("页面路径").forward(request, response);

@RequestMapping("/itemEdit")
        public void findItemById(HttpServletRequest request,HttpServletResponse response,Integer id){
            try {
                Item item = itemService.findItemById(id);
                request.setAttribute("item", item);
                request.getRequestDispatcher("/WEB-INF/jsp/itemEdit.jsp").forward(request, response);
            } catch (ServletException | IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

 

2、也能够经过response页面重定向:

response.sendRedirect("url")

@RequestMapping("/itemEdit")
        public void findItemById(HttpServletRequest request,HttpServletResponse response,Integer id){
            try {
                response.sendRedirect(request.getContextPath()+"/list.action");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

 

3、也能够经过response指定响应结果,例如响应json数据以下:

response.setCharacterEncoding("utf-8");

response.setContentType("application/json;charset=utf-8");

response.getWriter().write(json对象);

@RequestMapping("/itemEdit")
        public void findItemById(HttpServletRequest request,HttpServletResponse response,Integer id){
            try {
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write("json");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

第三中方式:

返回字符串,其实返回的不是字符串,而是逻辑视图的名字

 

1.redirect方式至关于“response.sendRedirect()”,转发后浏览器的地址栏变为转发后的地址,由于转发即执行了一个新的requestresponse

2.forward方式至关于“request.getRequestDispatcher().forward(request,response)”,转发后浏览器地址栏仍是原来的地址。转发并无执行新的requestresponse,而是和转发前的请求共用一个requestresponse。因此转发前请求的参数在转发后仍然能够读取到

 

 

@RequestMapping("/batchEdit")
    public String bachEdit(QueryVo vo){ 
        if(vo!=null){
            itemService.updateBatch(vo);
        }
//        转发
//        return "forward:/list.action";
        return "redirect:list.action";
    }

 


springMVC的全局异常处理,就是当前端控制器收到异常时,咱们要判断是语气异常仍是运行异常,而后作出处理

1.预期异常,通常跳转到一个页面,给用户提示响应的信息

2:运行异常:   A:先打印到日志文件中   B:发短信或者邮件告诉维护文员  C: 给用户友好提示

第一步:先定义一个本身的异常类,全部的预期异常都由这个类或子类抛出

package com.ssm.exception;
/**
 * 自定义异常给客户友好提示
 * @author Administrator
 *
 */

public class CustomerException extends Exception {
    
    private String message;

    public CustomerException(String message) {
        super();
        this.message = message;
    }

    public CustomerException() {
        super();
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
    
    
}

第二部自定义异常处理器

package com.ssm.exception;

import java.util.Properties;

import javax.mail.Session;
import javax.management.loading.PrivateClassLoader;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.aspectj.weaver.patterns.ThisOrTargetAnnotationPointcut;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.ssm.utils.MailUtils;

/**
 * 自定义异常处理器
 * @author Administrator
 *
 */
public class CustomerExceptionResolver implements HandlerExceptionResolver {
    private final Logger logger=Logger.getLogger(this.getClass());
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
         
        CustomerException customerException=null;
        //若是抛出的是自定义的异常就强转为自定义的异常
        if(ex instanceof CustomerException){
            //强转为自定义的异常
             customerException=(CustomerException) ex;
        }else{
            //若是不是自定义的异常就给用户友好提示
            //打印日志
            logger.error(ex.getMessage(), ex); 
            
            //给开发人员发短信或邮件
            //邮箱属性
            final Properties mailProps = new Properties();
            //smtp服务器
            mailProps.put("mail.smtp.host", "smtp.126.com");
            mailProps.put("mail.smtp.auth", "true");
            //邮箱用户名
            mailProps.put("mail.username", "helloword110110@126.com");
                //受权码
            mailProps.put("mail.password", "hello110");
            
            Session mailSession=MailUtils.getMailSession(mailProps); 
            String sendMessage=this.getClass().getName()+"有异常须要处理";
                                   //邮箱标题            // 邮箱会话      //邮箱属性      //须要发送的信息   //发送的邮箱地址
            MailUtils.sendMail("有异常赶忙解决", mailSession, mailProps, sendMessage,"jiangxiangit@163.com");
            //而后给出友好提示
            customerException = new CustomerException("您的网络出现了故障,请稍后再试"); 
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("exceptionMessage",customerException.getMessage());
        mv.setViewName("error"); 
        return mv;
    }

}

发送邮件的工具类

package com.ssm.utils; import java.io.Serializable; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message.RecipientType; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /** * 发送邮件工具类 */ public class MailUtils implements Serializable { /** * 获取邮箱会话 */ public static Session getMailSession(final Properties mailProps){ try { /*final Properties mailProps = new Properties(); mailProps.put("mail.smtp.host", this.getSmtpServer()); mailProps.put("mail.smtp.auth", "true"); mailProps.put("mail.username", this.getUsername()); mailProps.put("mail.password", this.getPassword());*/ // 构建受权信息,用于进行SMTP进行身份验证 Authenticator authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { // 用户名、密码 String userName = mailProps.getProperty("mail.username"); String password = mailProps.getProperty("mail.password"); return new PasswordAuthentication(userName, password); } }; // 使用环境属性和受权信息,建立邮件会话 Session mailSession = Session.getInstance(mailProps, authenticator); System.out.println("邮箱登陆成功"); return mailSession; } catch (Exception ex) { ex.printStackTrace(); return null; } } /** * 发送邮件 * @param title 邮件标题 * @param mailSession 邮箱会话 * @param mailProps 邮箱属性 * @param sendMessage 须要发送的信息 * @param toAddress 发送的邮箱地址 */ public static void sendMail(String title,Session mailSession,Properties mailProps,String sendMessage, String toAddress) { System.out.println("要发邮件了。。。"); try { // 建立邮件消息 MimeMessage message = new MimeMessage(mailSession); // 设置发件人 InternetAddress from = new InternetAddress(mailProps.getProperty("mail.username")); message.setFrom(from); // 设置收件人 InternetAddress to = new InternetAddress(toAddress); message.setRecipient(RecipientType.TO, to); // 设置邮件标题  message.setSubject(title); // 设置邮件的内容体 message.setContent(sendMessage, "text/html;charset=UTF-8"); // 发送邮件  Transport.send(message); } catch (Exception ex) { ex.printStackTrace(); } } }

 

第三部:配置到配置前端异常请求页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${exceptionMessage }
</body>
</html>

 

第四部:配置配置文件  springmvc.xml

<!--配置异常处理器  handlerExceptionResolver  必须是这个  -->
         <bean id="handlerExceptionResolver" class="com.ssm.exception.CustomerExceptionResolver"></bean>

springmvc的文件上传:

首先是前台页面:form表单中必须配置enctype="multipart/form-data",而且name="pictureFile" 的那么值必须与后提的形式参数变量名一致

<form id="itemForm"    action="${pageContext.request.contextPath }/updateItem.action" method="post" enctype="multipart/form-data">
          
          <tr>
          <td> <c:if test="${item.pic !=null}"> <img src="/pic${item.pic}" width=100 height=100/> <br/> </c:if> <input type="file" name="pictureFile"/> </td></tr>        <tr> <td colspan="2" align="center"><input type="submit" value="提交" /> </td> </tr> </table> </form>

第二步:

添加jar

CommonsMultipartResolver解析器依赖commons-fileuploadcommons-io

第三步:在springmvc.xml配置文件上传解析器

<!--配置文件上传的解析器  ,id必须写这个-->
         <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
                 <!-- 设置上传文件最大为5MB,支持用1024*1024*5的方式 -->
                 <property name="maxUploadSize">
                     <value>5242880</value>
                 </property>
                 <!--设置默认编码  -->
                 <property name="defaultEncoding" value="UTF-8"></property>
         </bean>

第四步业务代码:

//更新时修改图片
@RequestMapping("/updateItem") //前端页面传递的name必须和变量名如:pictureFile一致 public String updateItem(Item item,MultipartFile pictureFile){ //获取文件原始名 String pictureName = pictureFile.getOriginalFilename(); //获取文件的后缀 String nameSuffix = pictureName.substring(pictureName.lastIndexOf(".")); try { //获取文件的md5值 String fileMD5 = MD5Utils.getFileMD5(pictureFile); //经过md5的值获取文件应该保存的路径 String filDir = UploadUtils.getDir(fileMD5); //新的文件路径名以及文件名如 0/2/5/a.jpg String newName=filDir+"/"+fileMD5+nameSuffix; //须要上传的文件 File uploadFile = new File("E:/upload/picture"+newName); //若是不存在这个文件,就写到磁盘 if(!uploadFile.exists()){ //建立文件 uploadFile.mkdirs(); //向磁盘写文件 pictureFile.transferTo(uploadFile); } item.setPic(newName); } catch (Exception e) { e.printStackTrace(); } itemService.updateItem(item); return "redirect:list.action"; }

下面是几个工具类的

1.md5

package com.ssm.utils;  
  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.InputStream;  
import java.math.BigInteger;  
import java.security.MessageDigest;

import org.springframework.web.multipart.MultipartFile;  
/** 
 * 获取文件的md5值,从而比对两个文件是否相等 
* @Description: TODO 
* @author jixiang 
* @date 2015年6月1日 上午9:34:15  
* @version V1.0 
 */  
public class MD5Utils {  
    //根据文件路径获取md5值
    public static String getFileMD5(String filePath) throws Exception{  
        File file = new File(filePath);  
        InputStream in = new FileInputStream(file);  
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");  ;  
            byte buffer[] = new byte[8192];  
            int len;  
            while((len = in.read(buffer))!=-1){  
                digest.update(buffer, 0, len);  
            }  
            BigInteger bigInt = new BigInteger(1, digest.digest());   
            return bigInt.toString(16).toUpperCase();
        } catch (Exception e) {
            
            e.printStackTrace();
        }  finally{
            in.close();
        }
        return null;
    }
    //根据上传文件获取md5的值
    public static String getFileMD5(MultipartFile uploadFile) throws Exception{  
        byte[] uploadFileBytes = uploadFile.getBytes();
        MessageDigest digest = MessageDigest.getInstance("MD5");  ;  
        BigInteger bigInt = new BigInteger(1, digest.digest(uploadFileBytes));   
        return bigInt.toString(16).toUpperCase();  
    }  
   
    public static void main(String[] args) throws Throwable{  
        String f1 = getFileMD5("E:\\upload\\8\\0\\e0207632-77f5-4dd1-8085-31c228627357 - 副本.png");  
        String f2 = getFileMD5("E:\\upload\\8\\0\\e0207632-77f5-4dd1-8085-31c228627357.png");  
        System.out.println(f1.equals(f2)+"=="+f1);  
    }  
}

2是因为可能会有不少的图片都放在一个文件夹中,查找慢,而且,不便于管理,建立目录的工具类

package com.ssm.utils;



import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.BeanUtils;

public class UploadUtils {
    /**
     * 获取随机名称
     * @param realName 真实名称
     * @return uuid
     */
    public static String getUUIDName(String realName){
        //realname  多是  1.jpg   也多是  1
        //获取后缀名
        int index = realName.lastIndexOf(".");
        if(index==-1){
            return UUID.randomUUID().toString().replace("-", "").toUpperCase();
        }else{
            return UUIDUtils.getId()+realName.substring(index);
        }
    }
    
    /**
     * 11.bmp
     * 获取文件真实名称
     * @param name
     * @return
     */
    public static String getRealName(String name){
        // c:/upload/11.bmp    1.jpg
        //获取最后一个"/"
        int index = name.lastIndexOf("\\");
        return name.substring(index+1);
    }
    
    /**
     * 获取文件目录
     * @param name 文件名称
     * @return 目录
     */
    public static String getDir(String name){
        int i = name.hashCode();
        String hex = Integer.toHexString(i);
        int j=hex.length();
        for(int k=0;k<8-j;k++){
            hex="0"+hex;
        }
        return "/"+hex.charAt(0)+"/"+hex.charAt(1)+"/"+hex.charAt(2)+"/"+hex.charAt(3)+"/"+hex.charAt(4)+"/"+hex.charAt(5)+"/"+hex.charAt(6)+"/"+hex.charAt(7);
    }
    
    @SuppressWarnings("unused")
    public static void main(String[] args) {
        //String path=getDir("1432142142142.bmp");
        //System.out.println(path);
        
        //String val=getUUIDName("11.bmp");
        //System.out.println(val);
        
        String val=getRealName("c:\\1\\2\\1.bmp");
        System.out.println(val);
    }
    
}

3.uuid转换为大写的字符串

package com.ssm.utils;

import java.util.UUID;

public class UUIDUtils {
    public static String getId(){
        return UUID.randomUUID().toString().replaceAll("-", "").trim().toUpperCase();
    } 
}

json数据的交互

1前端页面代码,最好用ajax进行请求,由于$.ajax能够设置contentType:"application/json;charset=utf-8",由于(默认: "application/x-www-form-urlencoded") 这种格式发送信息至服务器时内容编码类型,若是直接用post或者get,有可能传过去不是application.json的格式,而你若是加了@RequestBody的注解就会报错

<script type="text/javascript">
    function sendJson(){
        var url=
        $.ajax({
            type:'post',
            url:"${pageContext.request.contextPath }/sendJson.action",
            data:'{"name":"张三","price":18}',
            contentType:"application/json;charset=utf-8",
            success:function(data){
                alert("a")
                alert(data)
            }
        });
    }

</script>

<body>
<input type="button" value="发送json" onclick="sendJson()"/>
</body>

在导入json须要的jar包

 

配置文件:若是配置了<mvc:annotation-driven/>就不用管

若是没配这个须要配上下面的

<!--配置式处理器映射器,对类中标记@ResquestMapping的方法进行映射,
         根据ResquestMapping定义的url匹配ResquestMapping标记的方法
         ,匹配成功返回HandlerMethod对象给前端控制器,HandlerMethod对象中封装url对应的方法Method。
         不配置的会用默认的org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping
         可是从spring3.1版本开始已经被废除了,官方推荐使用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
     -->
      <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
     
     
     <!--
         注解式处理器适配器,对标记@ResquestMapping的方法进行适配。
         不配置会用默认的org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
        从spring3.1版本开始,废除了AnnotationMethodHandlerAdapter的使用,
        推荐使用RequestMappingHandlerAdapter完成注解式处理器适配。
       -->
       <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
               配置json转换器,在注解适配器中加入messageConverters,
               <propertyname="messageConverters">
            <list>
                <beanclass="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
            </list>
        </property>
       
       </bean>

 

@RequestBody

做用:

@RequestBody注解用于读取http请求的内容(字符串),经过springmvc提供的HttpMessageConverter接口将读到的内容转换为jsonxml等格式的数据并绑定到controller方法的参数上。

 

本例子应用:

@RequestBody注解实现接收http请求的json数据,json数据转换为java对象

 

 @ResponseBody

做用:

该注解用于将Controller的方法返回的对象,经过HttpMessageConverter接口转换为指定格式的数据如:json,xml等,经过Response响应给客户端

//json交互
    @RequestMapping("/sendJson")
    //@ResponseBody表示将java对象转成json对象
    //@RequsetBody表示将json对象转java成对象
    public @ResponseBody Item sendJson(HttpServletResponse response,@RequestBody Item item,HttpServletRequest request){

        
        return item;
    }

 


 

springmvc  的Restful风格

Restful就是一个资源定位及资源操做的风格。不是标准也不是协议,只是一种风格,是对http协议的诠释。

第一步,将<url-pattern>*.action</url-pattern>改成<url-pattern>/</url-pattern>拦截除了jsp页面的全部

 

 <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
  <--<url-pattern>*.action</url-pattern>--> <url-pattern>/</url-pattern> </servlet-mapping>

 

第二步在springmvc.xml的配置文件中配置不拦截静态资源

    <!-- 配置不拦截静态资源 location="/js/":表示js下路径的不拦截,/js/**,表示包及其子包下面的都不拦截 -->
    <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>

第三步将请求的参数方式改变

<--<td><a href="${pageContext.request.contextPath }/itemEdit?id=${item.id}">修改</a></td>-->
<--改为-->
<td><a href="${pageContext.request.contextPath }/itemEdit/${item.id}">修改</a></td>

第四部修改代码

    //根据Id查询商品 :第四种方式:经过model或者modelMap,返回值就能够撒设成String,返回的是视图的名称
  //{}表示占位符大括号内的值要和参数名子一致才能取到,而且这里的有几个参数,页面要传几个参数才能访问,如如今必须传两个
  //@PathVariable注解 表示这个值是大括号嫩的值 @RequestMapping("/itemEdit/{id}/{name}") public String findItemById(@PathVariable Integer id,@PathVariable String name,Model model,ModelMap modelMap){ Item item = itemService.findItemById(id); modelMap.addAttribute("item", item); return "itemEdit"; }

springmvc的拦截器配置

自定义一个拦截器实现handlerInterceptor 接口

package com.ssm.hindlerInterceptor;

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

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
 * 模拟未登陆拦截
 * @author Administrator
 *
 */
public class LoginHindlerInterceptor  implements HandlerInterceptor{
    /**
     * 在controller执行后,且已经返回视图后执行此方法
     *  这里可获得执行controller时的异常信息
     * 这里可记录操做日志,资源清理等
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception arg3)
            throws Exception {
    }
    
    /**
     * 在controller执行后,但未返回视图前调用此方法
     * 这里可在返回用户前对模型数据进行加工处理,好比这里加入公用信息以便页面显示u
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
            throws Exception {
    }
    
    /**
     * controller执行前调用此方法
     * 返回true表示继续执行,返回false停止执行
     * 这里能够加入登陆校验、权限拦截等
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //首先从当前的url中获取访问的路径,若是/user/showLogin 和/user/Login (不须要拦截)
        String pathrequest = request.getRequestURL().toString();
        if(pathrequest.contains("login")){
            return true;
        }
        if(request.getSession().getAttribute("user")==null){
            response.sendRedirect(request.getContextPath()+"/showlogin");
            return false;
        }
        return true;
    }

}

配置配置文件

<!--配置拦截器 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--path="/**" 表示拦截全部  -->
            <mvc:mapping path="/**" />
            <bean class="com.ssm.hindlerInterceptor.MyHindlerInterceptor1"></bean>
        </mvc:interceptor>
        <mvc:interceptor>
            <mvc:mapping path="/**" />
            <bean class="com.ssm.hindlerInterceptor.MyHindlerInterceptor2"></bean>
        </mvc:interceptor>
        <mvc:interceptor>
            <mvc:mapping path="/**" />
            <bean class="com.ssm.hindlerInterceptor.LoginHindlerInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

拦截器的执行顺序

HandlerInterceptor1..preHandle..

HandlerInterceptor2..preHandle..

 

HandlerInterceptor2..postHandle..

HandlerInterceptor1..postHandle..

 

HandlerInterceptor2..afterCompletion..

HandlerInterceptor1..afterCompletion.

 

prehandle方法是顺序,先配置(在springmvc.xml上面些的)的先执行;

postHandle和afterCompletion是倒序,先配置的后执行

登录拦截的模拟实现controller代码

@RequestMapping("/login")
    public String Login(String username,String password,HttpSession session){
        
        if(username.equalsIgnoreCase("admin")&&password.equals("admin")){
            session.setAttribute("user","user"); 
        }
        return "redirect:list";
    }
    @RequestMapping("/showlogin")
    public String showlogin(){
        
        return "login";
    }

前端页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <a href="http://localhost:8080/spring_ssm_second/list">查看全部订单</a> 
    <form action="${pageContext.request.contextPath }/login" method="post">
        用户名:<input type="text" name="username"/>
        密    码:<input type="text" name="password"/>
              <input type="submit" value="登录"/>
    </form>
</body>
</html>
相关文章
相关标签/搜索