java中servlet实现登录验证的方法
本文导语: login.java: 代码如下:package com.ncu;import java.io.PrintWriter; import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class login extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletRespon...
login.java:
package com.ncu;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class login extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res){
try{
//res.setCharacterEncoding("utf-8");
res.setContentType("text/html;charset=gbk");
PrintWriter pw=res.getWriter();
//返回登录界面
pw.print("");
pw.print("");
pw.print("登录界面");
pw.print("");
pw.print("用户登录界面");
pw.print("");
pw.print("用户名:
");
pw.print("密码:
");
pw.print("");
pw.print("");
}catch(Exception e)
{
e.printStackTrace();
}
}
}
LoginPro.java:
package com.ncu;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginPro extends HttpServlet{
public void doPost(HttpServletRequest req,HttpServletResponse res){
try{
String user=req.getParameter("userName");
String pwd=req.getParameter("Pwd");
if(user==null){
user="";
}
if(pwd==null)
{
pwd="";
}
if(user.equals("nicolas")&&pwd.equals("nicolas")){
//用户和密码合法
//res.sendRedirect("wel");
// res.setCharacterEncoding("gbk");
// PrintWriter pw=res.getWriter();
// pw.print("恭喜你,登录成功!!");
res.sendRedirect("welcome");
}
else{
//不合法进行跳转
res.sendRedirect("login");//跳转到登录界面
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
Welcome.java:
package com.ncu;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Welcome extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res){
try{
res.setCharacterEncoding("gbk");
PrintWriter pw=res.getWriter();
pw.print("welcome,您好");
}catch(Exception e)
{
e.printStackTrace();
}
}
}
web.xml
index.jsp
hello
com.ncu.Hello
hello
/nicolas
helloservlet
com.ncu.HelloServlet
helloservlet
/helloservlet
helloHttpServlet
com.ncu.helloHttpServlet
helloHttpServlet
/helloHttpServlet
login
com.ncu.login
login
/login
loginpro
com.ncu.LoginPro
loginpro
/loginpro
welcome
com.ncu.Welcome
welcome
/welcome