Use ServletContext to implement web page counters and servletcontext

Source: Internet
Author: User

Use ServletContext to implement web page counters and servletcontext

(1) Train of Thought Analysis:

Use ServletContext and notepad to write the login times in the txt file. First, use the Servlet init () when the function is initialized, open the txt counter file and read the file. Then, when the user logs on, the website will not be accessed again and the technology will only count once, until after the cancellation, destroy () and Add 1 to the counter file;

(2) login interface

Package com. tsinghua; import javax. servlet. http. *; import java. io. *; public class Login extends HttpServlet {public void doGet (HttpServletRequest req, HttpServletResponse res) {// business logic try {// Chinese garbled res. setContentType ("text/html; charset = gbk"); PrintWriter pw = res. getWriter (); // return to the logon interface pw. println ("


(2) process login page requests

Package com. tsinghua; import javax. servlet. http. *; import java. io. *; import java. SQL. *; public class LoginCl extends HttpServlet {// rewrite the init function public void init () {try {// will only be called once. // create a FileReaderFileReader f = new FileReader ("f: \ myCounter.txt"); BufferedReader br = new BufferedReader (f ); // read a row of data String numVal = br. readLine (); // be sure to close the file stream br. close (); // put the times value into servletcontextthis. getServletContext (). setAttribute (" VisitTimes ", numVal); System. out. println ("inti called");} catch (Exception ex) {ex. printStackTrace () ;}/// rewrite the destroy function public void destroy () {try {// when writing new times, FileWriter fw = new FileWriter ("f: \ myCounter.txt "); <span style =" white-space: pre "> </span> BufferedWriter bw = new BufferedWriter (fw); <span style =" white-space: pre "> </span> // write data to the file <span style =" white-space: pre "> </span> bw. write (this. getServletContext (). GetAttribute ("visitTimes "). toString (); <span style = "white-space: pre"> </span> // close the file stream <span style = "white-space: pre "> </span> bw. close (); System. out. println ("destroy called");} catch (Exception ex) {ex. printStackTrace () ;}/// process get requests // req: used to obtain information about the client (browser) // res: used to send data to the client (browser) public void doGet (HttpServletRequest req, HttpServletResponse res) {// business logic Connection ct = null; Statement sm = null; ResultSet rs = null; Try {// accept the username and password String u = req. getParameter ("usrename"); String p = req. getParameter ("passwd"); // call UserBeanCl, 1. create an object UserBeanCl ubc = new UserBeanCl (); // 2. use the UserBeanCl method if (ubc. checkUser (u, p) {// valid user String keep = req. getParameter ("keep"); if (keep! = Null) {// Save the user name and password on the client (cookie) // create Cookie name = new Cookie ("myname", u ); cookie pass = new Cookie ("mypasswd", p); // set the time name. setMaxAge (14*24*3600); pass. setMaxAge (14*24*3600); // write back to the client res. addCookie (name); res. addCookie (pass);} // put the user name and password into the session. HttpSession hs = req. getSession (true); hs. setMaxInactiveInterval (30); hs. setAttribute ("uname", u); // set the value of visitTime in serlvetContext to + + String times = this. getServletContext (). GetAttribute ("visitTimes "). toString (); // pair times ++ and then replace servletthis. getServletContext (). setAttribute ("visitTimes", (Integer. parseInt (times) + 1) + ""); // jump to welres. sendRedirect ("Main");} else {// invalid // redirect res. sendRedirect ("login"); // write the servlet url you want} catch (Exception ex) {ex. printStackTrace ();} finally {try {if (rs! = Null) {rs. close () ;}if (sm! = Null) {sm. close () ;}if (ct! = Null) {ct. close () ;}} catch (Exception ex) {ex. printStackTrace () ;}}// process post requests // req: used to obtain client (browser) Information // res: used to send to client (browser) public void doPost (HttpServletRequest req, HttpServletResponse res) {this. doGet (req, res );}}


(3) submit the information to the wel page after successful login

Package com. tsinghua; import javax. servlet. http. *; import java. io. *; import java. SQL. *; import java. util. *; public class Wel extends HttpServlet {// process get requests // req: used to obtain client (browser) Information // res: used to send to client (browser) public void doGet (HttpServletRequest req, HttpServletResponse res) {// business logic Connection ct = null; PreparedStatement ps = null; ResultSet rs = null; // business logic try {// obtain the username HttpSession hs = req from the session. getSession (true); String MyName = (String) hs. getAttribute ("uname"); String name = ""; String passwd = ""; if (myName = null) {// if the session contains no user information, check whether there is any cookie information. // obtain all cookie information from the client. Cookie [] allCookies = req. getCookies (); int I = 0; // If allCookies are not empty... if (allCookies! = Null) {// extract cookiefor (I = 0; I <allCookies. length; I ++) {// retrieve the Cookie temp = allCookies in sequence [I]; if (temp. getName (). equals ("myname") {// obtain the cookie value name = temp. getValue ();} else if (temp. getName (). equals ("mypasswd") {passwd = temp. getValue () ;}} System. out. println ("myname =" + name + "pas =" + passwd); if (! Name. equals ("")&&! Passwd. equals ("") {// go to logincl to verify res. sendRedirect ("loginCl? Usrename = "+ name +" & passwd = "+ passwd); return ;}// return to the logon interface res. sendRedirect (" login? Info = error1 "); return;} // solves Chinese garbled res. setCharacterEncoding ("gbk"); PrintWriter pw = res. getWriter (); pw. println ("<body bgcolor = # CED3FF>"); // adds the pw function for the number of webpage visits. println ("this webpage has been accessed" + this. getServletContext (). getAttribute ("visitTimes "). toString () + "Times <br>"); pw. println ("</body>");} catch (Exception ex) {ex. printStackTrace () ;}} public void doPost (HttpServletRequest req, HttpServletResponse res) {this. doGet (req, res );}}


Here, there is no page to be returned after login is successful. Only website users can count once after login to logout!


Use of the ServletContext class in java

String s = context. getInitParameter ("name ");
This is the initial parameter set in web. xml.

Context. setAttribute ("name", "haha ");
This is for the page

What is the implementation class of javaxservletServletContext?

For myeclipse software

Press Ctrl + T on the class to see
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.