request细节一----->通过request获取ip
/** * Servlet request常用方法 */ @WebServlet("/RequestDemo1") public class RequestDemo1 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //页面访问次数,拦截访问 System.out.println(request.getRequestURI());//很常见 System.out.println(request.getRequestURL()); System.out.println(request.getQueryString());//得到查询信息也就是http://www.snowing.com?name=1 //得到name=1 System.out.println(request.getRemoteAddr());//得到访问者ip地址 System.out.println(request.getRemoteHost());//得到访问者主机名---》如果没在dns上注册就打印主机名 System.out.println(request.getRemotePort());//得到访问者端口(随机的) System.out.println(request.getLocalAddr());//返回web服务器的主机地址 System.out.println(request.getLocalName());//返回web服务器的主机名---》如果没在dns上注册就打印主机名 System.out.println(request.getMethod());//得到客户机请求方式 } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
结果:访问:http://localhost:8082/day05/RequestDemo1?name=1
request细节二----->通过request获取头信息
request细节三----->通过request获取请求头数据
request细节四----->通过request控制编码问题
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // request.setCharacterEncoding("UTF-8");//只有post生效 String username=new String(request.getParameter("username").getBytes("iso8859-1"),"UTF-8"); //反向查找,get/post都可以 //URLEncoder.encode(username, "UTF-8"); System.out.println(username); }
<meta charset="UTF-8">
另一种处理方式,在uri里带参数的情况,可以在tomcat server.xml里配置
post和get都通用的乱码配置情况:
servlet里配置:
server.xml:
request细节四----->MVC模式(model=javabean view=jsp controller=servlet)
jsp:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> ${data} <% String data=(String) request.getAttribute("data"); out.write(data); %> </body> </html>
servlet:
/** * 请求转发,以及使用request域对象把数据带给转发资源 */ @WebServlet("/RequestDemo3") public class RequestDemo3 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data="aaaa"; request.setAttribute("data", data); request.getRequestDispatcher("/1.jsp").forward(request, response);//把数据转发给jsp,并显示 } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
转发不能在response关闭后转发,所以一定记得,return!!!
//forward会清空response中的数据
页头和页脚总一样就用这种方式:
注意:head.jsp和foot.jsp要这样