Servlet 的快速入门
添加jar包依赖
在 tomcat10以后使用的是jakarta这个包
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>5.0.0</version>
</dependency>
在tomcat10以前是用的javax这个包
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
实现Servlet接口
public class Demo1 implements Servlet
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("hello servlet");
}
修改tomcat
添加web.xml 配置
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>demo1</servlet-name>
<servlet-class>wy.Demo1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo1</servlet-name>
<url-pattern>/demo1</url-pattern>
</servlet-mapping>
</web-app>
启动访问
http://localhost:8080/use_servlet/demo1
查看控制台打印信息
Servlet 的生命周期
三个生命周期方法
public class Demo1 implements Servlet {
/**
* 在servlet被创建时执行,只会执行一次
* 默认情况下是第一次访问的时候,也可以在配置文件中修改
* @param servletConfig
* @throws ServletException
*/
@Override
public void init(ServletConfig servletConfig) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
/**
* 提供服务的方法
* 每次访问都会执行
* @param servletRequest
* @param servletResponse
* @throws ServletException
* @throws IOException
*/
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("hello servlet");
}
@Override
public String getServletInfo() {
return null;
}
/**
* 销毁方法
* 在servlet被关闭时执行
* 服务器正常关闭时候执行
*/
@Override
public void destroy() {
}
}
修改servlet的访问时间
在servlet标签下新增
<!-- 值为负数时,在第一次访问的时候创建-->
<!-- 值为0或者正数时在服务启动的时候创建-->
<load-on-startup>0</load-on-startup>
Servlet 注解配置
参数使用参考配置
@WebServlet(urlPatterns = "/demo2")
Servlet 的结构
HttpServlet > GenericServlet > Servlet
GenericServlet抽象类 封装了Servlet ,使用者只需要实现其service方法即可
public class Demo3 extends GenericServlet
HttpServlet 基于Http请求响应封装的
@WebServlet("/demo4")
public class Demo4 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("执行了get");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("执行了post");
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("执行了put");
}
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("执行了delete");
}
}
取值
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取单个值 name = "zhangsan"
String name= req.getParameter("name");
System.out.println(name);
// 获取名称下的值集合 name = "zhangsan"&name = "lisi"
String[] names= req.getParameterValues("name");
for (String item:names) {
System.out.println(item);
}
// 取出所有的键值
Map<String,String[]> map= req.getParameterMap();
for (String key: map.keySet()) {
for (String item: map.get(key)) {
System.out.println(item);
}
}
}
中文乱码的问题
req.setCharacterEncoding("utf-8");
请求转发
System.out.println("demo4请求.....");
req.getRequestDispatcher("/demo3").forward(req,resp);
传值
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("demo4请求.....");
req.setAttribute("msg","hello demo3");
req.getRequestDispatcher("/demo3").forward(req,resp);
}
@WebServlet("/demo3")
public class Demo3 extends GenericServlet {
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
String msg = (String) servletRequest.getAttribute("msg");
System.out.println("接收到数据:"+msg);
}
}
工具类的简单使用
导入mvn配置依赖
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
BeanUtils 批量设置属性值
User user= new User();
BeanUtils.populate(user,req.getParameterMap());
System.out.println(user.name);
响应
重定向
resp.sendRedirect("http://www.baidu.com");
设置编码 响应输出字符数据
resp.setContentType("text/html;charset=utf-8");
PrintWriter pw = resp.getWriter();
pw.write("hello 你好");
输出字节数据
resp.setContentType("text/html;charset=utf-8");
ServletOutputStream outputStream = resp.getOutputStream();
outputStream.write("hello 你好111".getBytes());
获取应用程序根目录
ServletContext context = this.getServletContext();
System.out.println(context.getRealPath("/"));
文件下载及解决文件中文乱码问题
ServletContext context = this.getServletContext();
String fileName = "哈哈.txt";
resp.setHeader("content-type","txt");
//获得请求头中的User-Agent
String agent = req.getHeader("User-Agent");
//根据不同浏览器进行不同的编码
String fileNameEncoder = "";
if (agent.contains("MSIE")) {
// IE浏览器
fileNameEncoder = URLEncoder.encode(fileName, "utf-8");
fileNameEncoder = fileNameEncoder.replace("+", " ");
} else if (agent.contains("Firefox")) {
// 火狐浏览器
BASE64Encoder base64Encoder = new BASE64Encoder();
fileNameEncoder = "=?utf-8?B?" + base64Encoder.encode(fileName.getBytes("utf-8")) + "?=";
} else {
// 其它浏览器
fileNameEncoder = URLEncoder.encode(fileName, "utf-8");
}
resp.setHeader("content-disposition","attachment;filename="+fileNameEncoder);
String realPath = context.getRealPath("/");
String filePath = realPath+"../resources/a.txt";
System.out.println(filePath);
FileInputStream fileInputStream = new FileInputStream(filePath);
ServletOutputStream servletOutputStream = resp.getOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while ((len=fileInputStream.read(buff))!=-1){
servletOutputStream.write(buff,0,len);
}