使用一个文件来存储网站的总访问量(在这里时以键值对的形式来存储 比如count=0 然后通过一个properties通过count去获取值也就是访问量),每登陆网站一次就让文件存储的时加一
用setArrtibute 方法给我们需要展示在页面的总访问量赋值
每有一位用户登录,在线人数加一,和上面类似同样使用setAttribute 存储数据 用户退出登录(即注销) 在线人数减一
ServletConfig config = null;
ServletContext sc = null;
private Set<String> names=new HashSet<>();//定义Set来存放name 用于统计在线人数
//数据库连接
static Usermapper mapper;
static SqlSession session;
static {
try {
String resource = "mybatis-config.xml";
InputStream is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
session = sqlSessionFactory.openSession();
mapper = session.getMapper(Usermapper.class);
} catch (IOException e) {
e.printStackTrace();
}
}
mybatis-config.xml
注意如果使用myesplice的web工程 将mybatis-config 和 db.properties 放在直接src中否则会读不到
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="密码"/>
</properties>
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
<typeAliases>
<package name="fir"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="fir.Usermapper"/>
</mappers>
</configuration>
db.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/demo
jdbc.username=root
jdbc.password=密码
public void UpDate(ServletContext sc) {
Properties pro = new Properties();
String n;
String filePath = "/Users/曹智斌/Desktop/count.txt";
//最开始的时候在文件中写 只此一行count=0 也就是访问量为0
InputStream in = null;
try {
in = new FileInputStream(filePath);
pro.load(in);
//将上面字节流所督导的加载进pro 也就是在最开始所创建的properties
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
n = pro.getProperty("count");
//在这里就是通过count来获取访问量 文件写的是count=访问量
//类似于Map中通过 键 来访问 值
//但是要注意的是此处获得的是一个字符并非是一个数字
//所以在下面调用Integer.parseInt方法 该方法是将所传进的字符 通过补全二进制中用于表示整型值的字节数,将字符转化成数字
int a = Integer.parseInt(n) + 1;
sc.setAttribute("totalcount", a);
pro.setProperty("count", a );
try {
OutputStream os = new FileOutputStream(filePath);
pro.store(os, null);
//将通过setProperty 修改过的count 重新通过输出流写进filePath如今所指向的文件中
} catch (IOException e) {
e.printStackTrace();
}
}
在线人数统计
public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
String username=req.getParameter("username");
String password = req.getParameter("password");
User user = mapper.query(username);
if (user != null) {
if (user.getPassword().equals(password)) {
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
out.print("");
out.flush();
out.close();
req.getSession().setAttribute("username", username);
//将用户名保存到set集合中
names.add(username);
//再将names集合保存到application内置对象中
req.getServletContext().setAttribute("users", names);
//集合大小即为人数多少
req.getServletContext().setAttribute("count", names.size());
}else {
PrintWriter out = resp.getWriter();
out.print("");
out.flush();
out.close();
}
}else {
PrintWriter out = resp.getWriter();
out.print("");
out.flush();
out.close();
}
}
//这句话的作用就是在窗口提示是否登陆成功 在index.jsp 上显示 如下图
out.print("");
注销
//实现注销的方法
public void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
//移除当前用户输入的用户名
names.remove(req.getSession().getAttribute("username"));
//销毁当前用户的session内置对象
req.getSession().invalidate();
req.getServletContext().setAttribute("count", names.size());
PrintWriter out = resp.getWriter();
out.print("");
out.flush();
out.close();
}
注册
注册前先根据输入的用户名在数据库查找是否存在,没有则插入信息,否则不会插入
实体类
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + "]";
}
mapper文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="fir.Usermapper">
<select id="query" resultType="fir.User">
select username,password from user where username = #{
username}
</select>
<insert id="Register">
insert into user(username, password) values
(#{
username,jdbcType=VARCHAR},
#{
password,jdbcType=VARCHAR})
</insert>
<cache readOnly="true"></cache>
</mapper>
//查看是否存在
private boolean IsExist(String username, String password) throws SQLException, IOException{
User user = mapper.query(username);
if (user == 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();
}
}
提交
@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("");
out.flush();
out.close();
} else {
PrintWriter out = resp.getWriter();
out.print("");
out.flush();
out.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
if (str3 != null) {
logout(req,resp);
}
}
web.xml
<servlet>
<servlet-name>LOGIN</servlet-name>
<servlet-class>fir.LOGIN</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LOGIN</servlet-name>
<url-pattern>/LOGIN.do</url-pattern>
</servlet-mapping>
index.xml
<%@ 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>
<html>
<head>
<base href="/logn/">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</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>
在运行的时候,如果出现找不到相应的例如 着了的 Main.do
一般两个根本原因
1.web.xml 和 index.jsp 中的url路径不匹配
那么匹配就好了
2.找不到编译的.class 文件
url 匹配 那么就是.class 文件
(1)Project 查看是否 勾选 Build Automically自动编译
(2)不行的话 那么 Project --> clean-->clean project selected below
(3) 还是不行的话 window --> show views --> other --> general --> Navigator
应该就可以了