❶ 求大神寫一下jsp的簡單的注冊界面代碼。
1.需要一個jsp頁面:
//login.jsp核心代碼:
<form action="${pageContext.request.contextPath}/servlet/UserServlet" method="post">
<input type="text" name="loginname" /><input type="password" name="password"/>
<input type="submit" value="登錄"/>
</form>
2.需要一個servlet來驗證登錄信息
//UserServlet 核心代碼
class UserServlet extends HttpServlet{
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
process(request, response);
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
process(request, response);
}
private void process(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
PrintWriter pw = response.getWriter();
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
String loginname = request.getParameter("loginname");
String password = request.getParameter("password");
//創建一個service來處理業務邏輯(包括查詢資料庫操作)
UserService service = new UserService();
boolean bool = service.validateUser(loginname,password);
if(!bool){
pw.println("用戶名或密碼錯誤");
}else{
pw.println("登錄成功");
}
}
3.需要一個service處理業務邏輯(包括查詢資料庫操作)
//UserService 核心代碼
public class UserService{
/**
*查詢資料庫驗證用戶是否存在,返回boolean
*/
public boolean validateUser(String loginname,String password){
boolean bool = false;
Connection conn = null;
PreparedStatement ps = null;
//這里以mysql為例
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
String sql = "select login_name,pass_word from t_user where login_name=? and pass_word=?";
ps = conn.prepareStatement(sql);
ps.setString(0, loginname);
ps.setString(1, password);
ResultSet rs = ps.executeQuery();
if(rs.next()){
bool = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(conn != null){
conn.close();
conn = null;
}
if(ps != null){
ps.close();
ps = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return bool;
}
}