登录代码
package dmeo;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.User;
@WebServlet("/login.do")//login.do索引
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
private boolean isOK(String s) { //布尔型变量
boolean result = true;//声明一个结果变量为true
for(int i=0;i<s.length();i++) { //for循环
char c = s.charAt(i);//
if(Character.isLetterOrDigit(c))
continue;
else {
result =false;
break;
}
}
return result;
}
private User find(Map userinfo, String username, String password) {
User user = new User();//实例化User类
Iterator<Entry<String,String>>itor = userinfo.entrySet().iterator();
while(itor.hasNext()) { //while循环
Map.Entry<String, String> entry = (Entry<String,String>) itor.next();
String userStr = entry.getKey().toString();
String pwdStr = entry.getValue().toString();
System.out.println("用户名:"+userStr+"\t--------密码:"+pwdStr);
if(username.equals(userStr) && password.equals(pwdStr)) {//如果用户名等于用户字符与密码等于密码字符,则
user.setUsername(userStr);//设置用户名
user.setPassword(pwdStr);//设置密码
break;//中止
}
}
return user;//返回
}
//发送
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username= request.getParameter("username");
String password = request.getParameter("password");
System.out.println(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/");
// String path = "C:/上传图片/保存的数据.txt";
String classpath = this.getClass().getResource("/").getPath();
String path =classpath+"保存的数据.txt";
System.out.println("密码文件路径"+path);
TextFileUtil tfu = new TextFileUtil(path);
Map<String,String> userinfo = new HashMap<>();
List<String> list = tfu.read();
for(String s : list) { //for循环,将list中的值赋值给s
if(isOK(s)) { //如果
String[] arrayStr=s.split("ok");//以ok将用户名和密码划分,再赋值给arrayStr数组
userinfo.put(arrayStr[0], arrayStr[1]);//将用户名和密码放在arrayStr数组中的0~1坐标
}
}
User user = find(userinfo,username,password); //查找用户信息,用户名和密码,再赋值给user变量
System.out.println("用户名"+user.getUsername()+"\t密码"+user.getPassword()); //输出用户名和密码
if(user.getUsername() == null || user.getPassword() == null) {//如果用户名为空或者用户密码为空
response.sendRedirect("fail.jsp");
}else if (user.getUsername() != null || user.getPassword() != null) { //否则如果用户名不为空或者用户密码不为空
request.getRequestDispatcher("logined.jsp").forward(request, response); //则跳转到登录成功页面,并交给request,response
}else { //否则
response.sendRedirect("fail.jsp");//调用发送重定向(sendRedirect)到登录失败页面
}
}
class User{ //声明一个用户类
private String username;
private String password;
public void setUsername(String username) {
this.username=username;
}
public void setPassword(String password) {
this.password=password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
}
package dmeo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginFormServlet
*/
@WebServlet("/index.jsp")
public class LoginFormServlet extends HttpServlet { //登录表单
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginFormServlet() {
super();
// TODO Auto-generated constructor stub
}
//获取
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");//setContentType设置文本文件为html,进行解析
PrintWriter out = response.getWriter();//输出
out.println("<html>");
out.println("<head>");
out.println("<title>登录表单</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>用户登录</h1>");
out.println("<form action='login.do' method='post'> ");
out.println("用户名:<input name='username' type='text'> <br>");
out.println("密码:<input name='password' type='password' > <br> ");
out.println("自动登录:<input name='login' type='checkbox'> <br> ");
out.println("<button type=\"submit\">登录</button>");
out.println("<a href=\"register.jsp\">注册</a>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
package dmeo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/logined.jsp") ///logined.jsp索引
public class LoginedServlet extends HttpServlet { //登录成功
private static final long serialVersionUID = 1L;
public LoginedServlet() {
super();
}
//service中可以写方法,如doget,dopost........
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>登录成功</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>登录成功</h1>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
package dmeo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginFailServlet
*/
@WebServlet("/fail.jsp")
public class LoginFailServlet extends HttpServlet { //登录失败页面
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginFailServlet() {
super();
// TODO Auto-generated constructor stub
}
//service方法中可以写doget,dopost....方法的代码
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>登录失败</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1> 登录失败</h1>");
out.println("<a href=\"index.jsp\">登录页面</a>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
package dmeo;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RegisterHand
*/
@WebServlet("/register.do")
public class RegisterHand extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RegisterHand() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String password2 = request.getParameter("password2");
if(password.equals(password2)) {//如果密码1等于密码2,则
// 执行注册逻辑 WEB-INF\classes
String classpath = this.getClass().getResource("/").getPath();
String path =classpath+"保存的数据.txt";
System.out.println("密码文件路径 "+path);
TextFileUtil tfu = new TextFileUtil(path);
String str = username+"ok"+password;
tfu.writeLine(str);
System.out.println("注册成功");
request.setAttribute("message", "注册成功"); //设置(setAttribute)属性("属性名","属性值")
request.getRequestDispatcher("msg.jsp").forward(request, response);//转跳到注册页面.并交给request,response
}else { //否则
//转跳(getRequestDispatcher)到注册页面.并交给request,response
request.setAttribute("message", "用户两次密码不一致"); //设置属性("属性名","属性值")
request.getRequestDispatcher("msg.jsp").forward(request, response);
System.out.println(username +"\t"+password+"\t"+password2);
}
}
package dmeo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RegisterServlet
*/
@WebServlet("/register.jsp")
public class RegisterServlet extends HttpServlet { //注册页面
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RegisterServlet() {
super();
// TODO Auto-generated constructor stub
}
//获取
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>用户注册</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>用户注册</h1>");
out.println("<form action=\"register.do\" method=\"post\"> ");
out.println("用户名:<input name=\"username\" type=\"text\"> <br>");
out.println("密码:<input name=\"password\" type=\"password\"> <br> ");
out.println("确认密码:<input name=\"password2\" type=\"password\"> <br> ");
out.println("<button type=\"submit\">注册</button>");
out.println("<a href=\"index.jsp\">首页</a>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
package dmeo;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
public class TextFileUtil { //声明一个文本文件
private String path;//路径
private BufferedWriter out;//缓冲区输出 的out变量
private String getlineBreak() {//断线
String osName = System.getProperty("os.name");//调用得到的值
String lineBreak = null;
if(osName.startsWith("Mac OS")) {
lineBreak = "\n";
}else if (osName.startsWith("Windows")) {
lineBreak="\r\n";
}else {
lineBreak ="\r";
}
return lineBreak;
}
public TextFileUtil(String path) {
this.path=path;
try {
File writename = new File(this.path);
this.out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(writename,true)));
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//追加写入,不分行
public void write(String str) {
try {
this.out.write(str);
this.out.flush();//把缓存区内容压入文件
}catch(Exception e) {
e.printStackTrace();
}
}
//按行写入
public void writeLine(String line) {
try {
this.out.write(line+getlineBreak());
this.out.flush();//把缓存区内容压入文件
}catch (Exception e) {
e.printStackTrace();
}
}
public List<String> read() {
List<String> list = new ArrayList<>();
BufferedReader br = null;
try {
br=new BufferedReader(new InputStreamReader(new FileInputStream(this.path),"GBK"));
String line;
while((line=br.readLine())!=null) {
list.add(line);
}
}catch (IOException e) {
e.printStackTrace();
}
return list;
}
protected void finalize() throws Throwable{
super.finalize();
this.out.close();
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path=path;
}
public BufferedWriter getOut() {
return out;
}
public void setOut(BufferedWriter out) {
this.out=out;
}
}
package dmeo;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class IndexServlet
*/
@WebServlet("/index.jsp")
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public IndexServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies();//取得Cookie
if(cookies!=null) {
for(Cookie c : cookies) {
String name = c.getName();
String value= c.getValue();
if((name==null )||(value==null)) {
response.sendRedirect("login.jsp");
}else {
if("user".equals(name) && "autologin".equals(value)) { //如果这个cookie名称与数值,表示允许自动登录
request.getRequestDispatcher("logined.jsp").forward(request, response);
}else {
response.sendRedirect("login.jsp");
}
}
}
}else {
response.sendRedirect("login.jsp");//如果没有相对应的cookie名称与数值,表示尚未允许自动登录,重定向到登录窗体
}
}
}
最后在文件夹里建一个.txt文档