Javaweb0802作业

这篇博客介绍了如何使用JavaWeb模拟在线人数统计和网站访问量的实现,包括利用本地文件记录访问次数,通过setAttribute方法更新页面显示。同时,讲解了如何运用MyBatis连接数据库进行用户注册功能,注册时检查用户名是否存在,以及项目的其他组成部分如web.xml配置和网页设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Javaweb0802作业:

1.模拟在线人数统计和网站的访问量

2.模拟注册和登陆的功能的实现。(注册,相当于往表中插入数据;登陆,相当于要查询数据和前端页面的数据进行匹配)


1.模拟在线人数统计和网站的访问量

我们可以利用本地文件存储网站的访问量,就是网站每登陆一次,文件储存的数值加一;然后用setAttribute()方法给页面的总访问量命名和赋值。

(1)更新数据

public void UpDate(ServletContext sc) {
	Properties pro = new Properties(); 
	String n;
	String filePath = "/Users/ruirui/Desktop/count.txt";
	InputStream in = null;
	try {
		in = new  FileInputStream(filePath);
		pro.load(in);
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}	
	n = pro.getProperty("count");
	int a = Integer.parseInt(n) + 1;
	sc.setAttribute("totalcount", a);
	pro.setProperty("count", a + "");
	try {
		OutputStream os = new FileOutputStream(filePath);
		pro.store(os, null);
	} catch (IOException e) {
		e.printStackTrace();
	}
}

 (2)统计在线人数

每登录一个人,在线人数+1,注销时,在线人数-1。用setAttribute存储数据

public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
	String username=req.getParameter("username");
	String password = req.getParameter("password");
	TB7 tb7 = mapper.query(username);
	if (tb7 != null) {
		if (tb7.getPassword().equals(password)) {
			resp.setCharacterEncoding("utf-8");
			PrintWriter out = resp.getWriter();
			out.print("<script>alert('login Successs'); window.location='index.jsp' </script>");
			out.flush();
			out.close();								        
	        req.getSession().setAttribute("username", username);
	        names.add(username);//将用户名保存到set集合中
	        req.getServletContext().setAttribute("users", names);//再将names集合保存到application内置对象中              
	        req.getServletContext().setAttribute("count", names.size());//集合大小即为人数多少 
		}else {
			PrintWriter out = resp.getWriter();
			out.print("<script>alert('password Failed');window.location='index.jsp' </script>");
			out.flush();
			out.close();
	    }
	}else {
	    PrintWriter out = resp.getWriter();
		out.print("<script>alert('not exist'); window.location='index.jsp' </script>");
		out.flush();
		out.close();								
	} 
}

(3) mybatis--------用来连接数据库,对数据库进行操作:

static {
    try {
        String resource = "mybatis-config.xml";		
        InputStream is = Resources.getResourceAsStream(resource);		
	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);				
	SqlSession session = sqlSessionFactory.openSession();
	mapper = session.getMapper(TB7mapper.class);
    } catch (IOException e) {
	e.printStackTrace();
    }
}

2.注册方法

首先查找我们要输入的用户名,存在就不用再插入数据,不存在则插入数据。

private boolean Isexist(String username, String password) throws SQLException, IOException{
    TB7 tb7 = mapper.query(username);
    if (tb7 == null) {
        return false;
    }else {
        return true;
    }
}
private void register(String username, String password) throws SQLException {		
    try {
        mapper.Register(username, password);		
    }catch (Exception e) {
	e.printStackTrace();
    }
}

3.判断按钮

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
    req.setCharacterEncoding("utf-8");
    this.UpDate(sc);
    String str1 = req.getParameter("login");
    String str2 = req.getParameter("register");
    String str3 = req.getParameter("logout");
    if (str1 != null) {
        try {
            login(req,resp);
	} catch (ServletException | IOException | SQLException e) {
	    e.printStackTrace();
	}
    }
    if (str2 != null) {
        String username = req.getParameter("username");
    	String password = req.getParameter("password");
    	System.out.println(username+password);
    	try {
            if (!Isexist(username, password)) {
	        this.register(username, password);
	        PrintWriter out = resp.getWriter();
                out.print("<script>alert('success');window.location='index.jsp' </script>");
	        out.flush();
	        out.close();				
	    } else {
		PrintWriter out = resp.getWriter();
	        out.print("<script>alert('failed');window.location='index.jsp' </script>");
	        out.flush();   
                out.close();				
	    }
	} catch (SQLException e) {
	    e.printStackTrace();
	}
    }
    if (str3 != null) {
        logout(req,resp);
    }	            
}

 4.web.xml

<servlet>
    <servlet-name>Main</servlet-name>
    <servlet-class>fir.Main</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Main</servlet-name>
    <url-pattern>/Main.do</url-pattern>
  </servlet-mapping>

5.网页

<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.sql.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"+request.getServerName() + ":"
 + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<head>
    <base href="/logn/">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>在线人数统计</title>
</head>
<body>
<h1>在线人数:${count==null? 0:count}</h1>
<h1>总访问量:${totalcount}</h1>
${users}
<form action="Main.do" method="get">
    用户名:<input  type="text" name="username">
    密 码: <input  type="password" name="password">
    <input type="submit" value="登陆" name="login">
    <input type="submit" value="注册" name="register">
    <input type="submit" value="注销" name="logout">
</form>
</body>
</html>

6.结果展示:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值