如何在spring mvc中显示服务器端验证的错误消息

时间:2015-10-12 05:10:59

标签: java jquery spring validation jsp



//This is my loginController.java

import java.io.IOException;
import java.util.Map;

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController
{
	
	@RequestMapping(value="/login.htm", method = RequestMethod.POST)
	public String login(@RequestParam(value="userid", required=true) String userid,
    					@RequestParam(value="password", required=true) String password,
    					@RequestParam(value="confirmpassword", required=true) String confirmpassword,
    					@RequestParam(value="role", required=true) String role,
    					Map<String, Object> model)
	
	{
    		if(userid.matches("^[a-zA-Z0-9]{5,24}$") && password.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{5,15}$")
    		&& confirmpassword.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{6,20}$") 
    		&& (role.equals(new String("OPS(Operational)"))||role.equals(new String("Helpdesk"))))
    		{
	    		model.put("userid", userid);
	    		model.put("password", password);
	    		model.put("confirmpassword", confirmpassword);
	    		model.put("role", role);
	    		
	    		System.out.println("successful!");
	    		return "page2";
    		}
    			else
    			{
    				return "login";
    			}
    	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
	{
		String userid = request.getParameter("userid");
	    String password = request.getParameter("password");
	    String confirmpassword = request.getParameter("confirmpassword");
	    String role = request.getParameter("role");
	    
	    try
	    {
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
	    catch (ServletException e)
	    {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    catch (IOException e)
	    {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	  }
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String userid = request.getParameter("userid");
	    String password = request.getParameter("password");
	    String confirmpassword = request.getParameter("confirmpassword");
	    String role = request.getParameter("role");
		
	    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
	}	
}
&#13;
//This is my login.jsp file

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ include file="include.jsp" %>
<html>
<head>
<meta charset="utf-8">

</head>

<body>

<div align="center" id='formlogin' class="container">

<form method="post" id="loginForm" name="loginForm" action="login.htm">
		<table class="tableprop" border="0" width="90%" cellspacing="5" cellpadding="5">
		
		<h3> Add a new user </h3>
		
			<tr>
				<td align="center">User ID:</td>
				<td><input tabindex="5" size="20" type="text" name="userid" id="userid" value="<%=request.getParameter("userid")!=null?request.getParameter("userid"):""%>"/></td>
			</tr>
			
			<tr>
				<td align="center">Password:</td>
				<td><input tabindex="5" size="20" type="password" name="password" id="password" value="<%=request.getParameter("password")!=null?request.getParameter("password"):""%>"/></td>
			</tr>
			
			<tr>
				<td align="center">Confirm Password:</td>
				<td><input tabindex="5" size="20" type="password" name="confirmpassword" id="confirmpassword" value="<%=request.getParameter("confirmpassword")!=null?request.getParameter("confirmpassword"):""%>"/></td>
			</tr>
			
			<tr>
				<td align="center">Role:</td>
				<td><select name="role" id="role" title="Please select role" tabindex="5" value="<%=request.getParameter("role")!=null?request.getParameter("role"):""%>"/>
					<option value="">Select a specific role</option>
					<option value="OPS(Operational)">OPS(Operational)</option>
					<option value="Helpdesk">Helpdesk</option>
				</select></td>
			</tr>
			
			<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
			
			<tr>
				<td align="center" colspan="4"><input tabindex="7" type="submit" value="Submit" id="submit" class="submit"/></td>					
			</tr>
<!-- 			<div id="dialog" title="Dialog Title">I'm in a dialog</div> -->
			</table>				
		</form>
	</div>

<script>
	// just for the demos, avoids form submit
	jQuery.validator.setDefaults({
	debug: true,
	success: "valid"
	});
</script>

</body>
</html>
&#13;
&#13;
&#13;

我在这里添加了2个文件。 第一个是loginController.java 另一个是login.jsp 我在jquery中完成了客户端验证。 现在我想在loginController.java文件中显示服务器端验证的错误消息,该文件包含服务器端验证的代码。而且我希望能够检查loginController.java是否写得正确。

1 个答案:

答案 0 :(得分:2)

您可以使用Spring Validator接口构建自己的自定义验证器并使用spring form标签。

       User.java
       package com.expertwebindia.beans;
        public class User {
            private String name;
            private String email;
            private String address;
            private String country;
            private String state;
            private String city;
            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            public String getAddress() {
                return address;
            }

            public void setAddress(String address) {
                this.address = address;
            }

            public String getCountry() {
                return country;
            }

            public void setCountry(String country) {
                this.country = country;
            }

            public String getState() {
                return state;
            }

            public void setState(String state) {
                this.state = state;
            }

            public String getCity() {
                return city;
            }

            public void setCity(String city) {
                this.city = city;
            }

            public String getEmail() {
                return email;
            }

            public void setEmail(String email) {
                this.email = email;
            }



        }

                UserValidator.java



package com.expertwebindia.validators;
                import org.springframework.stereotype.Component;
                import org.springframework.validation.Errors;
                import org.springframework.validation.ValidationUtils;
                import org.springframework.validation.Validator;

                import com.expertwebindia.beans.User;
                @Component
                public class UserValidator implements Validator
                {

                    public boolean supports(Class clazz) {
                        return User.class.equals(clazz);
                    }
                    public void validate(java.lang.Object arg0, Errors arg1) {
                          ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "name", "name.required", "Name is required.");
                          ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "email", "Name.required", "Email is required.");
                          ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "address", "name.required", "Address is required.");
                          ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "country", "country.required", "Country is required.");
                          ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "state", "state.required", "State is required.");
                          ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "city", "city.required", "City is required.");
                    }

                }

    In controller you need to the following code to validate your bean.
    @RequestMapping(value = "/login", method = RequestMethod.POST)
        public String doLogin(@ModelAttribute("userForm") User userForm,
                BindingResult result, Map<String, Object> model) {
            validator.validate(userForm, result);
            System.out.println("Email:"+userForm.getEmail());
            if (result.hasErrors()) {
                return "register";
            }else{

                return "success";
            }
        }

    Please find more details about this in link below.
    http://www.expertwebindia.com/spring-3-mvc-custom-validator-example/