jsp,servlet中的登录表单出错?

时间:2016-01-07 09:30:33

标签: java jsp servlets

我在下面写了一些文件:  -loginServlet.java:简单地转发到loginview.jsp   - loginView.jsp:获取用户名和密码 -doLoginServlet.java:在数据库中查找用户

@WebServlet("/doLogin")
public class DoLoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


/**
 * @see HttpServlet#HttpServlet()
 */
public DoLoginServlet() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String userName = request.getParameter("userName");
    String password = request.getParameter("passWord");
    String rememberMeStr = request.getParameter("rememberMe");
    boolean remember = "Y".equals(rememberMeStr);
    UserAccount user = null;
    boolean hasError = false;
    String errorString = null;
    if(userName == null||password == null||userName.length() == 0||password.length() == 0){
        hasError = true;
        errorString = "Require username and password!";

    }else{
        Connection conn = MyUtils.getStoreConnection(request);
        try {
            user = DBUtils.findUser(conn, userName,password);
            if(user == null){
                hasError = true;
                errorString = "User Name or password invalid";
            }
        } catch (SQLException e) {
            // TODO: handle exception
            e.printStackTrace();
            hasError = true;
            errorString = e.getMessage();
        }
    }
    if(hasError){
        user = new UserAccount();
        user.setUserName(userName);
        user.setPassword(password);
        request.setAttribute("errorString", errorString);
        request.setAttribute("user", user);
        request.getRequestDispatcher("/WEB-INF/views/loginView.jsp").forward(request, response);
    }
    else{
        HttpSession session = request.getSession();
        MyUtils.storeLoginedUser(session, user);
        if(remember){
            MyUtils.storeUserCookie(response, user);

        }
        else{
            MyUtils.deleteUserCookie(response);
        }
        response.sendRedirect(request.getContextPath() + "/userInfo");

    }

    }

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

} 我的DBUtils.java包含finduser函数,

package nguyenhuyhoan.com.simplewebapp.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import nguyenhuyhoan.com.simplewebapp.beans.Product;
import nguyenhuyhoan.com.simplewebapp.beans.UserAccount;

public class DBUtils {
    public static UserAccount findUser(Connection conn, String userName, String passWord) throws SQLException {
        String sql = "Select a.User_Name, a.Password, a.Gender from User_Account a "
                   + " where a.User_Name = ? and a.password= ?";

    PreparedStatement pstm = conn.prepareStatement(sql);
    pstm.setString(1, userName);
    pstm.setString(2, passWord);
    ResultSet rs = pstm.executeQuery();
    if (rs.next()) {
        String gender = rs.getString("Gender");
        UserAccount user = new UserAccount();
        user.setUserName(userName);
        user.setPassword(passWord);
        user.setGender(gender);
        return user;
    }
    return null;

}

public static UserAccount findUser(Connection conn, String userName) throws SQLException {
    String sql = "Select a.User_Name,a.PassWord,a.Gender from User_Account a" + "where a.User_Name = ?";
    PreparedStatement pstm = conn.prepareStatement(sql);
    pstm.setString(1, userName);
    ResultSet rs = pstm.executeQuery();
    if (rs.next()) {
        String passWord = rs.getString("Password");
        String gender = rs.getString("Gender");
        UserAccount user = new UserAccount();
        user.setUserName(userName);
        user.setPassword(passWord);
        user.setGender(gender);
        return user;

    }
    return null;

}

public static List<Product> queryProduct(Connection conn) throws SQLException {
    String sql = "Select a.Code,a.Name,a.Price from Product a";
    PreparedStatement pstm = conn.prepareStatement(sql);
    ResultSet rs = pstm.executeQuery();
    List<Product> list = new ArrayList<Product>();
    while (rs.next()) {
        String code = rs.getString("Code");
        String name = rs.getString("Name");
        float price = rs.getFloat("Price");
        Product product = new Product();
        product.setCode(code);
        product.setName(name);
        product.setPrice(price);
        list.add(product);
    }
    return list;

}

public static Product findProduct(Connection conn, String code) throws SQLException {
    String sql = "Select a.Code,a.Name,a.Price from Product a where a.Code = ?";
    PreparedStatement pstm = conn.prepareStatement(sql);
    pstm.setString(1, code);
    ResultSet rs = pstm.executeQuery();
    while (rs.next()) {
        String name = rs.getString("Name");
        float price = rs.getFloat("Price");
        Product product = new Product(code, name, price);
        return product;

    }
    return null;
}

public static void updateProduct(Connection conn, Product product) throws SQLException {
    String sql = "Update Product set Name = ?,Price=? where Code = ?";
    PreparedStatement pstm = conn.prepareStatement(sql);
    pstm.setString(1, product.getName());
    pstm.setFloat(2, product.getPrice());
    pstm.setString(3, product.getCode());
    pstm.executeUpdate();
}

public static void insertProduct(Connection conn, Product product) throws SQLException {
    String sql = "Insert INTO Product(Code,Name,Price) value(?,?,?)";
    PreparedStatement pstm = conn.prepareStatement(sql);
    pstm.setString(1, product.getCode());
    pstm.setString(2, product.getName());
    pstm.setFloat(3, product.getPrice());
    pstm.executeUpdate();
}

public static void deleteProduct(Connection conn, String code) throws SQLException {
    String sql = "Delete Product where code = ?";
    PreparedStatement pstm = conn.prepareStatement(sql);
    pstm.setString(1, code);
    pstm.executeUpdate();
}

}

但它在DBUtils.java中的FindUser函数中出现错误,但我不明白为什么? 服务器遇到内部错误,导致无法完成此请求。 显示java.lang.NullPointerException     nguyenhuyhoan.com.simplewebapp.utils.DBUtils.findUser(DBUtils.java:18) 任何身体帮助我,谢谢! 和myUtils.java

import java.sql.Connection;

import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import nguyenhuyhoan.com.simplewebapp.beans.UserAccount;

public class MyUtils {
    public static final String ATT_NAME_CONECTION = "ATTRIBUTE_FOR_CONNECTION";
    private static final String ATT_NAME_USER_NAME = "ATTRIBUTE_FOR_STORE_USER_NAME_IN_COOKIE";

    public static void storeConnection(ServletRequest request,Connection conn){
        request.setAttribute(ATT_NAME_CONECTION, conn);
    }

    public static Connection getStoreConnection(ServletRequest request){
        Connection conn = (Connection) request.getAttribute(ATT_NAME_CONECTION);
        return conn;
    }

    public static void storeLoginedUser(HttpSession session,UserAccount loginedUser){
        //tren JSP co the truy cap ${loginedUser}
        session.setAttribute("loginedUser", loginedUser);
    }

    public static UserAccount getLoginedUser(HttpSession session){
        UserAccount loginedUser = (UserAccount) session.getAttribute("loginedUser");
        return loginedUser;
    }

    public static void storeUserCookie(HttpServletResponse response,UserAccount user){
        System.out.println("store user cookie");
        Cookie cookieUserName = new Cookie(ATT_NAME_USER_NAME, user.getUserName());
        cookieUserName.setMaxAge(24*60*60);
        response.addCookie(cookieUserName);
    }
    public static String getUserNameInCookie(HttpServletRequest request){
        Cookie cookies[] = request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if(ATT_NAME_USER_NAME.equals(cookie.getName())){
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public static void deleteUserCookie(HttpServletResponse response){
        Cookie cookieUserName = new Cookie(ATT_NAME_USER_NAME, null);

        cookieUserName.setMaxAge(0);
        response.addCookie(cookieUserName);
    }
}

1 个答案:

答案 0 :(得分:1)

除了NPE之外。 第二个findUser方法中的语句永远不能成功执行:

String sql = "Select a.User_Name,a.PassWord,a.Gender from User_Account a" + "where a.User_Name = ?"

你在这里忘了一个空格:

from User_Account a "

或此处+ " where

相关问题