用Servlet实现简单的用户登录界面
首先创建一个Web工程(UserManager)
在src目录下创建com.focus.userCtrl充当控制器
控制器的作用:
在src目录下创建com.focus.userView作为界面视图
一、先在com.focus.userView创建UserLogin.java(Servlet文件),代码如下:
package com.focus.userView;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserLogin extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<form action='/UserManager/UserCtrl' method='post'>");
out.println("<h2>用户登录界面</h2><br/>");
out.println("用户名:<input type='text' name='username' /><br/>");
out.println("密 码:<input type='password' name='password' /><br/>");
out.println("<input type='submit' value='登录' />");
out.println("</form>");
}
}
说明:
//action的形式
<form action=”/web应用名/Servlet的url” method=”get/post”>
二、在com.focus.userCtrl包下创建UserCtrl.java(Servlet文件),在com.focus.userView包下创建MainFrame.java(Servlet文件)
UserCtrl.java代码如下:
package com.focus.userCtrl;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserCtrl extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.sendRedirect("/UserManager/MainFrame");
}
}
说明:
//跳转页面 location为绝对URL(/web应用/Servlet的URL)
response.sendRedirect(String location);
MainFrame.java代码如下:
package com.focus.userView;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MainFrame extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=gbk");
PrintWriter out = response.getWriter();
out.println("<h2>欢迎来到登录首页</h2>");
out.println("<a href='/UserManager/UserLogin'>返回登录界面</a>");
}
}
三、启动Tomcat,装入UserManager工程(即把UserManager工程发送到Tomcat webapps目录下),打开浏览器,输入http://localhost:8080/UserManager/UserLogin 出现如下效果。