jsp+servlet 登陆跳转实现

在src路径下新建一个servlet类,用于实现页面的跳转功能,相关代码如下所示:

package com.example.demo;

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;

/**
* Servlet implementation class ServletLogin
*/
@WebServlet("/ServletLogin")
public class ServletLogin extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public ServletLogin() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("username");//
String password = request.getParameter("password");//
System.out.println("用户名====》》》" +userName);
System.out.println("密码=====》》" +password);
// response.sendRedirect("index.jsp");
doGet(request, response);
}
}
在web-content目录下新建一个jsp文件,一定要注意,该jsp文件一定是在web-content目录下,不能在其子目录下,相关代码如下:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="utf-8"%>




Login



username:

password:






这个页面的作用是定义登陆页面的内容

接下来在web.xml中配置servlet路径,相关路径如下所示:

LoginServlet
LoginServlet
com.example.demo.ServletDemo


LoginServlet
/ServletJspLogin/ServletLogin

打开服务器,在地址栏中输入http://localhost:8080/ServletJspLogin/login.jsp,就会代打开已经设计好的登陆界面,在里面输入用户名和密码,点击登陆之后,页面中表单内容将会被送到/ServletJspLogin/ServletLogin路径下,也就是网址http://localhost:8080/ServletJspLogin/ServletLogin下,通过在web.xml中寻找对应名字的servlet-class,找到servlet类,由此开始了servlet的生命周期,通过调用里面的dopost方法,实现输出字符串。

你可能感兴趣的:(jsp+servlet 登陆跳转实现)