html修改为jsp、错误消息显示、错误消息回显、多个请求对应一个servlet、获取请求参数封装成对象

html修改为jsp:
a) 新建一个jsp文件,并将html页面复制进新页面(主要page指令要保留)
b) 在html页面中加入一个page指令,然后修改文件扩展名为jsp
c) 提取出页面中重复的部分,在通过include指令将这些内容分别引入网页

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

========================
浏览器地址访问路径提取到base.jsp:
项目上线部署到服务器时,主机名、端口号、项目名称有可能发生变化,如果在编程的时候路径写死了,那么每次更新访问路径信息的时候,对代码内的路径也需做出修改,不利于系统项目的维护。


    http://localhost:8080/BookStore_EG03/ <br />
    http://<%=request.getServerName() %>:<%=request.getServerPort() %><%=request.getContextPath() %>/
    <hr />
    getServerName <%=request.getServerName() %> <br />
    getServerPort <%=request.getServerPort() %> <br />
    getContextPath <%=request.getContextPath() %> <br />

base.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<base href="http://<%=request.getServerName() %>:<%=request.getServerPort() %><%=request.getContextPath() %>/" />
<link type="text/css" rel="stylesheet" href="static/css/style.css" >
<script type="text/javascript" src="static/script/jquery-1.7.2.js"></script>

这里写图片描述
这里写图片描述

=====================
登录和注册页面的错误消息显示:
登录或注册失败以后再页面中显示错误消息
登录,登录失败时也就是用户名或密码输错了,我们需要在域中设置一个错误消息然后在页面显示出来。

LoginServlet.java:
这里写图片描述

LoginServlet .java

package com.atguigu.bookstore.servlet.client;

import java.io.IOException;

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

import com.atguigu.bookstore.bean.User;
import com.atguigu.bookstore.service.UserService;
import com.atguigu.bookstore.service.impl.UserServiceImpl;

/**
 * 处理用户登录的Servlet
 * @author lilichao
 *
 */
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    //创建一个UserService
    private UserService userService = new UserServiceImpl();

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

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

        //获取用户填写用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //将用户名和密码封装为User对象
        User user = new User(null, username, password, null);

        //调用Service验证用户名和密码
        User loginUser = userService.login(user);

        //如果loginUser为null,用户名或密码错误,转发到login.html
        if(loginUser == null){

            //登录失败,设置一个错误消息 用户名或密码错误
            request.setAttribute("msg", "用户名或密码错误!");

            request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
        }else{
            //用户名和密码正确登录成功,重定向到login-success.html
            response.sendRedirect(request.getContextPath()+"/pages/user/login_success.jsp");
        }

    }

}

Login.jsp:
这里写图片描述

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>尚硅谷会员登录页面</title>
<%@ include file="/WEB-INF/include/base.jsp" %>
</head>
<body>
        <div id="login_header">
            <img class="logo_img" alt="" src="static/img/logo.gif" >
        </div>

            <div class="login_banner">

                <div id="l_content">
                    <span class="login_word">欢迎登录</span>
                </div>

                <div id="content">
                    <div class="login_form">
                        <div class="login_box">
                            <div class="tit">
                                <h1>尚硅谷会员</h1>
                                <a href="pages/user/regist.jsp">立即注册</a>
                            </div>
                            <div class="msg_cont">
                                <b></b>
                                <%-- <%
                                    String msg = (String)request.getAttribute("msg");
                                    if(msg == null){
                                        msg = "请输入用户名和密码";
                                    }

                                %> --%>
                                <span class="errorMsg"><%=request.getAttribute("msg")==null?"请输入用户名和密码":request.getAttribute("msg") %></span>
                            </div>
                            <div class="form">
                                <form action="client/UserServlet?method=login" method="post">

                                    <!-- <input type="hidden" name="method" value="login" /> -->

                                    <label>用户名称:</label>
                                    <input value="<%=request.getParameter("username")==null?"":request.getParameter("username") %>" class="itxt" type="text" placeholder="请输入用户名" autocomplete="off" tabindex="1" name="username" />
                                    <br />
                                    <br />
                                    <label>用户密码:</label>
                                    <input class="itxt" type="password" placeholder="请输入密码" autocomplete="off" tabindex="1" name="password" />
                                    <br />
                                    <br />
                                    <input type="submit" value="登录" id="sub_btn" />
                                </form>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        <div id="bottom">
            <span>
                尚硅谷书城.Copyright &copy;2015
            </span>
        </div>
</body>
</html>

========================
表单的回显:
登录或注册失败以后,在表单中显示用户上次输入的信息
这里写图片描述


                                    <label>用户名称:</label>
                                    <input value="<%=request.getParameter("username")==null?"":request.getParameter("username") %>" class="itxt" type="text" placeholder="请输入用户名" autocomplete="off" tabindex="1" name="username" />

============================
背景:一个功能对应一个servlet
问题1:目前我们的项目中是一个功能对应一个Servlet,登录有LoginServlet、注册有RegistServlet、删除用户有DelUserServlet、修改用户有UpdateUserServlet、添加图书有AddBookServlet。。。这样会导致我们的项目被淹没在Servlet海洋中。

解决:一个Serlvet可以处理多个请求,比如有一个UserServlet那么用户相关的请求都可交给该Servlet,比如登录对应一个login方法,注册对应一个regist方法。
具体步骤:
1.先创建一个UserServlet
2.在Servlet中创建两个方法,一个是login 一个是regist
3.当用户要登录时调用login 注册时调用regist
4.我们希望用户可以告诉Servlet要掉login还是调regist
5.我们通过用户传递method属性来判断要调用的方法。

UserServlet .java

package com.atguigu.bookstore.servlet.client;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.atguigu.bookstore.bean.User;
import com.atguigu.bookstore.service.UserService;
import com.atguigu.bookstore.service.impl.UserServiceImpl;
import com.atguigu.bookstore.servlet.BaseServlet;
import com.atguigu.bookstore.utils.WEBUtils;

/**
 * 处理用户相关请求的Servlet
 * @author lilichao
 *
 */
public class UserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    //创建一个UserService对象
    private UserService userService = new UserServiceImpl();

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

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取用户传递的请求参数
        String methodName = request.getParameter("method");

        //根据mehodName的值去调用不同的方法
        if("login".equals(methodName)){
            //调用login方法
            login(request, response);
        }else if("regist".equals(methodName)){
            //调用regist方法
            regist(request, response);
        }else if("delUser".equals(methodName)){
            delUser();
        }


    }


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

        //获取用户填写用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //将用户名和密码封装为User对象
        User user = new User(null, username, password, null);

        //调用Service验证用户名和密码
        User loginUser = userService.login(user);

        //如果loginUser为null,用户名或密码错误,转发到login.html
        if(loginUser == null){

            //登录失败,设置一个错误消息 用户名或密码错误
            request.setAttribute("msg", "用户名或密码错误!");

            request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
        }else{
            //用户名和密码正确登录成功,重定向到login-success.html
            response.sendRedirect(request.getContextPath()+"/pages/user/login_success.jsp");
        }

    }


    protected void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取用户填写用户名、密码、电子邮件
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        //封装User对象
        User user = new User(null, username, password, email);


        //调用Service将User插入进数据库
        boolean isRegist = userService.regist(user);

        //注册成功,重定向到regist_success.html
        if(isRegist){
            response.sendRedirect(request.getContextPath()+"/pages/user/regist_success.jsp");
        }else{
            //设置一个错误消息
            request.setAttribute("msg", "用户名已存在!");

            //注册失败,转发到regist.html
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);

        }
    }


}

==================================

问题2:在这个UserServlet中每添加一个方法,就要添加一个与之对应if else语句,这样会导致if else很多。
解决:
如果可以直接根据方法名,获取到方法,我们就可以直接去调用方法,而不需要再手动调用
通过反射动态的获取用户要调用的方法对象,然后在去调用这个方法,这样做的好处是,当在添加新的方法进Servlet时,不需要写if else,用户只需传递相应的方法名即可调用方法。
注意:我们所定义的方法要和doGet和doPost方法结构一样,可以通过重写doGet方法然后改名的形式创建方法。

UserServlet .java

package com.atguigu.bookstore.servlet.client;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.atguigu.bookstore.bean.User;
import com.atguigu.bookstore.service.UserService;
import com.atguigu.bookstore.service.impl.UserServiceImpl;
import com.atguigu.bookstore.servlet.BaseServlet;
import com.atguigu.bookstore.utils.WEBUtils;

/**
 * 处理用户相关请求的Servlet
 * @author lilichao
 *
 */
public class UserServlet {
    private static final long serialVersionUID = 1L;

    //创建一个UserService对象
    private UserService userService = new UserServiceImpl();

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

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

        //获取用户传递的请求参数
        String methodName = request.getParameter("method");

        //通过方法名获取到方法的对象

        //获取当前类的Class对象
        Class<? extends UserServlet> cla = this.getClass();
        //获取cla的的方法(Method对象)
        //getDeclaredMethod需要两个参数,方法名和参数名
        //因为在java需要通过方法名和参数列表来确定一个方法
        try {
            //获取方法对象
            Method method = cla.getDeclaredMethod(methodName, HttpServletRequest.class , HttpServletResponse.class);
            //设置方法的访问权限
            method.setAccessible(true);
            //调用方法
            //invoke用于调用一个方法,第一个参数时要调用方法的对象,剩下是调用方法需要的参数
            method.invoke(this, request , response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

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

        //获取用户填写用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //将用户名和密码封装为User对象
        User user = new User(null, username, password, null);

        //调用Service验证用户名和密码
        User loginUser = userService.login(user);

        //如果loginUser为null,用户名或密码错误,转发到login.html
        if(loginUser == null){

            //登录失败,设置一个错误消息 用户名或密码错误
            request.setAttribute("msg", "用户名或密码错误!");

            request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
        }else{
            //用户名和密码正确登录成功,重定向到login-success.html
            response.sendRedirect(request.getContextPath()+"/pages/user/login_success.jsp");
        }

    }


    protected void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取用户填写用户名、密码、电子邮件
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        //封装User对象
        User user = new User(null, username, password, email);

        //调用Service将User插入进数据库
        boolean isRegist = userService.regist(user);

        //注册成功,重定向到regist_success.html
        if(isRegist){
            response.sendRedirect(request.getContextPath()+"/pages/user/regist_success.jsp");
        }else{
            //设置一个错误消息
            request.setAttribute("msg", "用户名已存在!");

            //注册失败,转发到regist.html
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);

        }
    }
}

===========================

问题3:将反射这一系列代码编写到了当前Servlet,那么我们每新创建一个Servlet这一堆代码就得在写一遍,我们的代码不能复用。
解决:创建一个BaseServlet,将这些重复的代码在BaseServlet中编写,其他Servlet只需继承BaseServlet而不用再次编写重复的代码。

BaseServlet.java:该类不用处理请求,只是被其它类继承而已,所以并不需要在web.xml中配置。

package com.atguigu.bookstore.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

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

import com.atguigu.bookstore.servlet.client.UserServlet;

/**
 * 专门用来被其他Servlet继承
 * @author lilichao
 *
 */
public class BaseServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


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

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取用户传递的请求参数
        String methodName = request.getParameter("method");
        //通过方法名获取到方法的对象
        //获取当前类的Class对象
        Class cla = this.getClass();
        //获取cla的的方法(Method对象)
        //getDeclaredMethod需要两个参数,方法名和参数名
        //因为在java需要通过方法名和参数列表来确定一个方法
        try {
            //获取方法对象
            Method method = cla.getDeclaredMethod(methodName, HttpServletRequest.class , HttpServletResponse.class);
            //设置方法的访问权限
            method.setAccessible(true);
            //调用方法
            //invoke用于调用一个方法,第一个参数时要调用方法的对象,剩下是调用方法需要的参数
            method.invoke(this, request , response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

UserServlet.java:

package com.atguigu.bookstore.servlet.client;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.atguigu.bookstore.bean.User;
import com.atguigu.bookstore.service.UserService;
import com.atguigu.bookstore.service.impl.UserServiceImpl;
import com.atguigu.bookstore.servlet.BaseServlet;
import com.atguigu.bookstore.utils.WEBUtils;

/**
 * 处理用户相关请求的Servlet
 * @author lilichao
 *
 */
public class UserServlet extends BaseServlet {
    private static final long serialVersionUID = 1L;

    //创建一个UserService对象
    private UserService userService = new UserServiceImpl();
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取用户填写用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //将用户名和密码封装为User对象
        User user = new User(null, username, password, null);

        //调用Service验证用户名和密码
        User loginUser = userService.login(user);

        //如果loginUser为null,用户名或密码错误,转发到login.html
        if(loginUser == null){

            //登录失败,设置一个错误消息 用户名或密码错误
            request.setAttribute("msg", "用户名或密码错误!");

            request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
        }else{
            //用户名和密码正确登录成功,重定向到login-success.html
            response.sendRedirect(request.getContextPath()+"/pages/user/login_success.jsp");
        }

    }


    protected void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取用户填写用户名、密码、电子邮件
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        //封装User对象
        User user = new User(null, username, password, email);


        //调用Service将User插入进数据库
        boolean isRegist = userService.regist(user);

        //注册成功,重定向到regist_success.html
        if(isRegist){
            response.sendRedirect(request.getContextPath()+"/pages/user/regist_success.jsp");
        }else{
            //设置一个错误消息
            request.setAttribute("msg", "用户名已存在!");

            //注册失败,转发到regist.html
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);

        }
    }
}

注意:
当我们使用get请求时,get请求会覆盖action中的请求参数
当使用get请求时,可以在表单中设置一个表单隐藏域,这个域的name属性是method,值是要调用的方法
这里写图片描述

<div class="form">
                                <form action="client/UserServlet?method=login" method="post">

                                    <!-- <input type="hidden" name="method" value="login" /> -->

                                    <label>用户名称:</label>
                                    <input value="<%=request.getParameter("username")==null?"":request.getParameter("username") %>" class="itxt" type="text" placeholder="请输入用户名" autocomplete="off" tabindex="1" name="username" />
                                    <br />
                                    <br />
                                    <label>用户密码:</label>
                                    <input class="itxt" type="password" placeholder="请输入密码" autocomplete="off" tabindex="1" name="password" />
                                    <br />
                                    <br />
                                    <input type="submit" value="登录" id="sub_btn" />
                                </form>
                            </div>

===========================

问题4:在大部分的Servlet中都需要先获取用户发送的请求参数,然后将这些请求参数封装为对象,像这些操作都是一些比较简单,但是又比较繁琐(尤其是当我们需要做转型操作)
解决:写一个通用工具类来替咱们做这件事(BeanUtils)。
需要导入以下2个jar包:
commons-beanutils-1.8.0.jar
commons-logging-1.1.1.jar

JavaBean
属性私有化,通过getter和setter方法对属性进行读取和设置
有一个无参的构造器
JavaBean的属性指的是getter方法中属性名,属性名指的getter或setter方法将get或set去掉,然后首字母小写。getName()属性名叫name,如果有一个getAge()属性名叫age。
使用BeanUtils可以直接将一个Map转换一个JavaBean的对象。
我们想可不不可以获取到请求参数的map,然后将这个map直接转换为我们想要的对象。
我们通过BeanUtils的populate方法将请求参数的map直接封装为对象,但是这块有一个问题需要注意表单项中name属性要和类中的属性名一样,否则将不能进行封装。

Student.java

package com.atguigu.bean;

public class Student {

    private String name1;
    private int age;
    private String address;

    public String getName() {
        return name1;
    }

    public void setName1(String name) {
        this.name1 = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Student(String name, int age, String address) {
        super();
        this.name1 = name;
        this.age = age;
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student [name=" + name1 + ", age=" + age + ", address="
                + address + "]";
    }

}

TestBeanUtils.java

package com.atguigu.bean;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;

public class TestBeanUtils {

    @Test
    public void test2(){

        //创建一个map
        Map<String, Object> map = new HashMap<String, Object>();
        //向map中添加属性
        map.put("name1", "猪八戒");
        map.put("age", "38");
        map.put("address", "高老庄");

        //将这个map转换为一个Student对象
        Student stu = new Student();

        //populate可以将一个map转换成指定的java对象,要求map中key要和对象的属性名一致
        try {
            BeanUtils.populate(stu, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


        System.out.println(stu);


    }

    @Test
    public void test() {

        Student stu = new Student();

        /*stu.setName("孙悟空");
        stu.setAge(18);
        stu.setAddress("花果山");*/

        String name = "sunwukong";
        String age = "18";
        String address = "花果山";

        //BeanUtils可以动态想JavaBean设置或读取属性
        //使用BeanUtils需要导入两个jar包
        //commons-beanutils-1.8.0.jar
        //commons-logging-1.1.1.jar
        //setProperty方法需要设置三个参数,第一个参数需要一个对象,指定要为哪个对象设置属性
        //第二参数要设置的属性名 , 第三个参数时一个要设置的值
        try {
            //这个方法就可以像stu对象中设置一个name属性为孙悟空
            BeanUtils.setProperty(stu, "name", "孙悟空");
            //设置一个age,BanUtils可以自动转型
            BeanUtils.setProperty(stu, "age", "abc");

            BeanUtils.setProperty(stu, "address", "花果山");

            System.out.println(stu);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

=============

优化servlet:

WEBUtils .java

package com.atguigu.bookstore.utils;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;

import com.atguigu.bookstore.bean.User;

/**
 * WEB相关操作的工具类
 * @author lilichao
 *
 */
public class WEBUtils {

    /**
     * 将请参数封装为一个对象,并返回
     * @param request
     * @param t
     * @return
     */
    public static <T>T param2Bean(HttpServletRequest request, T t) {

        //获取请求参数的map
        Map map = request.getParameterMap();

        System.out.println(map);

        try {
            //将map转换为一个对象
            BeanUtils.populate(t, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        return t;
    }

}

UserServlet.java:

package com.atguigu.bookstore.servlet.client;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.atguigu.bookstore.bean.User;
import com.atguigu.bookstore.service.UserService;
import com.atguigu.bookstore.service.impl.UserServiceImpl;
import com.atguigu.bookstore.servlet.BaseServlet;
import com.atguigu.bookstore.utils.WEBUtils;

/**
 * 处理用户相关请求的Servlet
 * @author lilichao
 *
 */
public class UserServlet extends BaseServlet {
    private static final long serialVersionUID = 1L;

    //创建一个UserService对象
    private UserService userService = new UserServiceImpl();

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

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

        //获取用户传递的请求参数
        String methodName = request.getParameter("method");

        //通过方法名获取到方法的对象

        //获取当前类的Class对象
        Class<? extends UserServlet> cla = this.getClass();
        //获取cla的的方法(Method对象)
        //getDeclaredMethod需要两个参数,方法名和参数名
        //因为在java需要通过方法名和参数列表来确定一个方法
        try {
            //获取方法对象
            Method method = cla.getDeclaredMethod(methodName, HttpServletRequest.class , HttpServletResponse.class);
            //设置方法的访问权限
            method.setAccessible(true);
            //调用方法
            //invoke用于调用一个方法,第一个参数时要调用方法的对象,剩下是调用方法需要的参数
            method.invoke(this, request , response);
        } catch (Exception e) {
            e.printStackTrace();
        }


        //根据mehodName的值去调用不同的方法
        if("login".equals(methodName)){
            //调用login方法
            login(request, response);
        }else if("regist".equals(methodName)){
            //调用regist方法
            regist(request, response);
        }else if("delUser".equals(methodName)){
            delUser();
        }


    }*/


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

        //调用WEBUtils将请求参数封装为一个User对象
        User user = WEBUtils.param2Bean(request , new User());

        //获取到请求参数的map
    /*  Map map = request.getParameterMap();
        //创建一个User对象
        User user = new User();

        try {
            BeanUtils.populate(user, map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        */
        //System.out.println(user);

        /*//获取用户填写用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //将用户名和密码封装为User对象
        User user = new User(null, username, password, null);*/

        //调用Service验证用户名和密码
        User loginUser = userService.login(user);

        //如果loginUser为null,用户名或密码错误,转发到login.html
        if(loginUser == null){

            //登录失败,设置一个错误消息 用户名或密码错误
            request.setAttribute("msg", "用户名或密码错误!");

            request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
        }else{
            //用户名和密码正确登录成功,重定向到login-success.html
            response.sendRedirect(request.getContextPath()+"/pages/user/login_success.jsp");
        }

    }


    protected void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*//获取用户填写用户名、密码、电子邮件
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        //封装User对象
        User user = new User(null, username, password, email);*/

        User user = WEBUtils.param2Bean(request, new User());

        //调用Service将User插入进数据库
        boolean isRegist = userService.regist(user);

        //注册成功,重定向到regist_success.html
        if(isRegist){
            response.sendRedirect(request.getContextPath()+"/pages/user/regist_success.jsp");
        }else{
            //设置一个错误消息
            request.setAttribute("msg", "用户名已存在!");

            //注册失败,转发到regist.html
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);

        }
    }


}

BaseServlet.java:

package com.atguigu.bookstore.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

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

import com.atguigu.bookstore.servlet.client.UserServlet;

/**
 * 专门用来被其他Servlet继承
 * @author lilichao
 *
 */
public class BaseServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


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

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取用户传递的请求参数
        String methodName = request.getParameter("method");
        //通过方法名获取到方法的对象
        //获取当前类的Class对象
        Class cla = this.getClass();
        //获取cla的的方法(Method对象)
        //getDeclaredMethod需要两个参数,方法名和参数名
        //因为在java需要通过方法名和参数列表来确定一个方法
        try {
            //获取方法对象
            Method method = cla.getDeclaredMethod(methodName, HttpServletRequest.class , HttpServletResponse.class);
            //设置方法的访问权限
            method.setAccessible(true);
            //调用方法
            //invoke用于调用一个方法,第一个参数时要调用方法的对象,剩下是调用方法需要的参数
            method.invoke(this, request , response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

login.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>尚硅谷会员登录页面</title>
<%@ include file="/WEB-INF/include/base.jsp" %>
</head>
<body>
        <div id="login_header">
            <img class="logo_img" alt="" src="static/img/logo.gif" >
        </div>

            <div class="login_banner">

                <div id="l_content">
                    <span class="login_word">欢迎登录</span>
                </div>

                <div id="content">
                    <div class="login_form">
                        <div class="login_box">
                            <div class="tit">
                                <h1>尚硅谷会员</h1>
                                <a href="pages/user/regist.jsp">立即注册</a>
                            </div>
                            <div class="msg_cont">
                                <b></b>
                                <%-- <%
                                    String msg = (String)request.getAttribute("msg");
                                    if(msg == null){
                                        msg = "请输入用户名和密码";
                                    }

                                %> --%>
                                <span class="errorMsg"><%=request.getAttribute("msg")==null?"请输入用户名和密码":request.getAttribute("msg") %></span>
                            </div>
                            <div class="form">
                                <form action="client/UserServlet?method=login" method="post">
                                    <!--
注意:
当我们使用get请求时,get请求会覆盖action中的请求参数
当使用get请求时,可以在表单中设置一个表单隐藏域,这个域的name属性是method,值是要调用的方法

-->
                                    <!-- <input type="hidden" name="method" value="login" /> -->

                                    <label>用户名称:</label>
                                    <input value="<%=request.getParameter("username")==null?"":request.getParameter("username") %>" class="itxt" type="text" placeholder="请输入用户名" autocomplete="off" tabindex="1" name="username" />
                                    <br />
                                    <br />
                                    <label>用户密码:</label>
                                    <input class="itxt" type="password" placeholder="请输入密码" autocomplete="off" tabindex="1" name="password" />
                                    <br />
                                    <br />
                                    <input type="submit" value="登录" id="sub_btn" />
                                </form>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        <div id="bottom">
            <span>
                尚硅谷书城.Copyright &copy;2015
            </span>
        </div>
</body>
</html>

===================
未完待续!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值