Java Web Log

Java Web Log

In Java Web Servlet project is equivalent to the controller, JSP equivalent view. Login divided into two parts, the author, judge. JSP first entered user ID and password to the Servlet, and then judge in a Servlet.

JSP form submission:
<body>
	<form action="pageContext.request.contextPath/servlet/UserServlet" method="post">
		用户名<input id="username" name="username">
		密码<input id="password" name="password">
		<button type="submit">登录</button>
	</form>
</body>
Servlet login method:
public void login (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//先获取JSP输入的用户名和密码
	String username=request.getParameter("username");
	String password=request.getParameter("password");

//声明对象
	User user=null;
	try {

//连接mysql数据库
        	Class.forName("com.mysql.jdbc.Driver");
        	Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", "root");

//发送sql语句
        	PreparedStatement ps=con.prepareStatement("select * from user where username=? and password=?");

//给PreparedStatement对象的占位符赋值
        	ps.setString(1, username);
        	ps.setString(2, password);

//执行语句
        	ResultSet rs=ps.executeQuery();

//通过while循环给对象参数赋值
        	while (rs.next()) {
            		user=new User();
            		user.setUserid(rs.getInt("userid"));
            		user.setUsername(rs.getString("username"));
            		user.setPassword(rs.getString("password"));
        	}
	} catch (Exception e) {
		// TODO Auto-generated catch block	
		e.printStackTrace();
	}

//判断对象是否有值
	if(user!=null){	
		System.out.println("登录成功");
	}else{
		System.out.println("用户名或密码错误");
	}
}

Guess you like

Origin blog.csdn.net/weixin_44547599/article/details/90286075