实验三:Servlet 基础

一、实验目的:

1、理解Servlet的工作原理;
2、掌握javabean在web程序中的应用;
3、掌握基于Servlet的MVC模式;

二、实验环境:

Eclipse

三、实验内容:
(写出主要的内容)
1、参考教材P142的例子,使用JSP、Servlet、JavaBean实现基于MVC模式的用户登录验证程序。

loginCheck.jsp

<body>
<form action="loginCheckServlet" method="post">
<table>
<tr>
<td>用户名: </td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>密     码:</td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td><input type="submit" value="提交" id="bt"/></td>
<td><input type="reset" value="重置"/></td>
</tr>
</table>
</form>
</body>

效果:
在这里插入图片描述
loginSuccess.jsp

<body>
<jsp:useBean id="user" type="dto.User" scope="request"/>
恭喜<jsp:getProperty property="name" name="user"/>登录成功!
</body>

效果:
在这里插入图片描述
User.java

package dto;
public class User {
	private String name;
	private String pwd;
	public String getName () {
	return name ;
	}
	public void setName (String name) {
	this.name = name;
	}
	public String getPwd() {
	return pwd;
	}
	public void setPwd (String pwd) {
	this.pwd = pwd;
	}
}

UserCheck.java

package service;
import dto.User;
public class UserCheck {
	//验证登录
	public boolean validate(User user) {
	if (user != null && user.getName().equals("JSPMVC")){
		if (user.getPwd().equals("MVC")) {
			return true;
		}
		return false;
		}
	return false;
	}
}

loginCheckServlet.java

package servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 service.UserCheck;
import dto.User;
@WebServlet (name="loginCheckServlet",urlPatterns={"/loginCheckServlet"})
public class loginCheckServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet (HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException{
		doPost (request, response);
	}
	protected void doPost (HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException{
		request.setCharacterEncoding ("utf-8");
		String name = request.getParameter ("name");
		String pwd = request.getParameter ("pwd");
		User user = new User();//实例化实体模型user
		user.setName (name) ;//将数据存在模型user中
		user.setPwd (pwd) ;//将数据存在模型user中
		UserCheck uc = new UserCheck();//实例化业务模型userCheck
		if (uc.validate (user)) {
			//将装有数据的实体模型user存储到request范围内
			request.setAttribute("user", user);
			RequestDispatcher dis = request.getRequestDispatcher ("loginSuccess.jsp");
			dis.forward(request, response);
			} else{
				response.sendRedirect("loginCheck.jsp");
			}
	}
}


©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页