Servlet与JSP进阶

HTTP请求结构

  • HTTP请求包含三部分:请求行,请求头,请求体

巧用请求头开发多端应用

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	// TODO Auto-generated method stub
	String userAgent=request.getHeader("User-Agent");
	response.setContentType("text/html;charset=utf-8");
	response.getWriter().println(userAgent);
	String output = "";
	if(userAgent.indexOf("Windows NT")!= -1) {
		output = "<h1>这是pc端首页</h1>";
	}else if (userAgent.indexOf("iPhone")!= -1) {
		output = "<h1>这是iPhone端首页</h1>";
	}else if (userAgent.indexOf("Android")!= -1) {
		output = "<h1>这是Android端首页</h1>";
	}
	response.getWriter().println(output);
}

响应结构

  • HTTP响应包含三部分:响应行、响应头、响应体
状态码错误描述
200服务器处理成功
404无法找到文件
500内部服务器错误
403服务器拒绝访问
301,302请求重定向
400无效的请求
401未经过授权
503服务器超负载或正停机维护,无法处理请求

ContentType的作用

  • ContentType决定浏览器采用何种方式对响应体进行处理,决定了代码的展现形式
MIME类型描述
text/plain纯文本
text/htmlHTML文档
text/xmlXML文档
application/x-msdownload需要下载的资源
image/jpeg image/gif image/…图片资源

请求转发与重定向

请求转发

  • 服务器会跳转,只会产生一次请求
  • request.getRequestDispatcher).forward() -请求转发:不会改变地址栏中的地址

响应重定向

  • 浏览器端跳转,会产生两次请求
  • response.sendRedirect() -响应重定向:回调转到重定向的地址

设置请求自定义属性

  • 请求允许创建自定义属性
  • 设置请求属性: request.setAttribute(属性名, 属性值)
  • 获取请求属性: Object attr = request.getAttribute(属性名)

浏览前Cookie

  • Cookie是浏览器保存在本地的文本内容
  • Cookie常用于保存登录状态、用户资料等小文本
  • Cookie具有时效性,Cookie内容会伴随请求发送给Tomcat
==================loginServlet=====================
@WebServlet("/cookies/login")
public class loginServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("用户登录成功!");
		Cookie cookie = new Cookie("user","admin");
		response.addCookie(cookie);		//创建Cookie信息
		cookie.setMaxAge(60*60*24*7);   //设置cookie的保存时间
		response.getWriter().println("login success!");
	}
}
===================indexServlect=======================
@WebServlet("/cookies/index")
public class indexServlect extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Cookie[] cookie = request.getCookies();//获取Cookie信息
		if(cookie==null) {
			response.getWriter().println("user not login");
			return;
		}
		String user=null;
		for(Cookie cs : cookie) {
			String cd=cs.getName()+":"+cs.getValue();
			System.out.println(cd);
			response.getWriter().println(cd);
			if(cs.getName().equals("user")) {
				user=cs.getValue();
			}
		}
		if (user == null) {
			response.getWriter().println("user not login");
		}else {
			response.getWriter().println("user:"+user);
		}
	}
}

Session-用户会话

  • Session (用户会话)用于保存与"浏览器窗口”对应的数据
  • Session的数据存储在Tomcat服务器的内存中,具有时效性
  • Session通过浏览器Cookie的Sessionld值提取用户数据
    与浏览器绑定的且吧内容存储在Tomcat中的对象
===========SessionLoginServlet=============
@WebServlet("/session/login")
public class SessionLoginServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("用户登录成功");
		//获取到用户会话Session对象
		HttpSession session = request.getSession();
		String sessionId = session.getId();
		System.out.println(sessionId);
		session.setAttribute("name", "admin");
		request.getRequestDispatcher("/session/index").forward(request, response);
	}
}
============SessionIndexServlet=================
@WebServlet("/session/index")
public class SessionIndexServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String sessionId = session.getId();
		System.out.println(sessionId);
		String name = (String)session.getAttribute("name");
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().println("这是首页,当前用户为:"+name);
	}
}

Session原理

ServletContext

  • ServletContext(Servlet上下文对象),是Web应用全局对象
  • 一个Web应用只会创建一个ServletContext对象
  • ServletContext随着Web应用启动而自动创建
================ServletContextServlet===================
@WebServlet("/servletcontext/init")
public class ServletContextServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext context = request.getServletContext();
		context.setAttribute("copyright", "afterglow");
		context.setAttribute("title", "唐僧洗头艹飘柔");
		response.getWriter().println("init success:");
	}
}
=================ServletContextDefaultServlet===================
@WebServlet("/servletcontext/default")
public class ServletContextDefaultServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext servletcontext = (ServletContext)request.getServletContext();
		String copyright = (String) servletcontext.getAttribute("copyright");
		String title = (String) servletcontext.getAttribute("title");
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().println("<h1>"+copyright+"</h1>");
		response.getWriter().println("<h1>"+title+"</h1>");
	}
}

Java Web三大作用域对象

  • HttpServletRequest -请求对象:生命周期最短,当一个请求送往tomcat中,这个对象就会存在了,当Servlet处理完成并且产生响应返回给浏览器,当前的请求对象就会被销毁
  • HttpSession -用户会话对象:第一次用户发来请求的时候创建,在30分钟后没有访问这个session就会被销毁
  • ServletContext - web应用全局对象:Web应用程序启动的时候被创建,在Web应用程序重启或者关闭的时候被销毁
    作用域和生命周期依次递增
    能用小作用域开发的就不要使用大的作用域开发

Web应用的中文乱码由来

  • Tomcat默认使用字符集ISO-8859-1,属于西欧字符集
  • 解决乱码的核心思路是将ISO-8859-1转换为UTF-8
  • Servlet中请求与响应都需要设置UTF-8字符集
@WebServlet("/charset/process")
public class CharsetServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//对于Tomcat8.x的版本,默认get请求发送中文就是UTF-8的格式,因此无需转换
		String ename = request.getParameter("ename");
		String address = request.getParameter("address");
		response.setContentType("text/html;charset=utf-8");//设置响应的输出字符集
		response.getWriter().println(ename+":"+address);
		System.out.println(ename+":"+address);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//request.setCharacterEncoding方法用于将请求体重的字符集转为UTF-8
		request.setCharacterEncoding("UTF-8");
		// TODO Auto-generated method stub
		String ename = request.getParameter("ename");
		String address = request.getParameter("address");
		response.setContentType("text/html;charset=utf-8");//设置响应的输出字符集
		response.getWriter().println(ename+":"+address);
		System.out.println(ename+":"+address);
	}
}

web.xml常用配置

  • 设置全局参数

  • 获取url
================PatternServlet=====================
public class PatternServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//查询员工基本信息
		//获取当前访问的URL
		String url = request.getRequestURI().toString();
		System.out.println(url);
		String id = url.substring(url.lastIndexOf("/")+1);
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().println(id);
	}
}
===================XML=======================
<servlet>
   <servlet-name>patternServlet</servlet-name>
   <servlet-class>fun.afterglow.servlet.pattern.PatternServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>patternServlet</servlet-name>
   <!--这里的url最后需要使用*-->
   <url-pattern>/pattern/*</url-pattern>
</servlet-mapping>
  • 修改web应用默认首页
 <welcome-file-list>
   <welcome-file>index.html</welcome-file>
   <welcome-file>index.htm</welcome-file>
   <welcome-file>index.jsp</welcome-file>
   <welcome-file>default.html</welcome-file>
   <welcome-file>default.htm</welcome-file>
   <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>
//web.xml会依次检查这些页面是否存在,如果有一个存在他就会自动加载
  • Servlet通配符映射级初始化参数
==================XML======================
<context-param>
   <param-name>title</param-name>
   <param-value>唐僧洗头艹飘柔</param-value>
</context-param>
<context-param>
   <param-name>copyright</param-name>
   <param-value>afterglow</param-value>
</context-param>
=====================ServletContextServlet=========================
@WebServlet("/servletcontext/init")
public class ServletContextServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext context = request.getServletContext();
		String copyright = context.getInitParameter("copyright");
		String title = context.getInitParameter("title");
		context.setAttribute("copyright", copyright);
		context.setAttribute("title", title);
		response.getWriter().println("init success:");
	}
}
===============ServletContextDefaultServlet=====================
@WebServlet("/servletcontext/default")
public class ServletContextDefaultServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext servletcontext = (ServletContext)request.getServletContext();
		String copyright = (String) servletcontext.getAttribute("copyright");
		String title = (String) servletcontext.getAttribute("title");
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().println("<h1>"+copyright+"</h1>");
		response.getWriter().println("<h1>"+title+"</h1>");
	}
}
  • 设置404/500等状态码默认页面
 <!--指定错误页面 location需要指定页面所在位置-->
 <error-page>
   <error-code>404</error-code>
   <location>/error/404.html</location>
 </error-page>
 <error-page>
   <error-code>500</error-code>
   <location>/error/500.html</location>
 </error-page>

JSP九大内置对象

  • 内置对象和在class中使用时完全一样的
内置对象描述
request请求对象- HttpServletRequest
response响应对象- HttpServletResponse
session用户会话- HttpSession
application应用全局对象- ServletContext
out输出对象- PrintWriter
page当前页面对象-this
pageContext页面上下文对象- PageContext
config应用配置对象- ServletConfig
exception应用异常对象-Throwable
<%
	String url = request.getRequestURL().toString();// HttpServletRequest
	response.getWriter().println(url);//HttpServletPrsponse
%>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值