Java Web -- Servlet(7.1) 用Servlet实现简单的用户登录界面

Servlet实现简单的用户登录界面

 

首先创建一个Web工程(UserManager

src目录下创建com.focus.userCtrl充当控制器

控制器的作用:

src目录下创建com.focus.userView作为界面视图

Java Web -- Servlet(7.1) 用Servlet实现简单的用户登录界面_第1张图片 

 

一、先在com.focus.userView创建UserLogin.javaServlet文件),代码如下:

 

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应用名/Servleturl method=get/post>

Java Web -- Servlet(7.1) 用Servlet实现简单的用户登录界面_第2张图片 

 

二、com.focus.userCtrl包下创建UserCtrl.javaServlet文件),在com.focus.userView包下创建MainFrame.javaServlet文件)

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应用/ServletURL

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 出现如下效果。

 

Java Web -- Servlet(7.1) 用Servlet实现简单的用户登录界面_第3张图片 

 

Java Web -- Servlet(7.1) 用Servlet实现简单的用户登录界面_第4张图片

你可能感兴趣的:(java,Web,servlet)