Servlet模拟登陆应用
(1)熟悉开发环境,使用Myeclipse管理Web项目,掌握包括创建项目、发布项目、启动Tomcat等操作。
(2)掌握Servlet开发方法,理解post提交和get提交方式,理解request对象。
内容简介
步骤
- 在Myeclipse中 新建Web工程
- 创建reg.jsp,erro.jsp,success.jsp页面
- 创建regServlet.java
- 创建regBean.java
整体结构与代码
reg.jsp代码
<%@ page language="java" import="java.util.*" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>reg.jsp</title>
</head>
<body>
<h1>用户注册</h1>
<form name="regForm" action="regServlet" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="text" name="password" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="提交"/></td>
</tr>
</table>
</form>
</body>
</html>
success.jsp代码
<%@ page language="java" import="java.util.*" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>success.jsp</title>
</head>
<body>
注册成功
</body>
</html>
erro.jsp代码
<%@ page language="java" import="java.util.*" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>erro.jsp</title>
</head>
<body>
错误页面
</body>
</html>
regServlet.java代码
去博客设置页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的 代码片
.
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;
import bean.regBean;
/**
* Servlet implementation class regServlet
*/
@WebServlet("/regServlet")
public class regServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置request对象的解码方式
request.setCharacterEncoding("utf-8");
String username=request.getParameter("username");//用于获取某个指定名称的参数值
String password=request.getParameter("password");
regBean regbean=new regBean();
if(regbean.dealNewUser(username,password))
request.getRequestDispatcher("success.jsp").forward(request, response);//请求转发
else
request.getRequestDispatcher("erro.jsp").forward(request, response);
}
}
regBean.java代码
public class regBean {
public boolean dealNewUser(String username,String password)
{
if(username!=null&&!username.equals("")&&password!=null&&!password.equals(""))
return true;
else
return false;
}
}