jsp页面访问servlet

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



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运行之后得到的结果如下所示:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值