package user.web.servlet; 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; import cn.itcast.commons.CommonUtils; import user.domain.User; import user.service.UserException; import user.service.UserService; /** * UserServlet层 * @author 赵奇 * */ public class LoginServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); // 依赖UserService UserService userService = new UserService(); /* * 1、封装表单数据到User form中 * 2、调用service的login()方法,得到返回的User user对象 * > 如果抛出异常:获取异常信息,保存到request域,再保存form,转发到login.jsp * > 如果没有异常,保存返回值到session中,重定向到welcome.jsp */ User form = CommonUtils.toBean(request.getParameterMap(), User.class); try { UserService us = new UserService(); User user = us.login(form); request.getSession().setAttribute("sessionUser", user); response.sendRedirect(request.getContextPath()+"/user/welcome.jsp"); } catch (UserException e) { request.setAttribute("msg", e.getMessage()); request.setAttribute("user", form); request.getRequestDispatcher("/user/login.jsp").forward(request, response); } } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'login.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>登录</h1> <p style="color: red; font-weight: 900">${msg }</p> <form action="<c:url value='/LoginServlet'/>" method="post"> 用户名:<input type="text" name="username" value="${user.username }" /><br/> 密 码:<input type="password" name="password" value="${user.password }"/><br/> <input type="submit" value="登录"/> </form> </body> </html>