一个简单的jsp+servlet实例,实现简单的登录

开发环境eclipse+tomcat7


1、先创建webproject,项目名为LoginTest,创建时记得勾选Generate web.xml deployment descriptor

2、在WebContent目录下创建login.jsp文件,只需修改body中的内容,如下所示:


   


   username:

   password:

   
   

 

3、在scr目录下的com.ht.servlet编写AcountBean.java文件,代码如下:

package com.ht.servlet;

public class AccountBean {
 private String username = "";
 private String password = "";
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
}

4、在scr目录下的com.ht.servlet编写servlet类CheckAccount.java文件,代码如下:

package com.ht.servlet;

importjava.io.IOException;

importjavax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CheckAccount extendsHttpServlet {

 @Override
 protected void doPost(HttpServletRequest req,HttpServletResponse resp)
   throwsServletException, IOException {
  doGet(req,resp);
 }

 @Override
 public void doGet(HttpServletRequest req,HttpServletResponse resp)
   throwsServletException, IOException {
  HttpSession session =req.getSession();
  AccountBeanaccount = newAccountBean();
  Stringusername = req.getParameter("username");
  String pwd =req.getParameter("pwd");
  account.setPassword(pwd);
  account.setUsername(username);
  if((username !=null)&&(username.trim().equals("jsp"))){
   if((pwd !=null)&&(pwd.trim().equals("1"))){
    System.out.println("success");
    session.setAttribute("account",account);
    Stringlogin_suc = "success.jsp";
    resp.sendRedirect(login_suc);
    return;
   }
  }
  String login_fail ="fail.jsp";
  resp.sendRedirect(login_fail);
  return;
 }
 
}

5、在WebRoot目录下编写success.jsp文件 成功后跳转

页面上端引用AccountBean所在的包<%@page import="com.ht.servlet.AccountBean"%>


   <%
   AccountBean account =(AccountBean)session.getAttribute("account");
   %>
   username:<%= account.getUsername()%>
    

    password:<%= account.getPassword()%>
 

6、在WebRoot目录下编写fail.jsp文件失败后跳转


   Login Failed!

 

7、修改web.xml配置文件


 xmlns="
http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
   login.jsp
 

 
 
      This is the descriptionof my J2EEcomponent
      This is the displayname of my J2EEcomponent
        CheckAccount
      com.ht.servlet.CheckAccount
    

    
      CheckAccount
      /login
    

 


你可能感兴趣的:(一个简单的jsp+servlet实例,实现简单的登录)