Servlet简单使用

  1. 创建一个类 继承 HttpServlet
  2. 实现对doGet doPost的重载
  3. 使用web.xml或者注解 注册Servlet
    使用web.xml配置
<!-- 注册MyServlet -->
<servlet>
   <!-- Servlet的名字 -->
   <servlet-name>MyServlet</servlet-name>
   <!-- Servlet的包名+类名 -->
	   <servlet-class>com.test.MyServlet</servlet-class>
</servlet>
<!-- 配置MyServlet的访问地址 -->
<servlet-mapping>
    <!-- Servlet的名字 -->
    <servlet-name>MyServlet</servlet-name>
    <!-- 网络地址 -->
    <url-pattern>/MyServlet.do</url-pattern>
</servlet-mapping>
package com.wedding.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//使用WebSerlet注册Servlet
@WebServlet("/login.do")
public class UserLoginServlet extends HttpServlet{
     
     

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
     
		System.out.println("doPost");
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
     
		System.out.println("doGet");		
	}	
}

Servlet的请求和响应参数
doGet和doPost的参数:


HttpServletRequest 请求参数,包含请求URL、方法、参数等信息
主要方法:
String getParameter(“参数名”) 获得请求中的参数
setCharacterEncoding(“编码类型”) 设置请求的编码
getMethod() 获得请求方法类型,Get、POST…
getRequestURL() 获得请求的URL


HttpServletResponse 响应参数,给浏览器提供响应的交互
主要方法:
PrintWriter getWriter() 获得输出流,向浏览器发送信息
sendRedirect(“页面地址”) 实现页面的跳转
setCharacterEncoding(“编码类型”) 设置响应的编码

页面跳转的方法
重定向
响应对象的.sendRedirect(“路径”);
forward
请求对象.getRequestDispatcher(“路径”).forward
区别:
重定向:地址栏会变,服务器外跳转
forward:地址栏不变,服务器内跳转,效率更高


中文乱码问题
1、html页面中

<meta charset="utf-8">

2、doGet方法的请求参数
String name = req.getParameter(“name”);
name = new String(name.getBytes(“ISO-8859-1”),“UTF-8”);
3、doPost方法的请求参数
请求对象.setCharacterEncoding(“UTF-8”);
4、响应对象的输出流
响应对象.setContentType(“text/html;charset=UTF-8”);
5、JSP中
在page指令中设置pageEncoding=“UTF-8”


JSP的内置对象
下面四个对象都是用于存取数据
setAttribute(“名称”,值); 保存数据
getAttribute(“名称”); 获取数据
对象 类型 作用范围
application ServletContext 整个网站
session HttpSession 单个用户的所有页面或Servlet
request HttpServletRequest 重点内容跳转前后的两个组件


EL表达式
Expression Language(表达式语言),简化JSP的开发。
简化application、session、request、pageContext中数据的读取。
读取简单数据:
Java脚本:
application.getAttribute(“username”)
EL :
${username}
读取对象的属性:
Java脚本:

<%
   Student stu = (Student)application.getAttribute("stu");
%>
<%= stu.getName()%>
EL:
    ${stu.name}
    ${stu["name"]}

问题:如果在application、session、request、pageContext中都保存了num变量。
使用EL表达式会读取出哪个num?
查找顺序:
pageContext —> request —> session ----> application ----> null

问题:如何指定EL表达式读取的范围?
域对象
pageScope pageContext
requestScope request
sessionScope session
applicationScope application
${域对象.数据名称}

猜你喜欢

转载自blog.csdn.net/qq_33460865/article/details/82623434