简体   繁体   中英

how to display error message on server side validation in spring mvc

 //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])(?=.*[az])(?=.*[AZ])(?=.*[@#$%^&+=])(?=\\\\S+$).{5,15}$") && confirmpassword.matches("^(?=.*[0-9])(?=.*[az])(?=.*[AZ])(?=.*[@#$%^&+=])(?=\\\\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); } } 
 //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> 

I have added here 2 files. first one is loginController.java and other one is login.jsp i have done client side validation in jquery. now i want to display error message on server side validation in loginController.java file which has code for server side validation. and also i want it to be check once whether loginController.java is written correct or not.

You can use Spring Validator interface to build your own custom validator and use spring form tags.

       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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM