欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jsp页面访问servlet

程序员文章站 2022-06-01 22:49:11
...

1.新建一个Dynamic Web Project项目,里面新建一个servlet,新建一个jsp,整体的框架结构如下所示:

jsp页面访问servlet


2.LoginServlet.java文件的代码如下所示:

package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=GBK");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("GBK");
		String name = request.getParameter("user");
		String password = request.getParameter("pwd");
		out.println("<html><body>");
		if (name == null || name.length() == 0) {
			out.println("请输入用户名!");
		} else if (password == null || password.length() == 0) {
			out.println("请输入密码!");
		} else if (name.length() > 0 && password.length() > 0) {
			if (name.equals("zhangsan") && password.equals("lisi")) {
				out.println("输入信息正确!");
			} else {
				out.println("输入信息错误!");
			}
		}
		out.println("</html></body>");
	}

}

3.login.jsp文件的代码如下所示:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login.jsp</title>
</head>
<body>
	<form action="LoginServlet" method="post">
		<table>
			<tr>
				<td>用户名:</td>
				<td><input type="text" name="user" /></td>
			</tr>
			<tr>
				<td>密码:</td>
				<td><input type="password" name="pwd" /></td>
			</tr>
			<tr>
				<td><input type="submit" value="提交" /></td>
				<td><input type="reset" value="重置" /></td>
			</tr>
		</table>
	</form>
</body>
</html>

4.在浏览器里面输入http://localhost:8080/Servlet/login.jsp运行之后得到的结果如下所示:

jsp页面访问servlet

相关标签: jsp页面访问servlet