开发者

How to avoid saving details in database when a new user tries to create account with existing username?

开发者 https://www.devze.com 2023-04-09 07:28 出处:网络
I have a jsp page in my project where user fills up the details for creating an account. when a user enters username and clicks on the check button, the button looks in the database if the same name

I have a jsp page in my project where user fills up the details for creating an account.

when a user enters username and clicks on the check button, the button looks in the database if the same name exists or not(it is able to check because of the servlet code). If usern开发者_StackOverflow社区ame exists it shows not available. Now the problem is even if username is not available when user clicks on sumbit button with existing username the details get saved. how to correct this? (I'm nt able to post image otherwise it would have been more clear.)


Just add an if-else block to your servlet, something like this:

if (usernameExists) {
    showError();
} else {
    saveUser();
}

Do not do this:

if (usernameExists) {
    showError();
}

saveUser();

I'd also add an UNIQUE constraint on the username column in the DB so that your DAO throws an SQLException or like.

See also:

  • Our Servlets wiki page - contains a basic Hello world example with server-side validation


First, you serlvet accepting the HTTP POST must validate the data sent to it, when the user clicks a button, if the receiver doesn't validate the information then bad data will get into your system regardless of what you do in the JSP.

Some people send raw HTTP POST messages from time to time just for fun (I don't know why :) ) to see if bad data can get into poorly written web applications.

Once the servlet accepting the POST rejects bad data, you can have it redirect back to the offending web page, filled out with the information that was sent in the bad request, perhaps highlighting the offending field or fields.

Later on, if you have the time, you can write up a bunch of javascript to pre-check the fields and deactivate the submit button. This saves the back end servlet the bother of receiving so many bad requests; however, you cannot use such a technique to avoid fixing the back end servlet. There's too many ways your servlet could get the POST message that don't involve your specific javascript code working.

0

精彩评论

暂无评论...
验证码 换一张
取 消