码迷,mamicode.com
首页 > 其他好文 > 详细

对于servlet初步理解

时间:2016-05-07 07:23:52      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

Servlet在MVC框架中经常担当控制器(Controller)的角色,其作用类似于调度员,下面我们就根据一个简单JavaEE的示例来理解Servlet的机制和原理.

技术分享
树结构如上,其中
login.jsp作为测试用户登录页面.
welcome.jsp作为登录成功页面
DaDao.java作为数据库操作类
LoginServlet.java就是我们所说的Servlet类

我们来看具体内容:
login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; UTF-8">
<title>连接数据库范例</title>
</head>
<body>
    <span style="color: blue; font-weight: bold;"> <%
    if (request.getAttribute("err") != null) {
        out.println(request.getAttribute("err") + "<br/>");
    }
 %>
    </span> 请输入用户名密码:
    <form id="login" method="post" action="login">
        用户名: <input type="text" name="username"><br /> 密码:<input
            type="password" name="password"><br /> <input type="submit"
            value="登录"><br />
    </form>
</body>
</html>

以上页面只负责传递两个参数,一个是用户名,另一个是用户密码,将参数传递给LoginServlet的实例中,再通过验证数据库进行结果判断,然后Servlet将结果视图反馈给用户.
welcome.jsp

<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title> 欢迎页面 </title>
    <meta name="website" content="http://www.crazyit.org" />
</head>
<body>
<h3>欢迎登录</h3>
<%=session.getAttribute("name")%>,欢迎登录!
</body>
</html>

此页面是用户密码验证成功后返回的视图.

                  DbDao.java
package glq;

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

public class DbDao {

    private Connection conn;
    private String driver;
    private String url;
    private String username;
    private String password;
    public DbDao() {
    }
    public DbDao(String driver, String url, String username, String password) {
        this.driver = driver;
        this.url = url;
        this.username = username;
        this.password = password;
    }
    public String getDriver() {
        return driver;
    }
    public void setDriver(String driver) {
        this.driver = driver;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    public Connection getConnection() throws Exception {
        if(conn==null){
            Class.forName(this.driver);
            conn=DriverManager.getConnection(url, username, password);
        }
        return conn;
    }

    public boolean insert(String sql,Object... args) throws Exception, Throwable{
        PreparedStatement ps=getConnection().prepareStatement(sql);
        for(int i=0;i<args.length;i++){
            ps.setObject(i+1, args[i]);
        }
        if(ps.executeUpdate()!=1){
            return false;
        }
        return true;
    }

    public ResultSet query(String sql,Object... args) throws Exception{
        PreparedStatement ps=getConnection().prepareStatement(sql);
        for(int i=0;i<args.length;i++){
            ps.setObject(i+1, args[i]);
        }
        return ps.executeQuery();
    }

    public void modify(String sql,Object... args) throws Exception{
        PreparedStatement ps=getConnection().prepareStatement(sql);
        for(int i=0;i<args.length;i++){
            ps.setObject(i+1, args[i]);
        }
        ps.executeUpdate();
        ps.close();
    }
    public void closeConn() throws Exception{
        if(conn!=null &&!conn.isClosed()){
            conn.close();
        }
    }
}

DaDao类对数据库操作进行了简单的封装,插入了连接数据库,查询记录,修改记录,插曲记录等方法.
                  LoginServlet.java
package glq;

import java.io.IOException;
import java.sql.ResultSet;

import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;
@WebServlet(name="login" ,urlPatterns={"/login"})
public class LoginServlet extends HttpServlet {

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

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String errMsg = "";
        RequestDispatcher rd;
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        try {
            //创建数据库构造函数
            //注意,连接时要在数据库中创建名为servlet的数据库
            DbDao dd = new DbDao("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/servlet", "root", "123456");
            //执行查询方法
            //注意,要在servlet数据库中添加user_inf表,并在表中添加两个属//性:name,pass
            ResultSet rs = dd.query("select pass from user_inf where name=?", username);
            //如果存在该用户
            if (rs.next()) {
            //判定用户密码是否相同
                if (rs.getString("pass").equals(password)) {
                    //获得session
                    HttpSession session = req.getSession();
                    //注册name值为username
                    session.setAttribute("name", username);
                    //将参数和页面转向welcome.jsp
                    rd = req.getRequestDispatcher("/welcome.jsp");
                    rd.forward(req, res);
                } else {
                //如果密码匹配失败
                    errMsg += "密码不对,请重新输入";
                }
            } else {
                //如果没找到用户
                errMsg += "用户不存在";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //当错误信息存在时,将错误信息errMsg作为参数传递给request中的err变//量,使其在登录页面显示,并因为登录失败跳转至登录页面
        if (errMsg != null && !errMsg.equals("")) {
            rd = req.getRequestDispatcher("/login.jsp");
            req.setAttribute("err", errMsg);
            rd.forward(req, res);
        }

    }
}

在测试时,需要在WEB-INF的lib文件中加入mysql-connector-java-5.1.38-bin.jar包,此包为数据库工具包.

至于tomcat的构建,以及web项目的建立,需要自行检索.

对于servlet初步理解

标签:

原文地址:http://blog.csdn.net/wycmglq/article/details/51330653

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!