JavaEE學習day-51:整合項目案例

一、實現(xiàn)的功能

1.項目介紹:

項目名稱:
?????尚學堂后臺管理系統(tǒng)
項目需求:
?????實現(xiàn)用戶登錄施符;
?????實現(xiàn)用戶退出养泡;
?????實現(xiàn)用戶注冊埂奈;

2.功能介紹:

用戶登錄:
?????根據(jù)用戶名和密碼查詢用戶信息迄损。查到則登錄成功,查不到則登錄失敗账磺。
用戶退出:
?????用戶退回到登錄頁面芹敌,銷毀session痊远。
用戶戶注冊:
?????將用戶注冊信息插入數(shù)據(jù)庫

3.數(shù)據(jù)庫的設計:

用戶表:t_user
????用戶id:uid
????用戶名:uname
????用戶密碼:pwd
????用戶性別:sex
????用戶年齡:age
????出生日期:birthday

4.SQL語句設計:

用戶登錄:
????select * from t_user where uname=? and pwd=?;
用戶注冊:
????insert into t_user values(default,?,?,?,?,?)氏捞;

  • 代碼實現(xiàn):

使用的MySQL數(shù)據(jù)庫碧聪。
可以使用語句或者客戶端工具直接創(chuàng)建。

二液茎、實現(xiàn)步驟

1.用戶登錄:

(1)用戶點擊登錄發(fā)送請求到UserServlettomcat服務器接收到請求后調(diào)用UserServlet中service方法進行請求處理逞姿,并將封存了相關(guān)數(shù)據(jù)的request對象和response對象作為實參傳遞給service方法。
(2)在UserServlet中調(diào)用業(yè)務層方法進行登錄業(yè)務處理捆等。
(3)在業(yè)務層方法中調(diào)用Dao層方法完成數(shù)據(jù)庫操作滞造。
(4)完成功能跳轉(zhuǎn)。

  • 登錄的界面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!-- 
    添加前端代碼書寫插件
        插件在資料中栋烤,將查詢包放到myEclipse的安裝目錄中的drops文件中谒养,然后重啟myEclipse即可闷袒。
        安裝后快捷鍵為:ctrl+E
    模版套用:
        在自己的項目中創(chuàng)建模版對應的jsp文件
        將jsp文件中的basepath代碼移動到其他位置
        然后將模版中的HTML代碼整個復制到對應的jsp中
        然后將basepath在移動會head標簽中
        將模版中的前端資源文件復制到webRoot下夜焦。
 -->
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
    content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="renderer" content="webkit">
<title>登錄</title>
<link rel="stylesheet" href="css/pintuer.css">
<link rel="stylesheet" href="css/admin.css">
<script src="js/jquery.js"></script>
<script src="js/pintuer.js"></script>
</head>
<body>
    <div class="bg"></div>
    <div class="container">
        <div class="line bouncein">
            <div class="xs6 xm4 xs3-move xm4-move">
                <div style="height:150px;"></div>
                <div class="media media-y margin-big-bottom"></div>
                <form action="user" method="post">
                    <div class="panel loginbox">
                        <div class="text-center margin-big padding-big-top">
                            <h1>尚學堂后臺管理中心</h1>
                        </div>
                        <!-- 聲明java代碼塊 -->
                        <%
                            //獲取session中 的標記
                            Object obj = session.getAttribute("flag");
                            if (obj != null) {
                                if ("loginFalse".equals((String) obj)) {
                        %>
                        <div style="text-align: center;color:red;">用戶名或密碼錯誤</div>
                        <%
                            } else if ("regSuccess".equals((String) obj)) {
                        %>
                        <div style="text-align:center;color:red;">用戶注冊成功</div>
                        <%
                            }
                            }
                            session.invalidate();
                        %>
                        <div class="panel-body"
                            style="padding:30px; padding-bottom:10px; padding-top:10px;">
                            <div class="form-group">
                                <div class="field field-icon-right">
                                    <input type="text" class="input input-big" name="uname"
                                        placeholder="登錄賬號" data-validate="required:請?zhí)顚戀~號" /> <span
                                        class="icon icon-user margin-small"></span>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="field field-icon-right">
                                    <input type="password" class="input input-big" name="pwd"
                                        placeholder="登錄密碼" data-validate="required:請?zhí)顚懨艽a" /> <span
                                        class="icon icon-key margin-small"></span>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="field">
                                    <input type="text" class="input input-big" name="code"
                                        placeholder="填寫右側(cè)的驗證碼" data-validate="required:請?zhí)顚懹覀?cè)的驗證碼" />
                                    <img src="images/passcode.jpg" alt="" width="100" height="32"
                                        class="passcode" style="height:43px;cursor:pointer;"
                                        onclick="this.src=this.src+'?'">

                                </div>
                            </div>
                        </div>
                        <div style="padding:30px;">
                            <input type="submit"
                                class="button button-block bg-main text-big input-big"
                                value="登錄">
                        </div>
                        <div style="font-size:15px;position: relative;left:350px ;top:-20px ;"><a href="reg.jsp">注冊</a></div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>
jsp實現(xiàn)的登錄界面
  • UserServlet
package com.zlw.servlet;

import java.io.IOException;

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

import com.zlw.pojo.User;
import com.zlw.service.UserService;
import com.zlw.service.impl.UserServiceImpl;
/**
 *  用戶登錄:
 *  1扩灯、  用戶點擊登錄發(fā)送請求到UserServlet
 *      tomcat服務器接收到請求后調(diào)用UserServlet中service方法進行請求處理改执,并將封存了相關(guān)數(shù)據(jù)的
 *      request對象和response對象作為實參傳遞給service方法
 *  2浪蹂、在UserServlet中調(diào)用業(yè)務層方法進行登錄業(yè)務處理
 *  3毡泻、在業(yè)務層方法中調(diào)用Dao層方法完成數(shù)據(jù)庫操作
 *  4访锻、完成功能跳轉(zhuǎn)
 *  MVC分層開發(fā):
 *      M:model  service層和dao層和實體類層
 *      V:view    視圖層 jsp頁面等
 *      C:controller 控制層  servlet
 * @author zhang
 *
 */
public class UserServlet extends HttpServlet {
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設置請求編碼格式
        request.setCharacterEncoding("utf-8");
        //設置響應編碼格式
        response.setContentType("text/html;charset=utf-8");
        //獲取請求信息
        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        //處理請求信息
//      System.out.println(uname+":"+pwd);
        //處理業(yè)務邏輯層
        UserService us = new UserServiceImpl();
        User user=us.getUserInfoService(uname, pwd);
//      System.out.println(user);
        //處理響應結(jié)果
            //創(chuàng)建session對象
        HttpSession hs = request.getSession();
        if (user!=null) {//登錄成功
            //將用戶信息存儲在session中
            hs.setAttribute("user", user);
            //重定向到main.jsp
            response.sendRedirect("/project/main.jsp");
        } else {//登錄失敗
            hs.setAttribute("flag", "loginFalse");
            //重定向到login.jsp
            response.sendRedirect("/project/login.jsp");
        }
        
    }
}
  • JDBC數(shù)據(jù)庫連接:
    (1)Dao
package com.zlw.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.zlw.dao.UserDao;
import com.zlw.pojo.User;
import com.zlw.util.DBUtil;

public class UserDaoImpl implements UserDao{
    /**
     * 查詢用戶信息
     */
    @Override
    public User getUserInfoDao(String uname, String pwd) {
        //聲明jdbc變量
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        //聲明變量
        User us= null;
        try {
            //創(chuàng)建連接
            conn = DBUtil.getConnection();
            //創(chuàng)建sql語句
            String sql="select * from t_user where uname=? and pwd=?";
            //創(chuàng)建slq命令對象
            ps=conn.prepareStatement(sql);
            //給占位符賦值
            ps.setString(1, uname);
            ps.setString(2, pwd);
            //執(zhí)行sql命令
            rs = ps.executeQuery();
            //遍歷rs
            while(rs.next()){
                //給變量賦值
                us=new User();
                us.setUid(rs.getInt("uid"));
                us.setUname(rs.getString("uname"));
                us.setPwd(rs.getString("pwd"));
                us.setSex(rs.getString("sex"));
                us.setAge(rs.getInt("age"));
                us.setBirthday(rs.getString("birthday"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            DBUtil.closeAll(rs, ps, conn);  
        }
        return us;
    }
    /**
     * 用戶注冊
     */
    @Override
    public int regUserInfoDao(String uname, String pwd, String sex, int age, String birthday) {
        //創(chuàng)建sql語句
        String sql = "insert into t_user values(default,?,?,?,?,?)";
        return DBUtil.executeDML(sql, uname,pwd,sex,age,birthday);
    }
}

(2)pojo:

package com.zlw.pojo;

public class User {
    private int uid;
    private String uname;
    private String pwd;
    private String sex;
    private int age;
    private String birthday;

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

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

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User [uid=" + uid + ", uname=" + uname + ", pwd=" + pwd + ", sex=" + sex + ", age=" + age
                + ", birthday=" + birthday + "]";
    }
}

(3)Service業(yè)務處理:

package com.zlw.service.impl;

import com.zlw.dao.UserDao;
import com.zlw.dao.impl.UserDaoImpl;
import com.zlw.pojo.User;
import com.zlw.service.UserService;

public class UserServiceImpl implements UserService {
    //創(chuàng)建Dao層對象
    UserDao ud= new UserDaoImpl();
    //用戶登錄
    @Override
    public User getUserInfoService(String uname, String pwd) {
        //處理登錄業(yè)務
        return ud.getUserInfoDao(uname,pwd);
    }
    //用戶注冊
    @Override
    public int regUserInfoService(String uname, String pwd, String sex, int age, String birthday) {
        //處理注冊業(yè)務
        return  ud.regUserInfoDao(uname,pwd,sex,age,birthday);
    }
}

(4)Util工具類:

package com.zlw.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBUtil {
    //聲明全局變量記錄jdbc參數(shù)
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    //使用靜態(tài)代碼塊垢揩,在類加載時即完成對屬性文件的讀取
    static{
        //動態(tài)獲取屬性配置文件的流對象
        InputStream in=DBUtil.class.getResourceAsStream("/jdbc.properties");
        //創(chuàng)建Properties對象
        Properties p=new Properties();
        //加載
        try {
            p.load(in);//會將屬性配置文件的所有數(shù)據(jù)存儲到Properties對象中
            //將讀取的jdbc參數(shù)賦值給全局變量
            driver=p.getProperty("driver");
            url=p.getProperty("url");
            username=p.getProperty("username");
            password=p.getProperty("password");
            //加載驅(qū)動
            Class.forName(driver);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //創(chuàng)建連接對象并返回
    public static Connection getConnection(){
        Connection conn=null;
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return conn;
    }
    //關(guān)閉資源
    public static void closeAll(ResultSet rs,Statement stmt,Connection conn){
        try {
            if(rs!=null){
                rs.close();
            }
        } catch (SQLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            stmt.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }
    //封裝增加刪除修改的通用工具方法
    /**
     * @param sql SQL語句
     * @param objs  SQL語句占位符實參沉唠,如果沒有參數(shù)則傳入null
     * @return 返回增刪改的結(jié)果疆虚,類型為int
     */
    public static int executeDML(String sql,Object...objs){
        // 聲明jdbc變量
                Connection conn = null;
                PreparedStatement ps = null;
                int i = -1;
                try {
                    // 獲取連接對象
                    conn = DBUtil.getConnection();
                    // 開啟事務管理
                    conn.setAutoCommit(false);
                    // 創(chuàng)建SQL命令對象
                    ps = conn.prepareStatement(sql);
                    // 給占位符賦值
                    if(objs!=null){
                        for(int j=0;j<objs.length;j++){
                            ps.setObject(j+1,objs[j]);
                        }
                    }
                    // 執(zhí)行SQL
                    i = ps.executeUpdate();
                    conn.commit();
                } catch (Exception e) {
                    try {
                        conn.rollback();
                    } catch (SQLException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    e.printStackTrace();
                } finally {
                    DBUtil.closeAll(null, ps, conn);
                }
                return i;
    }
}

(5)jdbc.properties:配置文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/project
username=root
password=root
  • 登錄成功的頁面會跳轉(zhuǎn)到mian.jsp:
    登錄成功
  • 登錄失敗會跳轉(zhuǎn)到登錄頁面:
    登錄失敗

2.退出登錄:

  • OutServlet:
package com.zlw.servlet;

import java.io.IOException;

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

public class OutServlet extends HttpServlet {
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設置請求編碼格式
        request.setCharacterEncoding("utf-8");
        //設置響應的編碼格式
        response.setContentType("text/html;charset=utf-8");
        //獲取請求信息
        //處理請求信息
        //獲取session對象
        HttpSession hs = request.getSession();
        //銷毀session
        hs.invalidate();
        //相應處理結(jié)果
            //重定向
            response.sendRedirect("/project/login.jsp");
        
    }
}

3.用戶注冊

package com.zlw.servlet;

import java.io.IOException;

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

import com.zlw.service.UserService;
import com.zlw.service.impl.UserServiceImpl;

public class RegServlet extends HttpServlet {
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設置請求編碼格式
        request.setCharacterEncoding("utf-8");
        //設置響應編碼格式
        response.setContentType("text/html;charset=utf-8");
        //獲取請求信息
        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        String sex = request.getParameter("sex");
        int age = Integer.parseInt(request.getParameter("age"));
        String birthday = request.getParameter("birthday");
        //處理請求信息
            //獲取業(yè)務層對象
            UserService us= new UserServiceImpl();
            int i = us.regUserInfoService(uname, pwd, sex, age, birthday);
            
        //處理響應結(jié)果
            //獲得Session對象
            HttpSession hs = request.getSession();
        if(i>0){//注冊成功
            //給注冊成功添加標記到session中
            hs.setAttribute("flag","regSuccess");
            //重定向到登錄頁面
            response.sendRedirect("/project/login.jsp");
        }else{//注冊失敗
            //重定向到注冊頁面
            response.sendRedirect("/project/reg.jsp");
        }
    }

}
  • jsp頁面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
    content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="renderer" content="webkit">
<title></title>
<link rel="stylesheet" href="css/pintuer.css">
<link rel="stylesheet" href="css/admin.css">
<script src="js/jquery.js"></script>
<script src="js/pintuer.js"></script>
<!-- 聲明js代碼域 -->
<script type="text/javascript">
    $(function(){
        //給男添加單機按鈕
        $("#man").click(function(){
            //給男的span添加選擇樣式
            $("#manSpan").addClass("icon-check");
            //將女的選擇狀態(tài)去掉
            $("#womanSpan").removeClass("icon-check");
        //給女添加單機事件
        $("#woman").click(function(){
            //給女的span添加選擇樣式
            $("#womanSpan").addClass("icon-check");
            //將男的選擇狀態(tài)去掉
            $("#manSpan").removeClass("icon-check");
        })
            
        })
    })
</script>
</head>
<body>
    <div class="panel admin-panel">
        <div class="panel-head">
            <strong><span class="icon-key"></span> 會員注冊</strong>
        </div>
        <div class="body-content">
            <form method="post" class="form-x" action="reg">
                <div class="form-group"></div>
                <div class="form-group">
                    <div class="label">
                        <label for="sitename">用戶名:</label>
                    </div>
                    <div class="field">
                        <input type="text" class="input w50" id="uname" name="uname"
                            size="50" placeholder="請輸入用戶名" data-validate="required:請輸入用戶名" />
                    </div>
                </div>
                <div class="form-group">
                    <div class="label">
                        <label for="sitename">密碼:</label>
                    </div>
                    <div class="field">
                        <input type="password" class="input w50" name="pwd" size="50"
                            placeholder="請輸入新密碼"
                            data-validate="required:請輸入密碼,length#>=5:密碼不能小于5位" />
                    </div>
                </div>
                <div class="form-group">
                    <div class="label">
                        <label for="sitename">確認密碼:</label>
                    </div>
                    <div class="field">
                        <input type="password" class="input w50"
                            size="50" placeholder="請再次輸入密碼"
                            data-validate="required:請再次輸入密碼,repeat#pwd:兩次輸入的密碼不一致" />
                    </div>
                </div>
                
                <div class="form-group">
                    <div class="label">
                        <label for="sitename">年齡:</label>
                    </div>
                    <div class="field">
                        <input type="" class="input w50" id="age" name="age"
                            size="50" placeholder="請輸入年齡" data-validate="required:請輸入年齡,length#<=3:年齡不不合法""/>
                    </div>
                </div>
                <div class="form-group">
                    <div class="label">
                        <label for="sitename">出生日期:</label>
                    </div>
                    <div class="field">
                        <input type="date" class="input w50" id="birthday" name="birthday"
                            size="50" data-validate="required:請輸入出生日期" />
                    </div>
                </div>
                <!-- 性別 -->
                <div class="form-group">
                    <div class="label">
                        <label>性別:</label>
                    </div>
                    <div class="field">
                        <div class="button-group radio">

                            <label class="button active" > 
                            <span class="icon-check" id="manSpan"></span> <input name="sex" value="1" id="man"type="radio" checked="checked">男
                            </label> 
                            <label class="button active" >
                            <span class="" id="womanSpan"></span> <input name="sex" value="0" id="woman"type="radio">女 
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="label">
                            <label></label>
                        </div>
                        <div class="field">
                            <button class="button bg-main icon-check-square-o" type="submit">
                                提交</button>
                        </div>
                    </div>
            </form>
        </div>
    </div>
</body>
</html>
  • 實現(xiàn)效果
    注冊頁面

    注冊成功

三、實現(xiàn)動態(tài)調(diào)用請求處理

1.實現(xiàn)動態(tài)調(diào)用請求:

  • 問題:

現(xiàn)在我們一個請求或者一個獨立的業(yè)務邏輯都單獨進行一個Servlet的創(chuàng)建進行請求處理满葛。但是一個網(wǎng)站的功能是非常的多径簿,如果每個都創(chuàng)建單獨的Servlet進行處理,這樣造成Servlet過多嘀韧。造成資源浪費篇亭。

  • 解決:

服務器在接收到瀏覽器發(fā)送的請求后,會調(diào)用對應的Servlet進行請求處理锄贷。
然后調(diào)用Servlet中的Service方法進行處理译蒂。
我們將不同功能的處理封裝成對應的方法。
在service方法中調(diào)用其對應的功能處理方法進行請求處理谊却。
這樣Servlet我們只需要一個柔昼。
使用反射。

  • 注意:

請求中需要附帶要執(zhí)行的方法名稱炎辨。

package com.zlw.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
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 javax.servlet.http.HttpSession;

import com.zlw.pojo.User;
import com.zlw.service.UserService;
import com.zlw.service.impl.UserServiceImpl;
/**
 * servlet創(chuàng)建一個捕透,在service方法中動態(tài)的調(diào)用請求處理方法。
 * 注意:
 *  請求中需要附帶要調(diào)用的方法名
 * @author zhang
 *
 */
public class DataServlet extends BaseServlet {
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設置請求編碼格式
        request.setCharacterEncoding("utf-8");
        //設置響應編碼格式
        response.setContentType("text/html;charset=utf-8");
        //獲取請求信息
        String methodName = request.getParameter("method");
        System.out.println("DataServlet.service(當前請求的方法名:)"+methodName);
        //調(diào)用方法處理請求(根據(jù)動態(tài)方法名調(diào)用方法---->反射)
        try {
            //反射獲取方法所在的類的對象
            Class cs = this.getClass();
            //反射獲取要被調(diào)用的方法對象
            Method m = cs.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
            //反射執(zhí)行方法
            m.invoke(this,request,response);
        } catch (NoSuchMethodException | SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    public void userLogin(HttpServletRequest request, HttpServletResponse response) throws IOException{
        //獲取請求信息
                String uname = request.getParameter("uname");
                String pwd = request.getParameter("pwd");
                //處理請求信息
//              System.out.println(uname+":"+pwd);
                //處理業(yè)務邏輯層
                UserService us = new UserServiceImpl();
                User user=us.getUserInfoService(uname, pwd);
//              System.out.println(user);
                //處理響應結(jié)果
                    //創(chuàng)建session對象
                HttpSession hs = request.getSession();
                if (user!=null) {//登錄成功
                    //將用戶信息存儲在session中
                    hs.setAttribute("user", user);
                    //重定向到main.jsp
                    response.sendRedirect("/project2/main.jsp");
                } else {//登錄失敗
                    hs.setAttribute("flag", "loginFalse");
                    //重定向到login.jsp
                    response.sendRedirect("/project2/login.jsp");
                }
                
    }
    public void userOut(HttpServletRequest request, HttpServletResponse response) throws IOException{
        //處理請求信息
                //獲取session對象
                HttpSession hs = request.getSession();
                //銷毀session
                hs.invalidate();
                //相應處理結(jié)果
                    //重定向
                    response.sendRedirect("/project2/login.jsp");
                
    }
    public void userReg(HttpServletRequest request, HttpServletResponse response) throws IOException{
        //獲取請求信息
                String uname = request.getParameter("uname");
                String pwd = request.getParameter("pwd");
                String sex = request.getParameter("sex");
                int age = Integer.parseInt(request.getParameter("age"));
                String birthday = request.getParameter("birthday");
                //處理請求信息
                    //獲取業(yè)務層對象
                    UserService us= new UserServiceImpl();
                    int i = us.regUserInfoService(uname, pwd, sex, age, birthday);
                    
                //處理響應結(jié)果
                    //獲得Session對象
                    HttpSession hs = request.getSession();
                if(i>0){//注冊成功
                    //給注冊成功添加標記到session中
                    hs.setAttribute("flag","regSuccess");
                    //重定向到登錄頁面
                    response.sendRedirect("/project2/login.jsp");
                }else{//注冊失敗
                    //重定向到注冊頁面
                    response.sendRedirect("/project2/reg.jsp");
                }
    }
}

2.抽取BaseServlet類:

將Servlet中的Service方法抽取出來。

package com.zlw.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;

public class BaseServlet extends HttpServlet{
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設置請求編碼格式
                request.setCharacterEncoding("utf-8");
                //設置響應編碼格式
                response.setContentType("text/html;charset=utf-8");
                //獲取請求信息
                String methodName = request.getParameter("method");
                System.out.println("DataServlet.service(當前請求的方法名:)"+methodName);
                //調(diào)用方法處理請求(根據(jù)動態(tài)方法名調(diào)用方法---->反射)
                try {
                    //反射獲取方法所在的類的對象
                    Class cs = this.getClass();
                    //反射獲取要被調(diào)用的方法對象
                    Method m = cs.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
                    //反射執(zhí)行方法
                    m.invoke(this,request,response);
                } catch (Exception e) {
                    e.printStackTrace();
                } 
    }
}
  • Servlet
package com.zlw.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
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 javax.servlet.http.HttpSession;

import com.zlw.pojo.User;
import com.zlw.service.UserService;
import com.zlw.service.impl.UserServiceImpl;
/**
 * servlet創(chuàng)建一個乙嘀,在service方法中動態(tài)的調(diào)用請求處理方法末购。
 * 注意:
 *  請求中需要附帶要調(diào)用的方法名
 * @author zhang
 *
 */
public class DataServlet extends BaseServlet {
public void userLogin(HttpServletRequest request, HttpServletResponse response) throws IOException{
        //獲取請求信息
                String uname = request.getParameter("uname");
                String pwd = request.getParameter("pwd");
                //處理請求信息
//              System.out.println(uname+":"+pwd);
                //處理業(yè)務邏輯層
                UserService us = new UserServiceImpl();
                User user=us.getUserInfoService(uname, pwd);
//              System.out.println(user);
                //處理響應結(jié)果
                    //創(chuàng)建session對象
                HttpSession hs = request.getSession();
                if (user!=null) {//登錄成功
                    //將用戶信息存儲在session中
                    hs.setAttribute("user", user);
                    //重定向到main.jsp
                    response.sendRedirect("/project2/main.jsp");
                } else {//登錄失敗
                    hs.setAttribute("flag", "loginFalse");
                    //重定向到login.jsp
                    response.sendRedirect("/project2/login.jsp");
                }
                
    }
    public void userOut(HttpServletRequest request, HttpServletResponse response) throws IOException{
        //處理請求信息
                //獲取session對象
                HttpSession hs = request.getSession();
                //銷毀session
                hs.invalidate();
                //相應處理結(jié)果
                    //重定向
                    response.sendRedirect("/project2/login.jsp");
                
    }
    public void userReg(HttpServletRequest request, HttpServletResponse response) throws IOException{
        //獲取請求信息
                String uname = request.getParameter("uname");
                String pwd = request.getParameter("pwd");
                String sex = request.getParameter("sex");
                int age = Integer.parseInt(request.getParameter("age"));
                String birthday = request.getParameter("birthday");
                //處理請求信息
                    //獲取業(yè)務層對象
                    UserService us= new UserServiceImpl();
                    int i = us.regUserInfoService(uname, pwd, sex, age, birthday);
                    
                //處理響應結(jié)果
                    //獲得Session對象
                    HttpSession hs = request.getSession();
                if(i>0){//注冊成功
                    //給注冊成功添加標記到session中
                    hs.setAttribute("flag","regSuccess");
                    //重定向到登錄頁面
                    response.sendRedirect("/project2/login.jsp");
                }else{//注冊失敗
                    //重定向到注冊頁面
                    response.sendRedirect("/project2/reg.jsp");
                }
    }
}

四、總結(jié)和項目缺陷

1.套用模板進行頁面快速構(gòu)建

(1)在自己的項目中創(chuàng)建jsp文件虎谢。
(2)然后將模板中的前端相關(guān)代碼賦值到自己的jsp文件中盟榴。
(3)將靜態(tài)資源復制到webRoot下。

2.MCV的開發(fā)模式:

M:model????service dao pojo
V:view????jsp css html
C:????controller servlet

3.Servlet+jsp+jdbc的功能開發(fā)流程

1.瀏覽器發(fā)起頁面請求直接給jsp
2.瀏覽器發(fā)起功能請求給Servlet婴噩,Servlet調(diào)用service方法擎场,service進行業(yè)務邏輯處理,service調(diào)用dao几莽,dao層進行數(shù)據(jù)庫操作(jdbc)顶籽,dao層將處理結(jié)果返回給service,service再將結(jié)果返回給Servlet银觅,(或者繼續(xù)請求轉(zhuǎn)發(fā)或者重定向)請求轉(zhuǎn)發(fā)或者重定向給jsp礼饱,jsp作出頁面響應。

4.request和session作用域的使用

request:請求轉(zhuǎn)發(fā)的數(shù)據(jù)流轉(zhuǎn)的載體究驴。
session:重定向的數(shù)據(jù)流轉(zhuǎn)的載體(但是session可以解決同一個用戶的不同請求的數(shù)據(jù)共享問題)镊绪。

5.瀏覽器發(fā)起請求到服務器請求發(fā)起的方式

非ajax請求:
form表單提交:action數(shù)據(jù)提交地址,method:數(shù)據(jù)提交方式洒忧;
超鏈接標簽:href為數(shù)據(jù)提交地址蝴韭,可以直接使用“?”拼接請求數(shù)據(jù)熙侍,類似于form表單的get方式榄鉴。
js中的Windows.location.herf:為數(shù)據(jù)提交地址,可以直接使用“蛉抓?”拼接請求數(shù)據(jù)庆尘,類似于form表單的get方式。

  • 注意:

使用以上請求方式發(fā)起的請求巷送,瀏覽器在接收到相應內(nèi)容后驶忌,會將原有內(nèi)容覆蓋,顯示響應結(jié)果笑跛。

6.BaseServlet的抽取和使用:

反射機制
抽象類
不希望該Servlet類被調(diào)用和響應付魔。

7.項目缺陷:

(1)在jsp中獲取從Servlet流轉(zhuǎn)過來的數(shù)據(jù)特別麻煩;
(2)在jsp頁面中使用java代碼塊進行邏輯處理書寫和閱讀極不方便飞蹂;
(3)使用session進行數(shù)據(jù)流轉(zhuǎn)是很方便的几苍,但是session失效了,所有依賴session實現(xiàn)的功能都會出問題陈哑。
(4)響應結(jié)果都是覆蓋原有內(nèi)容顯示給用戶的

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末妻坝,一起剝皮案震驚了整個濱河市妖胀,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌惠勒,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,039評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件爬坑,死亡現(xiàn)場離奇詭異纠屋,居然都是意外死亡,警方通過查閱死者的電腦和手機盾计,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評論 3 395
  • 文/潘曉璐 我一進店門售担,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人署辉,你說我怎么就攤上這事族铆。” “怎么了哭尝?”我有些...
    開封第一講書人閱讀 165,417評論 0 356
  • 文/不壞的土叔 我叫張陵哥攘,是天一觀的道長。 經(jīng)常有香客問我材鹦,道長逝淹,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,868評論 1 295
  • 正文 為了忘掉前任桶唐,我火速辦了婚禮栅葡,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘尤泽。我一直安慰自己欣簇,他們只是感情好,可當我...
    茶點故事閱讀 67,892評論 6 392
  • 文/花漫 我一把揭開白布坯约。 她就那樣靜靜地躺著熊咽,像睡著了一般。 火紅的嫁衣襯著肌膚如雪闹丐。 梳的紋絲不亂的頭發(fā)上网棍,一...
    開封第一講書人閱讀 51,692評論 1 305
  • 那天,我揣著相機與錄音妇智,去河邊找鬼滥玷。 笑死,一個胖子當著我的面吹牛巍棱,可吹牛的內(nèi)容都是我干的惑畴。 我是一名探鬼主播,決...
    沈念sama閱讀 40,416評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼航徙,長吁一口氣:“原來是場噩夢啊……” “哼如贷!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,326評論 0 276
  • 序言:老撾萬榮一對情侶失蹤杠袱,失蹤者是張志新(化名)和其女友劉穎尚猿,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體楣富,經(jīng)...
    沈念sama閱讀 45,782評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡凿掂,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,957評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了纹蝴。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片庄萎。...
    茶點故事閱讀 40,102評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖塘安,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情兼犯,我是刑警寧澤切黔,帶...
    沈念sama閱讀 35,790評論 5 346
  • 正文 年R本政府宣布锉罐,位于F島的核電站,受9級特大地震影響绕娘,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜侨舆,卻給世界環(huán)境...
    茶點故事閱讀 41,442評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望绢陌。 院中可真熱鬧挨下,春花似錦脐湾、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至瓶竭,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間智哀,已是汗流浹背荧恍。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人授艰。 一個月前我還...
    沈念sama閱讀 48,332評論 3 373
  • 正文 我出身青樓世落,卻偏偏與公主長得像屉佳,于是被迫代替她去往敵國和親谷朝。 傳聞我的和親對象是個殘疾皇子武花,可洞房花燭夜當晚...
    茶點故事閱讀 45,044評論 2 355

推薦閱讀更多精彩內(nèi)容

  • IOC 控制反轉(zhuǎn)容器控制程序?qū)ο笾g的關(guān)系体箕,而不是傳統(tǒng)實現(xiàn)中,有程序代碼之間控制跃须,又名依賴注入娃兽。All 類的創(chuàng)建,...
    irckwk1閱讀 945評論 0 0
  • 一. Java基礎部分.................................................
    wy_sure閱讀 3,811評論 0 11
  • JSP總結(jié)(經(jīng)典) day1 JSP 定義: 1)Java Server Page, Java EE 組件,本...
    java日記閱讀 3,449評論 0 13
  • 1.abstract class 和interface 有什么區(qū)別? 抽象類可以有構(gòu)造方法 接口不行 抽象類可以有...
    sunnysans閱讀 856評論 0 1
  • 今天主要學習了教材對跆拳道教育的影響复旬。這主要是從“三個目的驹碍,道館角度,教練的角度”來講的怔球。三個目的是壯壯浮还、朗...
    Kim_34cd閱讀 46評論 0 0