关于Java web项目,怎么防止在浏览器中直接敲地址进入后台

来源:互联网 发布:360提示网络连接失败 编辑:程序博客网 时间:2024/05/16 00:38
在登陆的时候存一个session登陆成功,session为success,失败为error定义一个类实现Filter在doFilter中进行判断session是否为空或者error然后在web.xml中配置过滤器
1.定义一个LoginAction,关键代码如下:
<span style="background-color: rgb(255, 255, 255);">public class AdminLoginAction extends ActionSupport {private static final long serialVersionUID = 1L;private boolean success;private String message;private Admin admin;private List<Admin> adminList;private AdminService adminService = new AdminService();private HttpServletRequest request = ServletActionContext.getRequest();private HttpSession session = request.getSession();@Overridepublic String execute() throws Exception {adminList = adminService.list();for (int i = 0; i < adminList.size(); i++) {if (admin.getName().equals(adminList.get(i).getName())&& admin.getPassword().equals((String) adminList.get(i).getPassword())) {session.setAttribute("Adminlogin", "Right");this.success = true;return SUCCESS;}}this.success = false;this.message = "对不起,未授权的用户不能登录改系统";return SUCCESS;}}</span>

2.struts.xml中的配置
<span style="background-color: rgb(255, 255, 255);">         <action name="ManagerLogin" class="com.kxw.NewsReleaseSystem.loginAction.ManagerLoginAction" method="login">     <result name="success">/front/Welcome.jsp</result>     <result name="error">/front/Error.jsp</result>        </action></span>
3.编写过滤器
<span style="background-color: rgb(255, 255, 255);">public class AdminLoginFilter implements Filter {public void destroy() {}public void doFilter(ServletRequest arg0, ServletResponse arg1,            FilterChain arg2) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) arg0;        HttpSession session = request.getSession();        if (session.getAttribute("Adminlogin")!=null) {                arg2.doFilter(arg0, arg1);                }        else{        request.getRequestDispatcher("../../illegalLoginError.jsp").forward(arg0, arg1);                   }}public void init(FilterConfig filterConfig) throws ServletException {}}</span>

4.在web.xml中配置过滤器
<span style="background-color: rgb(255, 255, 255);"><filter>  <filter-name>AdminLogin</filter-name>  <filter-class>com.kxw.NewsReleaseSystem.filter.AdminLoginFilter</filter-class> </filter>                                                                                                      <filter-mapping> <filter-name>AdminLogin</filter-name> <url-pattern>/admin/superAdmin/*</url-pattern></filter-mapping></span>