Servlet拾遗

每一个Servlet实际上都可以配置多个名称,只需要增加对应的<servlet-mapping>元素即可。
Servlet拾遗_第1张图片

在容器启动时就自动为Servlet初始化

<load-on-startup>1</load-on-startup>

JSP内置对象config对象,可以读取web.xml中配置的初始化参数,此对象实际上是ServletConfig接口的实例。

 <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.test.servlet.HelloServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <init-param>
        <param-name>ref</param-name>
        <param-value>www.baidu.com</param-value>
    </init-param>
  </servlet>
    @Override
    public void init(ServletConfig config) throws ServletException {
        String initParam = config.getInitParameter("ref");
        System.out.println(initParam);
    }

取得其他内置对象
取得HttpSession实例

取得ServletContext实例
application内置对象是ServletContext接口的实例,表示的是Servlet上下文。
取得ServletContext实例

resp.sendRedirect()是客户端跳转,跳转后的地址栏是会改变的。跳转后只能接受session属性范围的内容,而request属性范围的内容无法接收到。

服务器端跳转
需要依靠RequestDispatcher接口完成

Web开发模式:Mode1与Mode2

Mode1

Mode1就是指在开发中将显示层、控制层、数据层的操作统一交给JSP或Java进行处理。
Mode1

Mode1的结构适合小型程序开发,或者是复杂度较低的程序。

Mode2:Mode-View-Controller

在Mode2中所有的开发都是以Servlet为主体展开的,由Servlet接收所有的客户端请求,然后根据请求调用响应的JavaBean,并将所有的显示结果交给JSP完成,也就是俗称的MVC设计模式。

  • 显示层(View):主要负责接收Servlet传递的内容,并且调用JavaBean,将内容显示给用户
  • 控制层(Controller):主要负责所有的用户请求参数,判断请求参数是否合法,根据请求的类型调用Javabean执行操作并将最终的处理结果交由显示层进行显示。
  • 模型层(Model):完成一个独立的业务操作组件,一般都是以JavaBean或者EJB的形式进行定义的。

例子

登录程序MVC设计模式

MVC登录程序清单
Servlet拾遗_第2张图片

定义VO类——User.java

package com.wz.mvc.vo;

public class User {

    private String userid;
    private String name;
    private String password;


    public String getUserid() {
        return userid;
    }
    public void setUserid(String userid) {
        this.userid = userid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }


}

定义数据库操作类——DatabaseConnection.java

package com.wz.mvc.dbc;

import java.sql.Connection;
import java.sql.DriverManager;

public class DatabaseConnection {

    private static final String DBDRIVER = "com.mysql.jdbc.Driver";
    private static final String DBURL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8";
    private static final String DBUSER = "root";
    private static final String DBPASS = "";
    private Connection conn = null;

    public DatabaseConnection() throws Exception {
        try {
            Class.forName(DBDRIVER);
            this.conn  =DriverManager.getConnection(DBURL,DBUSER, DBPASS);
        } catch (Exception e) {
            throw e;
        }

    }

    public Connection getConnection() {//取得数据库连接
        return this.conn;
    }

    public void close() throws Exception{//数据库关闭操作
        if(this.conn != null){
            try {
                this.conn.close();
            } catch (Exception e) {
                throw e;
            }
        }
    }


}

定义DAO接口——IUserDAO.java

package com.wz.mvc.dao;

import com.wz.mvc.vo.User;

public interface IUserDAO {

    /** * 用户登录验证 * @param user * @return * @throws Exception */
    public boolean findLogin(User user) throws Exception;

}

定义DAO实现类——UserDAOImpl.java类

package com.wz.mvc.dao.impl;

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

import com.wz.mvc.dao.IUserDAO;
import com.wz.mvc.vo.User;

public class UserDAOImpl implements IUserDAO {

    //定义数据库连接对象
    private Connection conn = null;
    //定义数据库操作对象
    private PreparedStatement pstmt = null;
    //设置数据库连接
    public UserDAOImpl(Connection conn) {
        this.conn = conn;
    }

    @Override
    public boolean findLogin(User user) throws Exception {
        boolean flag = false;
        try {

            String sql = "select name from user where userid = ? and password = ?";
            this.pstmt = this.conn.prepareStatement(sql);
            this.pstmt.setString(1, user.getUserid());
            this.pstmt.setString(2, user.getPassword());
            ResultSet rs = this.pstmt.executeQuery();
            if (rs.next()) {
                user.setName(rs.getString(1));//取得姓名
                flag  =true;
            }

        } catch (Exception e) {

            throw e;

        }finally {

            if (this.pstmt != null) {
                try{
                    this.pstmt.close();//关闭操作
                }catch(Exception e){
                    throw e;
                }
            }

        }

        return flag;
    }

}

定义DAO代理操作类——UserDAOProxy.java

package com.wz.mvc.dao.proxy;

import com.wz.mvc.dao.IUserDAO;
import com.wz.mvc.dao.impl.UserDAOImpl;
import com.wz.mvc.dbc.DatabaseConnection;
import com.wz.mvc.vo.User;

public class UserDAOProxy implements IUserDAO {

    //定义数据库连接
    private DatabaseConnection dbc = null;
    //定义DAO接口
    private IUserDAO dao = null;

    public UserDAOProxy() {
        try {
            this.dbc = new DatabaseConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.dao = new UserDAOImpl(this.dbc.getConnection());
    }

    @Override
    public boolean findLogin(User user) throws Exception {
        boolean flag = false;
        try {
            flag = this.dao.findLogin(user);//调用真实主题
        } catch (Exception e) {
            throw e;
        }finally {
            this.dbc.close();
        }

        return flag;
    }

}

定义工厂类,取得DAO实例——DAOFactory.java

package com.wz.mvc.factory;

import com.wz.mvc.dao.IUserDAO;
import com.wz.mvc.dao.proxy.UserDAOProxy;

public class DAOFactory {

    //取得DAO实例
    public static IUserDAO getIUserDAOInstance() {
        return new UserDAOProxy();
    }

}

定义Servlet——LoginServlet.java

package com.wz.mvc.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.jws.soap.SOAPBinding.Use;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wz.mvc.factory.DAOFactory;
import com.wz.mvc.vo.User;

public class LoginServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = "login.jsp";
        String userid = req.getParameter("userid");
        String userpass = req.getParameter("userpass");
        List<String> info = new ArrayList<String>();
        if(userid == null || "".equals(userid)){
            info.add("用户id不能为空!");
        }
        if(userpass == null || "".equals(userpass)){
            info.add("密码不能为空!");
        }
        if(info.size() == 0){
            User user = new User();
            user.setUserid(userid);
            user.setPassword(userpass);
            try {
                if(DAOFactory.getIUserDAOInstance().findLogin(user)){
                    //通过验证
                    info.add("用户登录成功,欢迎"+user.getName()+"光临!");
                }else{
                    info.add("用户登录失败,错误的用户名和密码");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            req.setAttribute("info", info);
            req.getRequestDispatcher(path).forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}

登录页

<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<% String basePath=request.getContextPath(); String path = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort() + basePath; %>
<!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; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript"> function validate(f){ if(!(/^\w{5, 15}$/.test(f.userid.value))){ alert("用户ID必须是5~15位"); f.userid.focus(); return false; } if(!(/^\w{5, 15}$/.test(f.userpass.value))){ alert("密码必须是5~15位"); f.userpass.focus(); return false; } return true; } </script>
</head>
<body>
    <h2>用户登录程序</h2>
    <% request.setCharacterEncoding("UTF-8"); %>
    <% List<String> info = (List<String>)request.getAttribute("info"); if(info != null){ Iterator<String> iter = info.iterator(); while(iter.hasNext()){ %>
                <h4><%=iter.next() %></h4>
    <% } } %>
    <form action="LoginServlet" method="post" >
        用户ID:<input type="text" name="userid"><br/>
        密码:<input type="password" name="userpass"><br/>
        <input type="submit" value="登录">
        <input type="reset" value="重置">
    </form>
</body>
</html>

配置web.xml文件

<servlet>
    <servlet-name>login</servlet-name>
    <servlet-class>com.wz.mvc.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>login</servlet-name>
    <url-pattern>/ch09/login/LoginServlet</url-pattern>
</servlet-mapping>

你可能感兴趣的:(servlet)