我正在使用session和PasswordCodec utils开发登录/注册页面。当我注册新用户时,它会生成以下错误...
Cannot invoke method getBytes() on null object. Stacktrace follows:
Message: Cannot invoke method getBytes() on null object
Line | Method
->> 15 | doCall in PasswordCodec$__clinit__closure1
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 10 | doCall in samplelogin.UserController$_closure1
| 195 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter
| 63 | doFilter in grails.plugin.cache.web.filter.AbstractFilter
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . in java.lang.Thread
下面是我的UserController代码......
package samplelogin
import javax.servlet.http.HttpSession
class UserController {
def registration = {
// new user posts his registration details
if (request.method == 'POST') {
// create domain object and assign parameters using data binding
def u = new User(params)
u.passwordHashed = u.password.encodeAsPassword()
if (! u.save()) {
// validation failed, render registration page again
return [user:u]
} else {
// validate/save ok, store user in session, redirect to homepage
session.user = u
redirect(controller:'main')
}
} else if (session.user) {
// don't allow registration while user is logged in
redirect(controller:'main')
}
}
def login = {
if (request.method == 'POST') {
def passwordHashed = params.password.encodeAsPassword()
def u = User.findByUsernameAndPasswordHashed(params.username, passwordHashed)
if (u) {
// username and password match -> log in
session.user = u
redirect(controller:'main')
} else {
flash.message = "User not found"
redirect(controller:'main')
}
} else if (session.user) {
// don't allow login while user is logged in
redirect(controller:'main')
}
}
def logout = {
session.invalidate()
redirect(controller:'main')
}
}
以下是我的PasswordCodec.groovy工具代码......
import java.security.MessageDigest
import sun.misc.BASE64Encoder
import sun.misc.CharacterEncoder
class PasswordCodec {
static encode = { str ->
MessageDigest md = MessageDigest.getInstance('SHA')
md.update(str.getBytes('UTF-8'))
return (new BASE64Encoder()).encode(md.digest())
}
}
我还在bootstrap.groovy init方法中创建了一个虚拟用户,但是当我尝试登录时,通过查看flash消息收到“user not find”。 任何帮助都是有益的。