Servlet login function implementation
(1) create a dynamic Login page
// Log on to the package com. lc; import javax. servlet. http. *; import java. io. *; public class Login extends HttpServlet {public void doGet (HttpServletRequest req, HttpServletResponse res) {// business logic try {// solves Chinese garbled res. setContentType ("text/html; charset = gbk"); PrintWriter pw = res. getWriter (); // return to the logon interface pw. println (""); Pw. println (""); Pw. println (" User Logon "); pw. println (" "); pw. println (""); Pw. println ("");} Catch (Exception ex) {ex. printStackTrace () ;}} public void doPost (HttpServletRequest req, HttpServletResponse res) {this. doGet (req, res );}}
(2) create a servlet that accepts Login
// Log on to the package com. lc; import javax. servlet. http. *; import java. io. *; public class Logincl extends HttpServlet {public void doGet (HttpServletRequest req, HttpServletResponse res) {// business logic try {// solve Chinese garbled characters // accept username and password String u = req. getParameter ("username"); String p = req. getParameter ("passwd"); // verify if (u. equals ("lc") & p. equals ("123") {// jump to Welcomeres. sendRedirect ("welcome"); // The servlet url is redirected here} else {// illegal // redirect res. sendRedirect ("login"); // jump to the servlet url} catch (Exception ex) {ex. printStackTrace () ;}} public void doPost (HttpServletRequest req, HttpServletResponse res) {this. doGet (req, res );}}
(3) successful login to the welcome page to jump
// Log on to the package com. tsinghua; import javax. servlet. http. *; import java. io. *; public class Welcome extends HttpServlet {public void doGet (HttpServletRequest req, HttpServletResponse res) {// business logic try {// solves Chinese garbled res. setContentType ("text/html; charset = gbk"); PrintWriter pw = res. getWriter (); pw. println ("hello welcome! ");} Catch (Exception ex) {ex. printStackTrace () ;}} public void doPost (HttpServletRequest req, HttpServletResponse res) {this. doGet (req, res );}}
(4) Compiling the configuration file web. xml
Welcome to Tomcat
Welcome to Tomcat
Login
com.lc.Login
Login
/login
Logincl
com.lc.Logincl
Logincl
/logincl
Welcome
com.lc.Welcome
Welcome
/welcome
(5) running result: