【Servlet实现登录表单示例】在这里, 我们将创建一个简单的示例, 以使用servlet创建登录表单。我们已经使用oracle10g作为数据库。该应用程序需要5个文件。
- index.html
- FirstServlet.java
- LoginDao.java
- SecondServlet.java
- web.xml
create table userreg(name varchar2(40), pass varchar2(40));
index.html
<
form action="servlet1" method="post">
Name:<
input type="text" name="username"/>
<
br/>
<
br/>
Password:<
input type="password" name="userpass"/>
<
br/>
<
br/>
<
input type="submit" value="http://www.srcmini.com/login"/>
<
/form>
FirstServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
String p=request.getParameter("userpass");
if(LoginDao.validate(n, p)){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
out.print("Sorry username or password error");
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.include(request, response);
} out.close();
}
}
LoginDao.java
import java.sql.*;
public class LoginDao {
public static boolean validate(String name, String pass){
boolean status=false;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");
PreparedStatement ps=con.prepareStatement(
"select * from userreg where name=? and pass=?");
ps.setString(1, name);
ps.setString(2, pass);
ResultSet rs=ps.executeQuery();
status=rs.next();
}catch(Exception e){System.out.println(e);
}
return status;
}
}
WelcomeServlet.java
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 WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
out.print("Welcome "+n);
out.close();
}}
下载此示例
推荐阅读
- 在Eclipse中创建Servlet示例详细图解
- Servlet获取给定rollno结果的示例
- 在NetBeans IDE中创建servlet示例图解
- Servlet从服务器下载文件的示例
- Servlet中的事件和监听器
- Servlet中的CRUD操作示例图解
- 在myeclipse IDE中创建Servlet实例图解
- 创建servlet示例的详细步骤图解
- Servlet中的Cookie用法详解