简述spring3 mvc核心

原创
2013/05/06 17:25
阅读数 955

疯狂的周末过后,今天拖着疲惫的身体。没有工作状态,于是总结几点spring3 mvc 的核心内容吧!包括不解之处能与大家讨论讨论!

虽然struts2功能强大,使得javaweb开发更加条理有序,代码整洁美观,方便维护。但是struts2的执行效率相对较低,学习难度也相对spring mvc偏高,复杂!个人认为常规的web开发spring mvc足已!下面简单总结总结:

一、在struts2中相信大家对ModelDriven<T>(数据模型驱动)不陌生吧!那么在spring3 mvc中也提供了相似的功能(我不解的是看到身边的同事居然在用request取form的值,代码复杂!!我个人不喜欢,看着头痛!)    --数据模型(将表单数据直接封装成entity)只需要将请求方法定义为带entity的参数方法,在jsp中input的name属性和entity属性名一致(不知还有其他方式?求分享!)


public Map<String, Object> deleteStudent(@ModelAttribute Student student){
 
 studentbiz.delete(student.getStudentId());
 
 return null;    //伪代码,主要看结构
 }
二、json数据,首先在springmvc-config.xml中配置(别忘记添加jackson-core-asl-1.9.2.jar,jackson-mapper-asl-1.9.2.jar)


<!-- json支持 -->
	 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		 <property name="messageConverters">
			  <list>
			   		<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
			  </list>
		 </property>
	</bean>
实现请求方法(添加@ResponseBody即可)


       @RequestMapping(value="deleteStudent")
	@ResponseBody
	public Map<String, Object> deleteStudent(@ModelAttribute Student student){
		Map<String,Object> data = new HashMap<String, Object>();
		try {
			studentbiz.delete(student.getStudentId());
			data.put("flag", true);
			data.put("msg", "删除成功!");
		} catch (Exception e) {
			data.put("flag", false);
			data.put("msg", "删除失败!");
		}
		return data;
	}
三、数据校验(这个头痛,望高手指点一二)


先定义验证器:

package com.test.web.validators;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.test.bean.User;

/**
 * 用户验证器
 * @author Administrator
 *
 */
public class UserValidator implements Validator{

	@Override
	public boolean supports(Class<?> zlass) {
		return User.class.isAssignableFrom(zlass);
	}

	@Override
	public void validate(Object object, Errors errors) {
		User user = (User)object;
		ValidationUtils.rejectIfEmpty(errors,"userName", "required", "用户名不能为空!");
		ValidationUtils.rejectIfEmpty(errors,"password", "required", "密码不能为空!");
		int len = user.getUserName().length();
		if (len>0) {
			if (len<2 || len>20) {
				errors.rejectValue("userName","user.userName.too_long","用户名在2-20个字符!");
			}
		}
		len = user.getPassword().length();
		if (len>0) {
			if (len<6 || len>10) {
				errors.rejectValue("password","user.password.too_long","密码在2-20个字符!");
			}
		}
	}
}
在Controller中引用


package com.test.web.controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.test.bean.User;
import com.test.web.validators.UserValidator;


@Controller
// 改注解可以省略,可以表示访问的包名吧
@RequestMapping("/user")
public class UserController{
	
	// 初始化绑定了一个自定义验证器,后续做介绍,忽略。。。
	@InitBinder
	protected void initBinder(WebDataBinder binder){
		binder.setValidator(new UserValidator());
	}
	// 请求映射,value和表单的action一致,mothod表明表单的提交方式 @Validated指定了user对象需要验证
	 @RequestMapping(value="hello",method=RequestMethod.POST)
	 public ModelAndView helloWorld(@Validated User user,BindingResult result,Model model) {
		 if (result.hasErrors()) {
			 // 回填表单信息,不至于用户请求失败后,数据清空
			model.addAttribute("user", user);
			// 请求结果跳转的视图名称
			return new ModelAndView("hello");
		}
		 return new ModelAndView("sucess", "user", user);
	 }
	 // 注意@ModelAttribute类似struts2中的模型驱动接口(将请求的表单直接封装成User对象了)
	 @RequestMapping(value="index")
	 public ModelAndView index(@ModelAttribute User user){
		 return new ModelAndView("hello").addObject(user); 
	 }
}


这样虽然可以实现按指定规格校验数据,但是如果我有n个请求需要校验是不是要写n个Validator实现类呢,太麻烦了,求高手指点!

四、拦截器

xml配置

<!-- 拦截器配置 -->
	<mvc:interceptors> 
       <mvc:interceptor> 
           <mvc:mapping path="/**" /> <!-- 拦截所有请求 -->
           <!-- 添加自定义拦截器 -->
           <bean class="com.manage.web.interceptor.SystemInterceptor" /> 
       </mvc:interceptor> 
    </mvc:interceptors>
实现拦截器

package com.manage.web.interceptor;

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

import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.manage.bean.User;
import com.manage.web.utils.Constant;

public class SystemInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		User user = (User) request.getSession().getAttribute(Constant.CURRENT_USER);
		
		PathMatcher matcher = new AntPathMatcher();
		// 获取请求路径
		String requestURL = request.getRequestURL().toString();
		String patternPath="**/login.do";//路径匹配模式
	    boolean result =matcher.match(patternPath, requestURL);
	    
	    if(result){
	    	return true;
	    }
		if (user==null) {
			response.sendRedirect(request.getContextPath()+"/login.jsp");
			return false;
		}
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		
	}
}
以上是简单的总结,不解之处望大牛们指点一二,不胜感激!!!









展开阅读全文
打赏
0
1 收藏
分享
加载中
更多评论
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部