JavaWeb实现servlet登录

JavaWeb实现servlet登录_第1张图片

lib里servlet包不能少

JavaWeb实现servlet登录_第2张图片

配置servlet一共有两种方式,一种是使用web.xml文件配置,另外一种就是使用注解配置,下面我们来详解介绍这两种配置方式  

web-inf下的web.xml方式



  
  
  	
  	MyServlet
  	
  	cn.roobtyan.servlet.FirstServlet
  
  
  
  
  
  	
  	MyServlet
  	
  	/first
  

使用注解的方式(servlet jar包太低会失效)

@WebServlet(name = "UserServlet",urlPatterns = "/UserServlet")
public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,            IOException {
​
    }
​
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,             IOException {
​
    }
}

 web.xml 



  nj1
  
    login.jsp
  
  
  LoginServlet
  com.servlet.LoginServlet
  
  
  LoginServlet
  /LoginServlet
  

loginServlet.servlet

package com.servlet;

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 javax.servlet.http.HttpSession;

@WebServlet(name = "LoginServlet",urlPatterns = "/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//System.out.println("进来了");
		loginServlet(request,response);
	}   
  
	public void loginServlet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		//设置字符编码
		request.setCharacterEncoding("utf8");
		//从request对象中获取username,password
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String repassword=request.getParameter("repassword");
		HttpSession session = request.getSession(true);
		//判断是否为管理员
		if("admin".equals(username)&&"123456".equals(password)&&"123456".equals(repassword)){
			//登录成功,设置session
			System.out.println("登陆成功");
			session.setAttribute("user", "登录成功!");
			//将页面转发到欢迎页面
			request.getRequestDispatcher("result.jsp").forward(request, response);		
		}else {
			System.out.println("登录失败");
			session.setAttribute("user","登录信息错误,请检查用户名或密码");
			//将页面转发到欢迎页面
			request.getRequestDispatcher("result.jsp").forward(request, response);		
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>



在线考试----登录



	

 result.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    欢迎页面


    

Welcome:

<% out.println(session.getAttribute("user")); %>

你可能感兴趣的:(html,前端,javascript)