java web 课上实验

一、对站点应用filter几时,是局域网中指定IP地址不能访问你的网站,其它IP地址可以
二、使用过滤器处理中文乱码问题
三、未登录的用户不能看见页面中的图片,登录之后才能看见

第一题:
filter文件:

package ch06;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 定义IpFilter过滤器,过滤掉自己配置的ip列表禁止访问系统
 * ip列表在配置的filter中加入初始化参数即可。
 * @author Administrator
 *
 */
public class IP_filter implements Filter{

	String [] forbidIps = null;
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		//由于拦截器定义的拦截规范是/* ,所以所有的请求都会被拦截,为了防止死循环 开一个特例显示具体的访问结果
		if(((HttpServletRequest)request).getRequestURI().contains("forbid.jsp")){
			filterChain.doFilter(request, response);
			return;//不加return 会继续执行请求。
		}
		String remoteAddr = request.getRemoteAddr();      //获取客户端IP地址进行比较
		if(forbidIps!=null){
			for (int i=0; i<forbidIps.length; i++) {
				if(forbidIps[i].equals(remoteAddr)){
					//如果访问的ip与配置的ip相等 则直接过滤掉。
					((HttpServletResponse)response).sendRedirect("error.jsp");
					return;
				}
			}
		}
		filterChain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//获取在web.xml中配置的<filter>的初始化参数
		String initParamter = filterConfig.getInitParameter("forbidIps");
		if(initParamter != null){
			forbidIps = initParamter.split(",");
		}
	}

}

XML文件:

<web-app>
<filter>
    <display-name>IP_filter</display-name>
    <filter-name>IP_filter</filter-name>
    <filter-class>ch06.IP_filter</filter-class>
    <init-param>
      <param-name>forbidIps</param-name>
      <param-value>192.168.12.133,192.168.6.99</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>IP_filter</filter-name>
    <url-pattern>/IP.jsp</url-pattern>
  </filter-mapping>
</web-app>

JSP文件:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>只有没有过滤的IP才能访问</title>
</head>
<body>
hello
</body>
</html>

第二题:
JSP文件:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>中文乱码</title>
</head>
<body>
<%
System.out.println(request.getContextPath());
%>
<form action="ZhonWentijiao" method="post">
  <input type="text" name="username"><br/>
  <input type="submit" value="提交">
</form>
</body>
</html>

Filter文件:

package ch06;
 
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
public class ZhonWenfile implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
 
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse)servletResponse;
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        filterChain.doFilter(request,response);
    }
        
    @Override
    public void destroy() {
 
    }
}

servlet文件:

package ch06;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
/**
 * Created by YYBJ on 2018/9/18.
 * ZCL
 */
public class ZhonWentijiao extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String munber = req.getParameter("munber");
        System.out.println("username===="+munber);
        resp.getWriter().write(munber);
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

XML文件:

<servlet>
    <description></description>
    <display-name>ZhonWentijiao</display-name>
    <servlet-name>ZhonWentijiao</servlet-name>
    <servlet-class>ch06.ZhonWentijiao</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ZhonWentijiao</servlet-name>
    <url-pattern>/ZhonWentijiao</url-pattern>
  </servlet-mapping>
  <filter>
    <display-name>ZhonWenfile</display-name>
    <filter-name>ZhonWenfile</filter-name>
    <filter-class>ch06.ZhonWenfile</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>ZhonWenfile</filter-name>
    <url-pattern>/ZhonWentijiao</url-pattern>
  </filter-mapping>

第三题:

JSP文件:

<%@ page language="java" import="java.awt.Image" import="java.io.FileInputStream" import="java.io.FileNotFoundException" import="java.awt.image.BufferedImage" import="java.util.Iterator" import="java.io.File" import="javax.imageio.stream.ImageInputStream" import="javax.imageio.ImageIO" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html"; charset=UTF-8>
<title>
Insert titile here
</title>

</head>
<body>


<form action="Loginsave" method="post" >
用户名:<input type="text" name="username" /><br>
密&nbsp;&nbsp;&nbsp;&nbsp;码:<input type="password" name="password" /><br>
<input type="submit"  value="登录" />

</form>



</body>

</html>

servlet文件:

package ch06;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class Loginsave extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();									//输出流
		String username = (String) request.getParameter("username");			//从html文件中获取用户名密码,cookie时间
		String password = (String) request.getParameter("password");		
		
		Users user = new Users();												//构造用户对象的方法
		user.setUsername(username);											//写入用户对象方法
		user.setPassword(password);
		request.getSession().setAttribute("user", user);					//将用户名保存在session中

		response.sendRedirect("xianshitupian.jsp");								//转到登陆页面
	}
	public void doPost(HttpServletRequest request,HttpServletResponse response)
	throws ServletException,IOException{
		doGet(request,response);
	}

}

User类对象:

package ch06;

public class Users {												//用户对象
	private String username;
	private String password;
	private String time;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {					//用户对象写入方法
		this.username = username;
	}
	public String getPassword() {								//用户对象获取方法
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

Filter文件:

package ch06;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * Servlet Filter implementation class LoginChecs
 */
public class LoginChecs implements Filter {

    /**
     * Default constructor. 
     */
    public LoginChecs() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	   public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
	    HttpServletRequest request = (HttpServletRequest) servletRequest;
	    HttpServletResponse response = (HttpServletResponse) servletResponse;
		// 获得session
		HttpSession session = request.getSession();								//使用session对象
        // 从session中获取SessionKey对应值,若值不存在,则重定向到redirectUrl
        Object users = session.getAttribute("user");
        System.out.println("username===="+users);
        if (users != null) {
        	request.getSession().removeAttribute("user");				//从session中删除用户名记录
            filterChain.doFilter(request, response);
        } else {
            response.sendRedirect("error.jsp");
        }
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
posted @ 2021-06-10 18:07  网抑云黑胶SVIP用户  阅读(69)  评论(0编辑  收藏  举报