第一个登录界面web应用
程序员文章站
2022-07-15 11:57:24
...
1.最基本的web登陆界面应用框架
在此案列中运用的是sendRedirect方法传递信息
2.对应每个流程写相应类
a.登陆界面编写
package com.myfirstwebLogin;
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.setContentType("text/html;charset=utf-8");
PrintWriter pw=res.getWriter();
//返回登录页面
pw.println("<html>");
pw.println("<body>");
pw.println("<h1>登录界面</h1>");
//action后面接跳转的url
pw.println("<form action=logincheck method=post>");
pw.println("用户名:<input type=text name=username><br>");
pw.println("密 码:<input type=password name=password><br>");
pw.println("<input type=submit value=login><br>");
pw.println("</form>");
pw.println("</body>");
pw.println("</html>");
}
catch(Exception ex){
ex.printStackTrace();
}
}
public void doPost(HttpServletRequest req,HttpServletResponse res){
this.doGet(req, res);
}
}
b.用户信息核对
package com.myfirstwebLogin;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginCheck extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res){
try{
//接收用户名和密码
String username=req.getParameter("username");
String password=req.getParameter("password");
if(username.equals("tpx")&&password.equals("123456")){
//传递给welcome页面username
res.sendRedirect("welcome?username="+username);
}
else{
//跳转的url
res.sendRedirect("login");
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
public void doPost(HttpServletRequest req,HttpServletResponse res){
this.doGet(req, res);
}
}
c.登陆成功页面
package com.myfirstwebLogin;
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{
//接收LoginCheck中的username
String username=req.getParameter("username");
PrintWriter pw=res.getWriter();
pw.println("Welcome"+" "+username);
}catch(Exception ex){
ex.printStackTrace();
}
}
//处理post请求
public void doPost(HttpServletRequest req,HttpServletResponse res){
this.doGet(req, res);
}
}
3配置到服务器
对应每个类都要配置在web.xml中
详见web环境设置
4效果如下