ServletContext获取Web配置参数
1.新写一个java文件,并在Web.xml里面配置
package top.servlet2;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class OtherServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = (String) context.getAttribute("username");//去ServletContext里面取username的信息
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<!--配置web应用的初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
<!-- Other.java的注册-->
<servlet>
<servlet-name>gp</servlet-name>
<servlet-class>top.servlet2.OtherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gp</servlet-name>
<url-pattern>/gp</url-pattern>
</servlet-mapping>
ServletContext转发请求
1.新建一个java来写请求的东西
2.web.xml里面注册
3.然后我们就会在/dis目录下看见之前的配置被转发了