gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:13:51 26 4
gpt4 key购买 nike

//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);
}
}
//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>

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

最佳答案

您可以使用 Spring Validator 接口(interface)构建自己的自定义 validator 并使用 Spring 表单标签。

       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/

关于java - 如何在 spring mvc 中的服务器端验证上显示错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33073646/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com