一、简介

是一个特殊的java类,可以接收http请求,并加以处理,作为前台页面和后台java代码连接的一个桥梁。

二、使用

1.创建包servlet
2.创建LoginServlet
3.代码

 package org.lanqiao.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;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
    public LoginServlet() {
    }

	/**
	 * 默认提交的地址
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//获取用户名和密码
		String name=request.getParameter("username");
		String pass=request.getParameter("pass");
		
		
		if("admin".equals(name)&&"123".equals(pass)) {
			//登录成功,放入用户名,跳转到成功页
			request.setAttribute("name", name);
			request.getRequestDispatcher("success.jsp").forward(request, response);
		}else {
			
			//登陆失败,重定向到登录项
			response.sendRedirect("error.jsp");
		}
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

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

}

4.将@WebServlet("/LoginServlet")中LoginServlet放入到login.jsp中<form action="LoginServlet" method="post">, 放入到表单中action位置

所有的请求都会默认进入service方法,如果想进入不同方法,需要删除service方法,把代码写到doGet或者doPost中

三、使用JBDC

1.导入MySQl驱动包,把驱动的jar包放在下,并且添加到构建路径

2.通过DBUtil.java工具类,查找用户是否在数据库中存在

3.存在就转发成功页,不存在跳转到登录页

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//处理请求中中文乱码
		request.setCharacterEncoding("utf-8");
		
		//获取用户名和密码
		String name=request.getParameter("username");
		String pass=request.getParameter("pass");
		
		//使用gdbc连接数据库判断用户名和密码是否正确
		
		Connection conn=DBUtil.getConn();
		String sql="select * from student where name=? and pass=?";
		
		Object[] objs={name,pass};
		
		ResultSet rs=DBUtil.excuteQuery(sql, objs);
		
		//封装用户
		Student stu=null;
		
		try {
			if(rs.next()) {
				String stuName=rs.getString("name");
				String stuPass=rs.getString("pass");
				
				stu=new Student(stuName,stuPass);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(stu!=null) {
			//登录成功,放入用户名,跳转到成功页
			request.setAttribute("name", name);
			
			request.getRequestDispatcher("success.jsp").forward(request, response);
		}else {
			
			//登陆失败,重定向到登录项
			response.sendRedirect("error.jsp");
		}
		

	}
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐