我正在尝试在我的项目中使用Spring Security,但我找不到错误的根源。我得到了与洞时间相同的例外:
并未设置所有命名参数:[login] [SELECT DISTINCT u FROM User u LEFT JOIN FETCH u.roles WHERE u.login =:login]
为什么我不能将所有参数发送到服务器?我使用Spring Boot,Hibernate和MySQL。 我的项目: login.jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<jsp:include page="headTag.jsp"/>
<body>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li>
<form:form class="navbar-form" role="form" action="login"
method="post">
<div class="form-group">
<label for="login"> Login: </label>
<div class="col-sm-3">
<input type="text" placeholder="Login" class="form-control" name='login' id="login">
</div>
</div>
<div class="form-group">
<label for="password"> Password: </label>
<div class="col-sm-3">
<input type="password" placeholder="Password" class="form-control" name='password' id="password">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-sm btn-block btn-primary">Sign in</button>
</div>
</form:form>
<br/>
<form class="navbar-form" action="{/register}">
<button class="btn btn-sm btn-block btn-primary">Register</button>
</form>
</li>
</ul>
</div>
</div>
</div>
<div class="jumbotron">
<div class="container">
<c:if test="${error}">
<div class="error">
${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
</div>
</c:if>
<c:if test="${not empty message}">
<div class="message">
<spring:message code="${message}"/>
</div>
</c:if>
<p>
<br/><br/><br/><br/>
<p>User login: <b> Bill </b></p>
<p>User password: <b> 112233 </b></p>
<p>Стек технологий: <a href="http://projects.spring.io/spring-security/">Spring Security</a>,
<a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html">Spring MVC</a>,
<a href="http://projects.spring.io/spring-data-jpa/">Spring Data JPA</a>,
<a href="http://spring.io/blog/2014/05/07/preview-spring-security-test-method-security">Spring Security
Test</a>,
<a href="http://hibernate.org/orm/">Hibernate ORM</a>,
<a href="http://hibernate.org/validator/">Hibernate Validator</a>,
<a href="http://www.slf4j.org/">SLF4J</a>,
<a href="https://github.com/FasterXML/jackson">Json Jackson</a>,
<a href="http://ru.wikipedia.org/wiki/JSP">JSP</a>,
<a href="http://en.wikipedia.org/wiki/JavaServer_Pages_Standard_Tag_Library">JSTL</a>,
<a href="http://tomcat.apache.org/">Apache Tomcat</a>,
<a href="http://www.webjars.org/">WebJars</a>,
<a href="http://datatables.net/">DataTables plugin</a>,
<a href="http://ehcache.org">Ehcache</a>,
<a href="http://www.postgresql.org/">PostgreSQL</a>,
<a href="http://junit.org/">JUnit</a>,
<a href="http://hamcrest.org/JavaHamcrest/">Hamcrest</a>,
<a href="http://jquery.com/">jQuery</a>,
<a href="http://ned.im/noty/">jQuery notification</a>,
<a href="http://getbootstrap.com/">Bootstrap</a>.</p>
</div>
</div>
<jsp:include page="footer.jsp"/>
</body>
</html>
用户类:
@NamedEntityGraphs({
@NamedEntityGraph(name = User.GRAPH_WITH_ROLES, attributeNodes = @NamedAttributeNode("roles")),
@NamedEntityGraph(name = User.GRAPH_WITH_ROLES_AND_CONTACTS, attributeNodes =
{
@NamedAttributeNode("roles"),
@NamedAttributeNode("contacts")
})
})
@NamedQueries({
@NamedQuery(name = User.DELETE, query = "DELETE FROM User u WHERE u.id=:id"),
@NamedQuery(name = User.BY_LOGIN, query = "SELECT DISTINCT u FROM User u LEFT JOIN FETCH u.roles WHERE u.login=:login"),
@NamedQuery(name = User.ALL_SORTED, query = "SELECT DISTINCT u FROM User u LEFT JOIN FETCH u.roles ORDER BY u.login"),
})
@Entity
@Table(name = "users", uniqueConstraints = {@UniqueConstraint(columnNames = "login", name = "users_unique_login_idx")})
public class User extends NamedEntity{
public static final String GRAPH_WITH_ROLES = "User.WithRoles";
public static final String GRAPH_WITH_ROLES_AND_CONTACTS = "User.WithRolesAndContacts";
public static final String DELETE = "User.DELETE";
public static final String BY_LOGIN = "User.BY_LOGIN";
public static final String ALL_SORTED = "User.All_SORTED";
@Column(name = "password", nullable = false)
@Length(min = 5, max = 100, message = "your password should have 5 or more symbols")
@JsonView(View.REST.class)
@NotEmpty
private String password;
@Column(name = "full_name", nullable = false)
@Length(min = 5, max = 100, message = "your fullName should have 5 or more symbols")
private String fullName;
@Enumerated(EnumType.STRING)
@CollectionTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"))
@Column(name = "role")
@ElementCollection(fetch = FetchType.LAZY)
protected Set<Role> roles;
@OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY, mappedBy = "user")
@OrderBy("firstName DESC")
protected List<Contact> contacts;
public User() {
}
public User(User u) {
this(u.getId(), u.getLogin(), u.getPassword(), u. getFullName(), u.getRoles());
}
public User(Integer id, String login, String password, String fullName, Role role, Role... roles) {
this(id, login, password, fullName, EnumSet.of(role, roles));
}
public User(Integer id, String login, String password, String fullName, Set<Role> roles) {
super(id, login);
this.password = password;
this.fullName = fullName;
setRoles(roles);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = CollectionUtils.isEmpty(roles) ? Collections.emptySet() : EnumSet.copyOf(roles);
}
public List<Contact> getContacts() {
return contacts;
}
@Override
public String toString() {
return "User{" +
"password='" + password + '\'' +
", fullName='" + fullName + '\'' +
", roles=" + roles +
'}';
}
}
联系班级:
@NamedQueries({
@NamedQuery(name = Contact.GET, query = "SELECT cont FROM Contact cont WHERE cont.id=:id AND cont.user.id=:userId"),
@NamedQuery(name = Contact.ALL_SORTED, query = "SELECT cont FROM Contact cont WHERE cont.user.id=:userId ORDER BY cont.firstName DESC"),
@NamedQuery(name = Contact.DELETE, query = "DELETE FROM Contact cont WHERE cont.id=:id AND cont.user.id=:userId"),
@NamedQuery(name = Contact.GET_FILTERED, query = "SELECT cont FROM Contact cont WHERE cont.user.id=:userId " +
"AND cont.firstName LIKE :firstName AND cont.lastName LIKE :lastName " +
"AND cont.mobilePhone LIKE :mobilePhone ORDER BY cont.firstName DESC"),
})
@Entity
@Table(name = "contacts")
public class Contact extends BaseEntity{
public static final String GET = "Contact.GET";
public static final String ALL_SORTED = "Contact.ALL_SORTED";
public static final String DELETE = "Contact.DELETE";
public static final String GET_FILTERED = "Contact.GET_FILTERED";
@Column(name = "first_name", nullable = false)
@NotEmpty
@Length(min = 4)
private String firstName;
@Column(name = "last_name", nullable = false)
@NotEmpty
@Length(min = 4)
private String lastName;
@Column(name = "patronymic", nullable = false)
@NotEmpty
@Length(min = 4)
private String patronymic;
@Column(name = "mobile_phone_number", nullable = false)
@NotEmpty
@Pattern(regexp = "\\+380\\([1-9]{2}\\)[0-9]{7}", message = "format should be like +380(66)1234567" +
"")
private String mobilePhone;
@Column(name = "home_phone_number")
private String homePhone;
@Column(name = "address")
private String address;
@Email
@Column(name = "email", nullable = false)
private String email;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
public Contact() {
}
public Contact(String firstName, String lastName, String patronymic, String mobilePhone, String homePhone, String address, String email ) {
this(null,firstName,lastName,patronymic,mobilePhone,homePhone,address,email);
}
public Contact( Integer id, String firstName, String lastName, String patronymic, String mobilePhone, String homePhone, String address, String email ) {
super(id);
this.firstName = firstName;
this.lastName = lastName;
this.patronymic = patronymic;
this.mobilePhone = mobilePhone;
this.homePhone = homePhone;
this.address = address;
this.email = email;
}
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 getPatronymic() {
return patronymic;
}
public void setPatronymic(String patronymic) {
this.patronymic = patronymic;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getHomePhone() {
return homePhone;
}
public void setHomePhone(String homePhone) {
this.homePhone = homePhone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Contact{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", patronymic='" + patronymic + '\'' +
", mobilePhone='" + mobilePhone + '\'' +
", homePhone='" + homePhone + '\'' +
", address='" + address + '\'' +
", email='" + email + '\'' +
'}';
}
}
RootController
@Controller
public class RootController extends AbstractContactController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String root() {
return "redirect:/login";
}
@RequestMapping(value = "/contacts", method = RequestMethod.GET)
public String contactList() {
return "contacts";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(ModelMap model,
@RequestParam(value = "error", required = false) boolean error,
@RequestParam(value = "message", required = false) String message) {
model.put("error", error);
model.put("message", message);
return "login";
}
}
WebSecurityConfiguration文件:
@Configuration
@EnableWebMvc
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers(HttpMethod.GET, "/**").permitAll()
.antMatchers(HttpMethod.POST, "/**").permitAll()
.antMatchers(HttpMethod.PUT, "/**").permitAll()
.antMatchers(HttpMethod.DELETE, "/**").permitAll()
.antMatchers("/js/**", "/css/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login")
.permitAll()
.and()
.logout()
.permitAll()
.logoutUrl("/logout")
.logoutSuccessUrl("/login");;
}
}
我的DTO授权用户:
public class AuthorizedUser extends org.springframework.security.core.userdetails.User{
private static final long serialVersionUID = 1L;
private UserDTO userDTO;
public AuthorizedUser(User user) {
super(user.getLogin(), user.getPassword(), true, true, true, true, user.getRoles());
this.userDTO = UserUtil.userAsDTO(user);
}
public static AuthorizedUser safeGet() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null) {
return null;
}
Object principal = auth.getPrincipal();
return (principal instanceof AuthorizedUser) ? (AuthorizedUser) principal : null;
}
public static AuthorizedUser get() {
AuthorizedUser user = safeGet();
requireNonNull(user, "No authorized user found");
return user;
}
public static int id() {
return get().userDTO.getId();
}
public void update(UserDTO newDTO) {
userDTO = newDTO;
}
public UserDTO getUserDTO() {
return userDTO;
}
@Override
public String toString() {
return userDTO.toString();
}
}
为什么我会遇到此异常? 谢谢人们?