使用Servlet实现登录页面并跳转
具体内容为前端数据获取以及请求转发。
1、新建一个Requeset工程,并且完善工程目录结构。
2、更新WEB-INF文件下的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"
metadata-complete="true">
</web-app>
3、在webaopp目录下建立一个新的index.jsp文件,将其内容更改为登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<h1>登录</h1>
<form action="${pageContext.request.contextPath}/login" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="checkbox" name="hobbys" value="唱歌">唱歌
<input type="checkbox" name="hobbys" value="跳舞">跳舞
<input type="checkbox" name="hobbys" value="代码">代码
<br>
<input type="submit">
</form>
</body>
</html>
4、再在相同目录下建立一个sucess.jsp文件,用于进行转发的页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>success</title>
</head>
<body>
<h1>success</h1>
</body>
</html>
至此,webapp目录结构如下:
5、编写java程序进行获取前端传递的参数并且进行请求转发
在java下建立一个包:com.donric.servlet
包下写一个java文件
package com.donric.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//将req和resp设置一下编码,使得页面不会出现乱码情况
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//获取前端传来的数据,这个数据名可以从前面写的jsp文件中找到
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbys = req.getParameterValues("hobbys");
System.out.println("===================");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbys));
System.out.println("===================");
System.out.println(req.getContextPath());
//其自动会寻找本项目下的success.jsp,然后进行请求转发
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
6、在web.xml中注册servlet,内容如下
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.donric.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
7、配置tomcat
选择Tomcat–Local,并且选择好本地tomcat的文件地址
再选择一下artifact
8、启动Tomcat,启动成功会出现如下画面,并填写内容
注:地址栏中的Request_war这个地址是在选择tomcat的artifact时的那个自动生成的Application context
9、提交内容,请求转发成功
注:地址栏中的Request_war这个地址是在选择tomcat的artifact时的那个自动生成的Application context