`
Kingson_Wu
  • 浏览: 111249 次
文章分类
社区版块
存档分类
最新评论

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

 
阅读更多
在登陆的时候存一个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();

	@Override
	public 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>



















分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics