刚学Java,听朋友说有的公司有这样一个面试题,为了提高自己的能力,结合http://www.xin126.cn/show.asp?id=2504上的例子,开始动手写出一个较为完整的登陆,并会列出基本相关问题和解决办法
做出这个小例子后,将尝试继续深入,做出一个类似当当网的网上购书系统
第一步、新建login.html,代码如下:
<form method="post" action="login.do">
用户名:
<input type="text" name="usuer">
密 码:
<input type="password" name="password">
<input type="submit" value="提交">
</form>
第二步、新建了一个成功页面,代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" import="java.sql.*"%>
<html>
<head>
<title>成功跳转</title>
</head>
<body>
<%
String message=new String ( request.getParameter("message").getBytes("ISO8859-1"),"GBK" ); %>
<%=message %>
</body>
</html>
第三步、新建一个myServlet包,并建立LoginValidate.java是一个Servlet,所以必须继承HttpServlet:,代码如下:
package myServlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginValidate extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name=request.getParameter("username");
String password=request.getParameter("password");
LoginDBO loginDBO=new LoginDBO();
String message =loginDBO.login(name, password);
String url="returnMessage.jsp?message="+message;
url=new String(url.getBytes("GBK"),"ISO8859_1");
response.sendRedirect(url);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
第四步、在myServlet包中新建一个LoginDBO.java。用来进行对数据库的操作.代码如下:
package myServlet;
import java.sql.*;
public class LoginDBO {
Connection conn;
Statement stmt;
public LoginDBO(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mvc_user","root","123");
stmt=conn.createStatement();
}catch(Exception e)
{
e.printStackTrace();
}
}
public String login(String name, String password){
String message="123";
try{
String sql1="select count(0) from user_info where user_name='"+name+"'";
ResultSet rs1=stmt.executeQuery(sql1);
if(rs1.next()){
int userCount=rs1.getInt(1);
if(0==userCount){
message="不存在该用户";
return message;
}
String sql2="select count(0) from user_info where user_name='"+name+"'and password='"+password+"'";
ResultSet rs2=stmt.executeQuery(sql2);
if(rs2.next()){
int trueUserCount=rs2.getInt(1);
if(0==trueUserCount){
message="密码错误";
return message;
}
message="成功!";
}
}
}catch(Exception e)
{
e.printStackTrace();
}
return message;
}
}