Ajax异步交互,判断用户名是否被占用

jsp页面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>




Insert title here


	
用户名:
密码:

bean

package com.huida.bean;

public class User {
	private int id;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	private String username;
	private String password;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

servlet

package com.huida.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.huida.bean.User;
import com.huida.service.UserService;


public class CheckUserNameServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置编码
		//接收用户
		String username=request.getParameter("username");
		username=new String(username.getBytes("iso-8859-1"),"utf-8");
		User user=new UserService().checkUserName(username);
		if(user==null){
			response.getWriter().println("1");
		}else{
			response.getWriter().print("0");
		}
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

service

package com.huida.service;

import com.huida.bean.User;
import com.huida.dao.UserDao;

public class UserService {

	public User checkUserName(String username) {
		// TODO Auto-generated method stub
		return new UserDao().getUserByName(username);
	}

}

dao

package com.huida.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.huida.bean.User;
import com.huida.utils.DataSourceUtils;

public class UserDao {

	public User getUserByName(String username) {
		QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select * from user where username=?limit 1";
		
		try {
			return qr.query(sql, new BeanHandler<>(User.class),username);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}

你可能感兴趣的:(JavaEE)