Servlet学习(二) 写一个Javaweb登陆项目&Cookie技术

Servlet学习(二) 写一个Javaweb登陆项目&Cookie技术

源码资料:链接:https://pan.baidu.com/s/1GrLHKQcgd5l1NBwZ41mfWw
提取码:jvjq

总览:

  1. 需要运用mvc思想:模型(Model)+视图(View)+控制器 (Controller)
  2. requst对象的作用域
  3. 请求转发&重定向
  4. 乱码问题解决
  5. Cookie技术

项目结构

Servlet学习(二) 写一个Javaweb登陆项目&Cookie技术_第1张图片

package edu.hue.jk;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.hue.jk.bean.User;
import edu.hue.jk.server.LoginServer;
import edu.hue.jk.server.LoginServerImpl;
/**
 * Cookie信息校验
 * 		判断请求中是否携带正确的Cookie信息
 * 		如果有则校验Cookie信息是否正确
 * 			如果校验正确则直接响应主页面给用户
 * 			如果校验不正确则响应登录页面给用户
 * 		没有则请求转发给登录页面
 * @author 超爱学习的可琛同学
 */
public class LoginCookie extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//设置请求编码格式
		req.setCharacterEncoding("utf-8");
	//设置响应编码格式
		resp.setContentType("text/html;charset=utf-8");
	//获取请求信息
		  //获取request中cookie信息
		Cookie[] cks = req.getCookies();
		if(cks!=null){
			//声明变量
			User u = null;
			String Uid = null;
			LoginServer ls;
			//遍历Cookie信息
			for(Cookie c :cks){
				//校验UID是否存在
				if(c.getName().equals("Uid")){
					Uid = new String(c.getValue()); 
				ls = new LoginServerImpl();
				 u= ls.checkLoginServer(Uid);
				//cookie 生命期内 判断该用户是否还存在
				if(u!=null){
					//重定向
					resp.sendRedirect("main");
					return;
				}
				
				if(Uid.equals(null)){
					//请求转发
					req.getRequestDispatcher("page").forward(req, resp);
					return;
				}
				}
			}
				
			
		}else{
			//请求转发
			req.getRequestDispatcher("page").forward(req, resp);
			return;
		}
		

	}

}

package edu.hue.jk;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginPage extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse reps)
			throws ServletException, IOException {
		//先获取req中“str”属性值:若密码第一次填写肯定为null的
		String str = (String)req.getAttribute("str");
		//设置请求编码格式
		req.setCharacterEncoding("utf-8");
		//设置响应编码格式
		reps.setContentType("text/html;charset=utf-8");
		//输出
		reps.getWriter().write(" 
"); if(str!=null){ //输出错误信息 reps.getWriter().write("" + str+"
"); } reps.getWriter().write("用户名:
"
); reps.getWriter().write(" 密码:
"
); reps.getWriter().write(""); reps.getWriter().write(""
); } }
package edu.hue.jk;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.hue.jk.bean.User;
import edu.hue.jk.server.LoginServer;
import edu.hue.jk.server.LoginServerImpl;

public class LoginServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//设置请求编码格式
		req.setCharacterEncoding("utf-8");
		//设置响应编码格式
		resp.setContentType("text/html;charset=utf-8");
		//将request中uname 和pwd 存储
		 String uname = req.getParameter("uname");
		 String pwd = req.getParameter("pwd");
		 //创建Loginserver对象
		LoginServer ls = new LoginServerImpl();
		//检查用户名和密码是否正确
		User u = ls.checkLoginServer(uname, pwd);
		if(u != null){
			System.out.println("登陆成功");
			Cookie c = new Cookie("Uid", u.getUid()+"");
			System.out.println(req.getParameter("Uid"));
			//设置cookie生命期 3*24*3600秒
			c.setMaxAge(3*24*3600);
			//设置cookie在指定路径下才可用
			c.setPath("lt/ck");
			//添加cookie到浏览器
			resp.addCookie(c);
			//重定向到main
			resp.sendRedirect("main");
		}else{
			resp.getWriter().write("登陆失败");
			System.out.println("登陆失败");
			//在req设置属性str 和 其值:用户名或密码错误
			req.setAttribute("str", "用户名或密码错误");
			//请求转发
			req.getRequestDispatcher("page").forward(req, resp);

			return;
		}
	}

}

package edu.hue.jk;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MainServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//设置请求编码格式
		req.setCharacterEncoding("utf-8");
		//设置响应编码格式
		resp.setContentType("text/html;charset=utf-8");
		//欢迎语
		resp.getWriter().write("

"+"欢迎用户"+req.getParameter("uname")+"

"
); resp.getWriter().write("
"
); } }
package edu.hue.jk.bean;

public class User {
	private int Uid;
	private String uname;
	private String pwd;
	public int getUid() {
		return Uid;
	}
	public void setUid(int uid) {
		Uid = uid;
	}
	public String getUname() {
		return uname;
	}
	public void setUname(String uname) {
		this.uname = uname;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public User(int uid, String uname, String pwd) {
		super();
		Uid = uid;
		this.uname = uname;
		this.pwd = pwd;
	}
	@Override
	public String toString() {
		return "User [Uid=" + Uid + ", uname=" + uname + ", pwd=" + pwd + "]";
	}
	

}

package edu.hue.jk.dao;

import edu.hue.jk.bean.User;

public interface LoginDao {
	//去数据库验证账户密码存在
	User checkLoginDao(String uname ,String pwd);
	//去数据库验证uid是否存在
	User checkLoginDao(String uid);

}

package edu.hue.jk.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import edu.hue.jk.bean.User;

public class LoginDaoImpl implements LoginDao {

	@Override
	public User checkLoginDao(String uname ,String pwd) {
		//声明Jdbc对象
		Connection conn;
		PreparedStatement ps;
		ResultSet rs;
		User u = null;
		//加载驱动
		try {
			Class.forName("com.mysql.jdbc.Driver");
			//获取连接对象
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", "root");
			//创建sql命令
			String sql = new String("select * from t_user where uname = ? and pwd = ?");
			//创建sql命令对象
			ps = conn.prepareStatement(sql);
			//给占位符赋值
			ps.setString(1, uname);
			ps.setString(2, pwd);
			//执行
			rs = ps.executeQuery();
			//遍历执行结果
			while(rs.next()){
				int Uid = rs.getInt("Uid");
				String t_uname = rs.getString("uname");
				String t_pwd = rs.getString("pwd");
				//赋值User对象
				u = new User(Uid, t_uname, t_pwd);
				
			}
			//关闭资源
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//返回user
		return u;
		
		
		
	}

	@Override
	public User checkLoginDao(String uid) {
		//声明Jdbc对象
				Connection conn;
				PreparedStatement ps;
				ResultSet rs;
				User u = null;
				//加载驱动
				try {
					Class.forName("com.mysql.jdbc.Driver");
					//获取连接对象
					conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", "root");
					//创建sql命令
					String sql = new String("select * from t_user where Uid = ?");
					//创建sql命令对象
					ps = conn.prepareStatement(sql);
					//给占位符赋值
					ps.setString(1, uid);
					//执行
					rs = ps.executeQuery();
					//遍历执行结果
					while(rs.next()){
						int Uid = rs.getInt("Uid");
						String t_uname = rs.getString("uname");
						String t_pwd = rs.getString("pwd");
						u = new User(Uid, t_uname, t_pwd);
						
					}
					//关闭资源
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return u;
				
				
	}
	

}

package edu.hue.jk.server;

import edu.hue.jk.bean.User;

public interface LoginServer {
	//校验用户登录信息
	User checkLoginServer(String uname ,String pwd);
	//校验用户Cookie信息
	User checkLoginServer(String uid);


}

package edu.hue.jk.server;

import edu.hue.jk.bean.User;
import edu.hue.jk.dao.LoginDao;
import edu.hue.jk.dao.LoginDaoImpl;

public class LoginServerImpl implements LoginServer {

	@Override
	public User checkLoginServer(String uname ,String pwd) {
		//创建Dao层过度向
		LoginDao dao =  new LoginDaoImpl();
		//校验用户登录信息
		return dao.checkLoginDao(pwd, pwd);
	}

	@Override
	public User checkLoginServer(String uid) {
		LoginDao dao =  new LoginDaoImpl();
		//校验Cookie信息
		return dao.checkLoginDao(uid);
	}
	

}

以下是运行截图:

page页面:
Servlet学习(二) 写一个Javaweb登陆项目&Cookie技术_第2张图片
登陆成功Servlet学习(二) 写一个Javaweb登陆项目&Cookie技术_第3张图片
登陆错误
Servlet学习(二) 写一个Javaweb登陆项目&Cookie技术_第4张图片
Servlet学习(二) 写一个Javaweb登陆项目&Cookie技术_第5张图片
Servlet学习(二) 写一个Javaweb登陆项目&Cookie技术_第6张图片

你可能感兴趣的:(个人QQ1126140903)