1. Servlet
一、Servlet介绍
1、概念
Servlet(Server Applet)是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,具有独立于平台和协议的特性,主要功能在于交互式地浏览和生成数据,生成动态Web内容。
2、实现过程
1.客户端发送请求至服务器端;
2.服务器将请求信息发送至 Servlet;
3.Servlet 生成响应内容并将其传给服务器。响应内容动态生成,通常取决于客户端的请求;
4.服务器将响应返回给客户端。
3、生命周期
1.客户端请求该 Servlet;
2.加载 Servlet 类到内存;
3.实例化并调用init()方法初始化该 Servlet;
4.service()(根据请求方法不同调用doGet() 或者 doPost(),此外还有doHead()、doPut()、doTrace()、doDelete()、doOptions()、destroy())。
二、Request对象(获取请求信息)
2.1获取相应消息数据
2.2 获取请求参数
String getParameter(String name):根据参数名称获取参数值
String[] getParameterValues(String name):根据参数名称获取参数值的数组
Enumeration<String> getParameterNames():获取所有请求的参数名称Map<String,String[]> getParameterMap():获取所有参数的map集合
2.3请求转发
1. 通过request对象获取请求转发器对象:RequestDispatcher getRequestDispatcher(String path)
2. 使用RequestDispatcher对象来进行转发:forward(ServletRequest request, ServletResponse response)
2.4 共享数据
void setAttribute(String name,Object obj):存储数据Object getAttitude(String name):通过键获取值void removeAttribute(String name):通过键移除键值对
post乱码解决
在获取参数前,设置request的编码request.setCharacterEncoding("utf-8");
三、Response对象(设置响应消息)
3.1 设置响应消息
3.2 重定向
方法:response.sendRedirect("路径");
特点:1. 地址栏发生变化
2. 重定向可以访问其他站点(服务器)的资源
3. 重定向是两次请求。不能使用request对象来共享数据
重定向与转发的区别:
forward:一般用于用户登陆的时候,根据角色转发到相应的模块。
redirect:一般用于用户注销登陆时返回主页面和跳转到其它的网站等。
四、综合案例
4.1新建项目步骤
4.2 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.beiyou</groupId><artifactId>servlet</artifactId><version>1.0-SNAPSHOT</version><name>servlet</name><packaging>war</packaging><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.target>1.8</maven.compiler.target><maven.compiler.source>1.8</maven.compiler.source><junit.version>5.8.1</junit.version></properties><dependencies><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version><scope>provided</scope></dependency><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><version>${junit.version}</version><scope>test</scope></dependency><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-engine</artifactId><version>${junit.version}</version><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-war-plugin</artifactId><version>3.3.2</version></plugin></plugins></build>
</project>
4.3 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version="4.0"><servlet><servlet-name>HelloServlet</servlet-name><servlet-class>com.beiyou.servlet.HelloServlet</servlet-class></servlet><servlet-mapping><servlet-name>HelloServlet</servlet-name><url-pattern>/hello-servlet</url-pattern></servlet-mapping>
</web-app>
4.4 HelloServlet.java
package com.beiyou.servlet;import java.io.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;//@WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet {private String message;public void init() {message = "Hello World!";}public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {//response.setContentType("text/html");response.setHeader("Content-Type","text/html;charset=UTF-8");PrintWriter out = response.getWriter();out.println("<html><body>");out.println("<h1> Servlet 你好,这是您要的麻婆豆腐 </h1>");out.println("</body></html>");}public void destroy() {}
}
4.5 乱码-解决
中文乱码
解决ide控制台乱码
五、使用注解
@WebServlet(name = "helloServlet", value = "/hello-servlet")
1.1 使用JSP页面
1、编写a.jsp页面
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %><!DOCTYPE html>
<html>
<head><title>JSP - Hello World</title>
</head>
<body>
<h1><%= "潘周聃1写死" %>
</h1>
<hr/>
<h1><%Object value = request.getAttribute("name");out.println(value);%>
</h1>
<hr/>
<h1>${requestScope.name}
</h1>
<hr/>
<h1>id: ${requestScope.user.id}
</h1>
<h1>姓名: ${requestScope.user.name}
</h1></body>
</html>
request和requestScope的区别_xiangwang2016的博客-CSDN博客_requestscope
EL表达式中,param和requestScope的区别在看param和requestScope之前,不妨先了解下在java下request的情况:1. request对象通常用来接收客户端提交到服务端的数据,如:在servlet或者action中可以用request.getParameter()的方法获取获取参数内容;2. requestScope通常是在servlet或者ac...
https://blog.csdn.net/xiangwang2016/article/details/85119692
2、Servlet传递参数到jsp页面
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {//通过请求作用域对象HttpServletRequest接口添加共享数据request.setAttribute("name","苍老师");//将数据写入请求作用于对象name(key名称)Map<String,Object> map = new HashMap<>();map.put("id",1);map.put("name","潘周聃");request.setAttribute("user",map); //通过请求转发索要a.jsp并写入到响应体中request.getRequestDispatcher("a.jsp").forward(request,response); }
<body><%Object o= request.getAttribute("name") ;out.println(o);
%>基本类型:${requestScope.name}对象id:${requestScope.user.id}对象name:${requestScope.user.name}
</body>
1.2 使用模板引擎
1.引入模板库
<dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version><scope>compile</scope></dependency><dependency><groupId>org.apache.taglibs</groupId><artifactId>taglibs-standard-impl</artifactId><version>1.2.5</version></dependency>
2. servlet 传递集合
public class User {private int id;private String name;
}
request.setAttribute("userLst",userLst);request.getRequestDispatcher("template.jsp").forward(request,response);
3. 页面头加上渲染方式
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<h1>使用模板引擎</h1><table><c:forEach items="${requestScope.userLst}" var="user"><tr><td>${user.id }</td><td>${user.name }</td></tr></c:forEach>
</table>
1.3 使用Post接受表单请求
1.书写表单
<form method="post" action="a"><input type="text" name="id" placeholder="请输入名 "><input type="text" name="name" placeholder="请输入姓 "><input type="submit" value="提交" >
</form>
2.书写doPost
@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//处理表单数据req.setCharacterEncoding("UTF-8");String id = req.getParameter("id");String name = req.getParameter("name");//构造一个响应页resp.setHeader("Content-Type","text/html;charset=utf-8");//一旦调用getWriter方法,此时header的内容就不能更改Writer writer = resp.getWriter();writer.write("<html>");writer.write("id: "+id);writer.write("<br/>");writer.write("name: "+name);writer.write("</html>");}
3.Post传输Json数据
3.1 引入fastjson包
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.28</version></dependency>
3.2 form表单提交
url:http://localhost:8080/demo/bBody:{"id":5,"name":"zhouxingxing"}
3.3 书写doPost方法
@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//读取request body 数据ServletInputStream inputStream = request.getInputStream();InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");BufferedReader bufferedReader = new BufferedReader(inputStreamReader);String jsonStr = "";String line;while ((line = bufferedReader.readLine()) != null){jsonStr += line;}// 转成对象JSONObject jsonObject = JSONObject.parseObject(jsonStr);JSONObject jsonObject2 = new JSONObject();//正常成功时候返回的格式jsonObject2.put("code",0);jsonObject2.put("data",jsonObject);jsonObject2.put("message","请求成功");//失败的时候返回的格式// jsonObject2.put("code",1);// jsonObject2.put("data",null);// jsonObject2.put("message","连接数据库失败");response.setCharacterEncoding("utf-8");response.setContentType("application/json");response.getWriter().write(String.valueOf(jsonObject2));// PrintWriter writer = response.getWriter();
// writer.println("<html>");
// writer.println("<body>");
// writer.println("id -> "+jsonObject.getString("id"));
// writer.println("<br/>");
// writer.println("name -> "+jsonObject.getString("name"));
// writer.println("</body>");
// writer.println("</html>");}
成功:
失败: