问题描述
- web jsp filter 权限控制 运行测试出现500问题 怎么解决
-
工程结构
index.jsp为登陆页面,UserServlet.java为针对登陆的servlet,登陆成功或失败都会跳转到show.jsp,但是有Userfilter.java的过滤。一旦登陆失败会让页面转到error.jsp。
正常是流程:进入index.jsp输入账号密码,登陆成功后进入show.jsp(测试过没问题)
错误的用例:通过控制url绕过index.jsp直接进入show.jsp(出现500错误,应该要进入error.jsp的)index.jsp
用户登陆
用户名:密码:
UserServlet.java
public class UserServlet extends HttpServlet
{public void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException,IOException { String name=req.getParameter("username"); String password=req.getParameter("password"); UserInfo info= new UserInfo(); if(password.equals("123456")) { info.setName(name); info.setPassword(password); req.getSession().setAttribute("name", name); req.getSession().setAttribute("userinfo", info); System.out.println("登陆成功"); RequestDispatcher rd=req.getRequestDispatcher("/hehe/show.jsp"); rd.forward(req, resp); } else { System.out.println("登录失败"); RequestDispatcher rd=req.getRequestDispatcher("/hehe/show.jsp"); rd.forward(req, resp); } } public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException { doGet(request,response); }
}
UserFilter.java
public class UserFilter implements Filter{
//销毁方法
public void destroy() {} //完成过滤操作 public void doFilter(ServletRequest request, ServletResponse response,FilterChain filter) throws IOException, ServletException { UserInfo info=(UserInfo)((HttpServletRequest) request).getSession().getAttribute("userinfo"); String name=((HttpServletRequest) request).getSession().getAttribute("name").toString(); System.out.println("filter 2:"+name); if(info!=null) //if(name!=null) { filter.doFilter(request, response); } else { response.setContentType("text/html;charset=utf-8"); ((HttpServletResponse) response).sendRedirect("../error.jsp"); } } //初始化 public void init(FilterConfig arg0) throws ServletException { }
}
解决方案
直接访问show.jsp的话 session为空啊,当然不行,你还要判断session是否为空,然后再处理跳转,可以写在过滤器里面, 也可以写在show.jsp里面
解决方案二:
java web中配置Filter解决jsp中文乱码问题
解决方案三:
路径要写对,你试试../hehe/show.jsp呢
时间: 2024-09-30 01:10:17