3

我不久前进入了Spring Web MVC 框架,因此我是一个完整的初学者。现在我正在为我的第一个Web 应用程序实现一个基本表单

同时我想说的是,我整天都在为我的问题寻找解决方案。如果类似问题的解决方案已经发布,我会提前道歉。

源代码:

spring-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: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/context
                            http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="si.src.controllers" />
    <context:component-scan base-package="si.src.validators" />

    <bean id="viewResolver" 
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass">
            <value>org.springframework.web.servlet.view.JstlView</value>
        </property>
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>            
</beans>

索引.jsp

<!-- language: lang-jsp -->
<html>
<head>
    <title>Spring 3.0 MVC Series - Index</title>
</head>
<body>
    <br>
    <div align='center'>
        <p>
        <h1>Example - Spring Application</h1>
        The "index.jsp" is the entry point for our application.
        This is my first test. Work!            
        <p>
        <a href="login.html">Welcome! Click Here to Login</a>           
    </div>      
</body>
</html>

登录.jsp

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

<html>
<head>
    <title>Spring Sample - Login Page</title>
</head>
<body>
    <h3>Login Page</h3><br>
    <form:form id="form" method="post" commandName="loginForm">
        <form:errors path="*" cssClass="errorblock" element="div" />
        <table>
            <tr>
                <td><form:label path="username">Username</form:label></td>
                <td><form:input path="username" /></td>
                <td><form:errors path="username" cssClass="error"/></td>
            </tr>
            <tr>
                <td><form:label path="username">Password</form:label></td>
                <td><form:input path="password" /></td>
                <td><form:errors path="password" cssClass="error"/></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Sign in" /></td>
            </tr>
        </table>
    </form:form>
</body>
</html>

登录表单控制器.java

package si.src.controllers;

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

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;

import si.src.logic.Login;
import si.src.validators.LoginValidator;

@Controller
@RequestMapping(value="/login")
public class LoginFormController extends SimpleFormController{

    public LoginFormController(){
        setCommandClass(Login.class);   //Form's values will store into the Login object    
        setCommandName("loginForm");    //If HTML form action value with named "loginForm" is sumbitted, Spring will forward request to this form controller
    }

    @RequestMapping(method=RequestMethod.POST)
    protected ModelAndView onSubmit(HttpServletRequest request,
        HttpServletResponse response, Object command, BindException errors) throws Exception{

        LoginValidator validator = new LoginValidator();        
        Login userLogin = (Login) command;
        validator.validate(userLogin, errors.getBindingResult());

        if(errors.hasErrors()){
            userLogin.setUsername("");
            userLogin.setPassword("");
            System.out.println("Ne");
            return new ModelAndView("login","loginForm", userLogin);

        }
        else{
            System.out.println(userLogin);
            System.out.println(userLogin.getUsername() + " " + userLogin.getPassword());    
            return new ModelAndView("success","userLogin", userLogin);
        }
    }

    protected Object formBackingObject(HttpServletRequest request) throws Exception {   
        //Initialize the values in the form. Not necessary
        Login userLogin = new Login();
        userLogin.setUsername("Admin");
        return userLogin;
    }

}

登录验证器.java

package si.src.validators;

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

import si.src.logic.Login;

public class LoginValidator implements Validator{

    public boolean supports(Class aClass) {
        //just validate the Login instances
        return Login.class.isAssignableFrom(aClass);
    }

    public void validate(Object obj, Errors errors) {
        Login login = (Login) obj;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username","required-username", "Enter username");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password","required-password", "Enter password");    
    }   
}

登录.java

package si.src.logic;

public class Login {

    private String username;
    private String password;

    public Login(){}

    public void setUsername(String username){
        this.username=username;
    }

    public String getUsername(){
        return username;
    }

    public void setPassword(String password){
        this.password=password;
    }

    public String getPassword(){
        return password;
    }   
}

我想由LoginValidator对象获得的错误消息没有正确地“绑定”到我的login.jsp文件中。我想这就是为什么当我的表单填写不完整时错误消息(即“输入用户名”“输入密码”)不显示的原因。

我的问题是:为什么错误消息没有出现在 login.jsp 中?

4

2 回答 2

3

我有类似的问题。我也改变了返回的类型,但我需要将日期从控制器转移到 JSP。我使用对象模型,但对象模型和视图的结果相同。

如何在不丢失表单显示的情况下传输数据:错误?

@RequestMapping(value="/addCaregiver", method= RequestMethod.POST)
public String addCaregiver(@ModelAttribute("caregiver") @Valid  
Caregivers caregiver, BindingResult result,Principal principal, Model model){


caregiverValidator.validate(caregiver, result);
if(result.hasErrors()){

model.addAttribute("caregivers",pp.getCaregiverses(principal.getName()));
model.addAttribute("error", "true");
model.addAttribute("caregiver", new Caregivers());
return "caregiver";
        }
return "intro";
}

我解决了,不要创建一个新的istance,我删除了这一行:

model.addAttribute("caregiver", new Caregivers());
于 2014-02-17T15:57:20.700 回答
2
return new ModelAndView("login","loginForm", userLogin);

您正在自己破坏模型。您正在ModelAndView使用新模型构建自己,忽略/放弃当前模型。因此,这也会破坏绑定错误。

此外,您的代码是错误的,您正在扩展 a SimpleFormControllerwhich is aController并用@Controller. 这是等待发生的麻烦,请删除extends SimpleFormController已弃用的内容。

把你的控制器改成这样

@Controller
@RequestMapping(value="/login")
public class LoginFormController {

    @ModelAttribute("loginForm")
    public Login loginForm() {
        return new Login();
        userLogin.setUsername("Admin");
        return userLogin;
    }

    @RequestMapping(method=RequestMethod.POST)
    public String submit(@ModelAttribute Login loginForm, BindingResult model) {

        LoginValidator validator = new LoginValidator();        
        validator.validate(loginForm, model);

        if(errors.hasErrors()){
            loginForm.setUsername("");
            loginForm.setPassword("");
            System.out.println("Ne");
            return "login";
        } else{
            System.out.println(loginForm);
            System.out.println(loginForm.getUsername() + " " + loginForm.getPassword());    
            return "success";
        }
    }
}
于 2013-11-05T15:15:10.127 回答