Servlet课程0425(四) Servlet实现简单用户登录验证
Login.java
//登录界面 package com.tsinghua; import javax.servlet.http.*; import java.io.*; public class Login extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res) { //业务逻辑 try{ //中文乱码 //浏览器默认ISO-8859 res.setContentType("text/html;charset=gbk"); PrintWriter pw = res.getWriter(); //返回登录界面 pw.println("<html>"); pw.println("<body>"); pw.println("<h1>登录界面</h1>"); pw.println("<form action='loginCl' method=post>"); pw.println("用户名<input type='text' name='username'/><br/>"); pw.println("密码<input type='password' name='userpwd'/><br/>"); pw.println("<input type='submit' value='loing' /><br/>"); pw.println("</form>"); pw.println("</body>"); pw.println("</html>"); } catch(Exception ex) { ex.printStackTrace(); } } //处理get请求 //req用于获得客户端(浏览器)的信息 //res用于向 客户端(浏览器)返回信息 public void doPost(HttpServletRequest req, HttpServletResponse res) { this.doGet(req,res); } }
LoginCl.java
//登录界面 package com.tsinghua; import javax.servlet.http.*; import java.io.*; public class LoginCl extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res) { //业务逻辑 try{ //接收用户名和密码 String u = req.getParameter("username"); String p = req.getParameter("userpwd"); //验证 if(u.equals("litao") && p.equals("litao")){ //合法 //跳转到welcome res.sendRedirect("wel"); } else{ //不合法 //写你要到的Servlet的那个URL res.sendRedirect("login"); } } catch(Exception ex) { ex.printStackTrace(); } } //处理get请求 //req用于获得客户端(浏览器)的信息 //res用于向 客户端(浏览器)返回信息 public void doPost(HttpServletRequest req, HttpServletResponse res) { this.doGet(req,res); } }
Welcome.java
//登录界面 package com.tsinghua; import javax.servlet.http.*; import java.io.*; public class Welcome extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res) { //业务逻辑 try{ PrintWriter pw = res.getWriter(); //返回登录界面 pw.println("Welcome,hello"); } catch(Exception ex) { ex.printStackTrace(); } } //处理get请求 //req用于获得客户端(浏览器)的信息 //res用于向 客户端(浏览器)返回信息 public void doPost(HttpServletRequest req, HttpServletResponse res) { this.doGet(req,res); } }