servlet交互
1.1 引入servlet依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
1.2 创建testservlet
继承httpservlet
,重写其doget
和dopost
方法,在testservlet类上添加注解@WebServlet("/login")
,/login
为映射路径
package com.j3071.web.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/login")
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("登录了");
System.out.println(req.getParameter("userName"));
resp.sendRedirect("huanying.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
1.3 jsp中添加form表单,method
选择get
,action
为/login
,使用按钮提交表单,即可把页面上的数据提交到testservlet
的doget
方法中
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>Hello World!</h2>
<%--method 请求方式 action 动作--%>
<form method="get" action="/login">
<p>用户名:<input name="userName"></p>
<p>密码:<input name="passWord"></p>
<p><button type="submit">登录</button></p>
</form>
</body>
</html>
1.4 servlet
获取请求参数req.getParameter
(参数的名字),跳转页面resp.sendRedirect
(要跳转页面的名字.jsp)