个性化阅读
专注于IT技术分析

Servlet实现登录表单示例

在这里, 我们将创建一个简单的示例, 以使用servlet创建登录表单。我们已经使用oracle10g作为数据库。该应用程序需要5个文件。

  • index.html
  • FirstServlet.java
  • LoginDao.java
  • SecondServlet.java
  • web.xml

你必须创建带有名称和传递字段的表userreg。而且, 它必须包含一些数据。该表应为:

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="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();
	}

}

下载此示例

赞(0) 打赏
未经允许不得转载:srcmini » Servlet实现登录表单示例
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

觉得文章有用就打赏一下文章作者

微信扫一扫打赏