我在spring mvc中为用户创建了一个模型,并使用ModelAttribute将数据保存到数据库...数据保存成功,我想在保存到数据库后更新一些字段...我使用ModelAttribute更新一些数据字段...当我单击更新按钮时,方面字段成功更新,其他字段更改为空...如何将其他字段存储在存储的值中...我想仅更新密码,移动和电子邮件.. < / p>
这是我的jsp。
<%--
Created by IntelliJ IDEA.
User: ignotus
Date: 2/6/2017
Time: 3:58 PM
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>User ${user.nic} </title>
<jsp:include page="template/styles.jsp"/>
</head>
<body>
<div id="bootstrapCssTest" class="hidden"></div>
<div class="container">
<div class="row headerRow1">
<div class="col-md-12">
<jsp:include page="template/banner.jsp"/>
</div>
</div>
<div class="row">
<div class="authheader">
<%@include file="template/message.jsp" %>
</div>
</div>
<div class="row ">
<div class="col-xs-12 col-sm-4 col-md-3 col-lg-3">
<jsp:include page="template/header.jsp"/>
</div>
<div class="col-xs-11 col-sm-7 col-md-7 col-lg-8">
<div class="row">
<div class="col-lg-12">
<div class="well lead">Account Details</div>
</div>
</div>
<div class="row" >
<div class="panel panel-default">
<div class="panel-body">
<div class="row">
<div class="form-group col-md-12">
<p>Name - ${user.firstName} ${user.lastName}</p>
<p>Agency - ${user.agency}</p>
<p>NIC/Emp No - ${user.nic}</p>
<p>VAT No - ${user.impoVat}</p>
</div>
</div>
<form:form method="POST" modelAttribute="user" commandName="user" class="form-horizontal" action="resetDetails">
<form:input type="hidden" path="id" id="id"/>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-3 control-lable" for="password">Password</label>
<div class="col-md-7">
<form:input type="password" path="password" id="password" class="form-control input-sm" maxlength="15"/>
<div class="has-error">
<form:errors path="password" class="help-inline"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-3 control-lable" for="mobile">Mobile Phone No.</label>
<div class="col-md-7">
<form:input type="number" path="mobile" id="mobile" class="form-control input-sm" maxlength="10"/>
<div class="has-error">
<form:errors path="mobile" class="help-inline"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-3 control-lable" for="email">Email</label>
<div class="col-md-7">
<form:input type="text" path="email" id="email" class="form-control input-sm"/>
<div class="has-error">
<form:errors path="email" class="help-inline"/>
</div>
</div>
</div>
</div>
<div class="form group row">
<div class="col-lg-12">
<div class="form-actions floatRight pull-right">
<input type="submit" value="Update" class="btn btn-success"/> or <a
href="<c:url value='./' />">Cancel</a>
</div>
</div>
</div>
</form:form>
</div>
</div>
</div>
</div>
</div>
<jsp:include page="template/footer.jsp"/>
</div>
<jsp:include page="template/stylesLoadHigh.jsp"/>
</body>
<script>
$(document).ready(function () {
$("#emp").hide();
$("#slsi").click(function () {
$("#agency").val("SLSI");
$("#emp").show();
$("#nic").hide();
$("#h1").hide();
$("#agency").attr("readonly", "readonly");
});
$("#other").click(function () {
$("#emp").hide();
$("#nic").show();
$("#h1").show();
$("#agency").val("");
$("#agency").removeAttr("readonly");
});
var dataString = $("#agency").val();
if (dataString == 'SLSI') {
$("#emp").show();
$("#nic").hide();
} else {
$("#nic").show();
$("#emp").hide();
}
});
</script>
<script>
$(document).ready(function () {
var agN = $("#agency").val();
if (agN == 'SLSI') {
$("#agency").attr("readonly", "readonly");
$("#h1").hide();
}
});
</script>
<script>
function lettersOnly(input) {
var regex = /[^a-zA-Z0-9-]/gi;
input.value = input.value.replace(regex, "");
}
</script>
<script>
function lettersOnly(input) {
var regex = /[^a-zA-Z0-9-]/gi;
input.value = input.value.replace(regex, "");
}
</script>
</html>
这是我的JSP retreive控制器
@RequestMapping(path = "/MyAccount", method = RequestMethod.POST)
public String updateUser(Model model) {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
long userId = 0;
String agency = "";
String units = "";
List<String> roles;
if (principal != null && principal instanceof AuthenticatedUser) {
AuthenticatedUser auth = (AuthenticatedUser) principal;
userId = auth.getUserId();
agency = auth.getAgency();
roles = auth.getUserRoles();
model.addAttribute("user", userServices.getUserFromUserId(userId));
model.addAttribute("roles", userServices.getAllRoles());
model.addAttribute("units", userServices.getAllUnits());
model.addAttribute("edit", true);
return "passwordChange";
} else {
return "redirect:/login";
}
}
这是我的更新控制器...
@RequestMapping(path = "/resetDetails", method = RequestMethod.POST)
public String reupdateUserDetails(@ModelAttribute("user") @Valid User user,
BindingResult result,
HttpSession session) {
if (result.hasErrors()) {
return "redirect:/somethingWentWorng/dataValidationError";
}
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
long userId = 0;
String agency = "";
String units = "";
List<String> roles;
if (principal != null && principal instanceof AuthenticatedUser) {
AuthenticatedUser auth = (AuthenticatedUser) principal;
userId = auth.getUserId();
agency = auth.getAgency();
roles = auth.getUserRoles();
User newUser=userServices.getUserFromUserId(userId);
newUser.setId(newUser.getId());
newUser.setUserUnits(newUser.getUserUnits());
newUser.setUserRoles(newUser.getUserRoles());
newUser.setAgency(newUser.getAgency());
newUser.setFirstName(newUser.getFirstName());
newUser.setLastName(newUser.getLastName());
newUser.setImpoVat(newUser.getImpoVat());
newUser.setUserName(newUser.getUserName());
newUser.setNic(newUser.getNic());
slsiLogger.info("Executing user update with user : [{}]", user);
if (userServices.updateUserDetails(user)) {
session.setAttribute(MESSAGE_KEY, "user update successful!");
} else {
session.setAttribute(MESSAGE_KEY, "user update was not successful");
}
}
return USAER_MANAGE_REDIRECT;
}
这是我的模特
package lk.slsi.domain;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import javax.persistence.*;
import java.util.Collections;
import java.util.Set;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private long id;
@Column(unique = true)
private String nic;
private String firstName;
private String lastName;
private String mobile;
private String email;
private String status;
private String agency;
@Column(unique = true)
private String userName;
private String password;
private String impoVat;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "user_roles",
joinColumns = {
@JoinColumn(name = "id")},
inverseJoinColumns = {
@JoinColumn(name = "roleId")})
private Set<Role> userRoles;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "user_units",
joinColumns = {
@JoinColumn(name = "id")},
inverseJoinColumns = {
@JoinColumn(name = "unitId")})
private Set<Unit> userUnits;
public Set<Unit> getUserUnits() {
return userUnits;
}
public void setUserUnits(Set<Unit> userUnits) {
this.userUnits = userUnits;
}
@PreRemove
private void removeRolesFromUser() {
this.setUserRoles(Collections.emptySet());
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
// public String getSsoId() {
// return ssoId;
// }
//
// public void setSsoId(String ssoId) {
// this.ssoId = ssoId;
// }
public String getNic() {
return nic;
}
public void setNic(String nic) {
this.nic = nic;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getImpoVat() {
return impoVat;
}
public void setImpoVat(String impoVat) {
this.impoVat = impoVat;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getAgency() {
return agency;
}
public void setAgency(String agency) {
this.agency = agency;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
ShaPasswordEncoder encoder = new ShaPasswordEncoder(224);
this.password = encoder.encodePassword(password, null);
}
public Set<Role> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<Role> roles) {
this.userRoles = roles;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("User{");
sb.append("id=").append(id);
//sb.append(", ssoId='").append(ssoId).append('\'');
sb.append(", nic='").append(nic).append('\'');
sb.append(", firstName='").append(firstName).append('\'');
sb.append(", lastName='").append(lastName).append('\'');
sb.append(", mobile='").append(mobile).append('\'');
sb.append(", email='").append(email).append('\'');
sb.append(", status='").append(status).append('\'');
sb.append(", agency='").append(agency).append('\'');
sb.append(", userName='").append(userName).append('\'');
sb.append(", userUnits='").append(userUnits).append('\'');
sb.append(", userRoles=").append(userRoles);
sb.append('}');
return sb.toString();
}
}
我想将以前的值存储在 nic,firstName,lastName,userUnits,userRoles 字段中,并且仅替换密码,移动设备和电子邮件。 如何从控制器执行此操作.... 我不想将数据传递给jsp并因为安全原因而返回到modelAttribute。我想从控制器执行此操作。