模型对象不会传递给Spring MVC中的jsps - InternalResourceView - renderMergedOutputModel

时间:2013-05-30 11:49:37

标签: java jsp spring-mvc tiles

我在我的项目中使用JstlView Spring Tiles。

当我尝试将表单:错误从验证程序发送到jsp到控制器时,错误不会在jsp中发送

当我调试时,

1)在从验证器类返回modelandview之前,在控制器类中打印错误。

2)然后在控制器类的JstlView类中也会打印错误。

所以我认为,jstlview类中的requestDispatcher.forward(request,response)不会将模型数据返回给jsp。

因为当我尝试使用HttpServletRequest或HttpServletResponse对象来检索jsp中的错误时,在jsp中显示了值。

可以帮助我使用这个。

如何将模型数据发送到jsp renderMergedOutputModel- RequestDispatcher,重定向方法。

我的代码如下,

JstlView类:

public class JstlView extends InternalResourceView {

 @Override
 protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

 // Determine the path for the request dispatcher.
 String dispatcherPath = prepareForRendering(request, response);

 // set original view being asked for as a request parameter
 request.setAttribute("partial", dispatcherPath.substring(dispatcherPath.lastIndexOf("/") + 1));

// force everything to be template.jsp
 RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/template.jsp");
 requestDispatcher.forward(request, response);

 System.out.println("**********************"+model.get("userName"));
 }

}

servlet.xml中

<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">

    <property name="viewClass" value="com.tms.web.view.JstlView" />

    <property name="prefix" value="/WEB-INF/jsp/" />

    <property name="suffix" value=".jsp" />
</bean>

控制器:

 private LoginValidator loginValidator;
     @Autowired
     public void setUserValidator(LoginValidator loginValidator) {
         this.loginValidator = loginValidator;
     }

       final RequestHandler  requestHandler = new RequestHandler();
       @RequestMapping(value = "/login", method = RequestMethod.GET)
       public ModelAndView login() {
          return new ModelAndView("login", "users", new users());
       }

   @RequestMapping(value = "/logins",method = RequestMethod.POST)
   public ModelAndView validateUser(@Valid users user, BindingResult result,@ModelAttribute("users")users users,ModelMap model,RedirectAttributes redirectAttributes,HttpServletRequest req) 
   {
       this.loginValidator.validate(user, result);
            if (result.hasErrors()) 
            {
                  model.putAll(result.getModel());//values not retuned to jsp
                  req.setAttribute("userName", result.getFieldError().getDefaultMessage().toString());  //working fine values retuned to jsp
                  return new ModelAndView("/login", model);
            }
           else
           {
                    //succes related code
                    return new ModelAndView(redirect, model);
           }    
      }   

验证

@Component
public class LoginValidator implements Validator {

  @Override
  public boolean supports(Class<?> clazz) {

    return clazz.isAssignableFrom(users.class);
  }
  @Override
  public void validate(Object obj, Errors errors) {
    users user = (users) obj;
    String userName = user.getUserName();
    String password = user.getPassword();
    validateuserName(userName,password, errors);
  }

  private void validateuserName(String userName, String password,Errors errors) {
    if (!(isValidString(userName))) {
       errors.rejectValue("userName", "userName.required","Username should not be blank");
    }
    else if(!(isValidString(password)))
    {
        errors.rejectValue("password", "password.required","Password should not be blank");
    }
  }

  private boolean isValidString(String str) {
    return isNotNull(str) && (str.length() > 0 ) && !(str.isEmpty());
  }

  private boolean isNotNull(String str) {
    return str != null;
  }
}

JSP

<%@ page language="java" contentType="text/html;charset=UTF-8; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" %>
<%@ page isScriptingEnabled="true" isELIgnored="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>



    <form:form method="POST" action="/TMSWeb/logins"  commandName="users" modelAttribute="users">                                          
                                <input name="password" type="password" align="center"/> 
                                <form:errors path="password" cssClass="error" element="div" /> 
                                <input type="submit" class="buttonorange"  value="Login"/>
            </form:form>

在Spring MVC中,当我可以在没有JstlView的JSP中访问我的bean时,那么,在我的JSP中我可以编写($ {errors)。但是,当相同的JSP是切片视图的一部分时,无法访问这些属性。

有人可以在这个问题上帮助我吗?

1 个答案:

答案 0 :(得分:2)

您正在 JstlView 类中扩展类 org.springframework.web.servlet.view.InternalResourceView 并覆盖 renderMergedOutputModel 方法,其中你缺少暴露模型对象。从override方法调用此方法 exposeModelAsRequestAttributes(model,requestToExpose); ,如下所示。尝试下面的代码,这对我有用。

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest    request, HttpServletResponse response) throws Exception {

// Expose the model object as request attributes.
     exposeModelAsRequestAttributes(model,request);

// Determine the path for the request dispatcher.
String dispatcherPath = prepareForRendering(request, response);

// set original view being asked for as a request parameter
request.setAttribute("partial", dispatcherPath.substring(dispatcherPath.lastIndexOf("/") + 1));

// force everything to be template.jsp
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/template.jsp");
requestDispatcher.forward(request, response);

System.out.println("**********************"+model.get("userName"));
}

}