(10)JavaWeb 一些注意事项 和 登录功能MVC的三层架构

  1. 我们在jsp页面中,写form表单中的提交action的时候,我们都要去写绝对路径 加上工程名称,并且我们不能把工程名称给写死。
    代码演示:
<!-- 
我们使用pageContext.request.contextPath来获取当前工程的名称
-->
<form action="${pageContext.request.contextPath }/AdminServlet">

登录功能MVC三层架构

  • 创建三个包:web service dao
  1. 先写web里的servlet
protected void service(HttpServletRequest request, HttpServletResponse response) 
   throws ServletException, IOException {
	//获取登录jsp页面中的请求参数
	String name = request.getParameter("username");
	String pwd = request.getParameter("password");

	//写在service方法中
	AdminService adminService = new AdminService();
	//将service和dao中的异常抛了出来,到这里不能再抛了,需要try catch
	try {
	//若是登录成功,则跳转后台首页
	//1.将用户信息保存在session域中
  		Admin admin = adminService.login(name,pwd);
   		HttpSession session = request.getSession();
   		session.setAttribute("admin",admin);
   	//2.跳转到后台首页
   	//使用重定向,相当于让浏览器跳转指定的位置,地址栏改变,而登陆失败里的跳转不会改变地址栏
   		response.sendRedirect(request.getContextPath()+"/admin/admin_index.jsp");
   	} catch (Exception e) {
   	//若是登录失败,跳转回登录页面,并区分是哪种异常
   		if(e.getMessage.equals("用户名或密码错误")){	
			request.getRequestDispatcher("admin/admin_login.jsp").forward(request,response);
		}else{
   		e.printStackTrace();
   		}
}
  1. service中的AdminService
public class AdminService{
	public Admin login(name,pwd) throws Exception{
		//调用dao中的方法,进行检测登陆是否成功
		AdminDao adminDao = new AdminDao();
		Admin admin = adminDao.check(name,pwd);
		//在dao中查到结果,判断admin是否存在
		if(admin != null){
			//如果不为空的话
			return admin;
		}else{
			//如果为空的话,我们写一个异常,将这个异常跑出去,然后在servlet中
			//判断时我们密码输入错误的异常还是我们在dao中的sql语句错误的异常
			throw new Exception("用户名或密码错误");
		}
	}
}
  1. dao中的AdminDao
public class AadminDao{
	public Admin check(name,pwd) throws SQLException{
		//1.连接数据库
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "select * from admin where username=? and password=?";
		Admin admin = null;
		//2.在数据库中进行查询,因为只查询一个用户,所以用BeanHandle即可
		//将查询的结果放在admin中,返回admin
		admin = qr.query(sql,new BeanHandle<Admin>(Admin.class),name,pwd);
		return admin;
	}
}

注意事项:
我们在写jap中的action,src,href时,都要写绝对路径,不要写相对路径。
因为在服务器跳转时,路径相对的是服务器WebContent,浏览器请求跳转时,路径相对的时当前的jsp。
绝对路径
action = “${pageContext.request.contextPath }/文件名”

发布了21 篇原创文章 · 获赞 7 · 访问量 355

猜你喜欢

转载自blog.csdn.net/qq_45260619/article/details/104039990
今日推荐