Servlet:通过初始参数实现权限访问某个文件、页面

目录结构


src 目录下com.xieyuan包MyServlet.java文件(Servlet文件)

package com.xieyuan;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.corba.se.impl.javax.rmi.CORBA.Util;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class MyServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public MyServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}


	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
         request.setCharacterEncoding("UTF-8");
         response.setCharacterEncoding("UTF-8");
         
         response.setContentType("text/html");
         PrintWriter out=response.getWriter();
         out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
         out.println("<HTML>");
         out.println("<HEAD><TITLE>请登录查看NOTICE文件</TITLE></HEAD>");
         out.println("<style>body,td,div{font-size:12px;}</style>");
         out.println("<BODY>");
         
         String referer=request.getHeader("referer");
         //通过获取用户上次进入的页面判断用户是否输入过密码,然后跳转到本页来的
         if(referer!=null&&referer.equals(request.getRequestURL().toString()))
              out.println("<font color='red'>账号密码错误!</font>");
         out.println("<form action='"+request.getRequestURI()+"' method='post'>");
         out.println("账号:<input type='text' name='username' autocomplete='off' style='200px' /><br/>");
         out.println("密码:<input type='password' name='password' style='200px' /><br/>");
         out.println("<input type='submit' value='登录' />");
         out.println("</form>");
         
         //获取上下文参数
         out.println("<BR/>"+ this.getServletContext().getInitParameter("test"));
         out.println("</BODY");
         out.println("</HTML>");
         out.flush();
         out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获得提交的数据
		String userName=request.getParameter("username");
		String password=request.getParameter("password");
		//遍历所有初始参数参数
		Enumeration<?> params=this.getInitParameterNames();
		while(params.hasMoreElements())
		{
			String paramName=(String)params.nextElement();
			String paramValue=this.getInitParameter(paramName);
			if(paramName.equals(userName)&¶mValue.equals(password))
			{
				/*
				 * 一个RequestDispatcher对象作为资源在指定的路径,或者为null的包装,
				 * 如果servlet容器不能返回的RequestDispatcher
				 * 
                        将请求转发到另一个资源(servlet,JSP和文件或HTML文件)从一个servlet在服务器上。
                        此方法允许一个servlet做初步处理的请求和其他资源来生成响应。

				 */
				request.getRequestDispatcher("/WEB-INF/notice.txt").forward(request, response);
				return;
			}
			
		}
		//不匹配,返回
		doGet(request, response);
	}
	
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
	}

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>com.xieyuan.MyServlet</servlet-class>
    <init-param>
       <param-name>user123</param-name>
       <param-value>pass123</param-value>
    </init-param> 
     
  </servlet>
  
  <context-param>
      <param-name>test</param-name>
      <param-value>这是测试数据!</param-value>
  </context-param>
 
  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/servlet/MyServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

部署好WEB后,访问:http://127.0.0.1:8080/Test/servlet/MyServlet 进入登录页面

输入正确的账号:

user123
密码

pass123
访问到预先定义的WEB-INF/notice.txt页面



原文地址:https://www.cnblogs.com/xieyuan/p/3787502.html