首先贴出login.jsp代码
<%@ page contentType="text/html;charset=UTF-8" language="java"%>登录 ${error}
然后贴后端控制器代码
package com.github.zhangkaitao.shiro.chapter7.web.servlet;import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.IncorrectCredentialsException;import org.apache.shiro.authc.UnknownAccountException;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.subject.Subject;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 java.io.IOException;/** *User: Zhang Kaitao *
Date: 14-1-29 *
Version: 1.0 */@WebServlet(name = "loginServlet", urlPatterns = "/login")public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String error = null; String username = req.getParameter("username"); String password = req.getParameter("password"); Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(username, password); token.setRememberMe(true); try { subject.login(token); } catch (UnknownAccountException e) { error = "用户名/密码错误"; } catch (IncorrectCredentialsException e) { error = "用户名/密码错误"; } catch (AuthenticationException e) { //其他错误,比如锁定,如果想单独处理请单独catch处理 error = "其他错误:" + e.getMessage(); } if(error != null) {//出错了,返回登录页面 req.setAttribute("error", error); req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp); } else {//登录成功 req.getRequestDispatcher("/WEB-INF/jsp/loginSuccess.jsp").forward(req, resp); } }}
后端控制器分别有两个关于登录验证的方法,一个是doGet一个是doPost,那当前端访问 (1)如果没有表单提交访问的情况下,默认是访问doGet方法 (2)如果有表单提交访问,并且表单没有指定method="post",这时访问的还是doGet方法 (3)如果有表单提交访问,并且表单指定method="post",这时访问的是doPost方法