jsp第十三周作业

1.第十二周上机作业(邮件功能)的控制层代码改用为servlet实现。

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<html>
  <head>
    

  </head>
  
  <body>
  <script type="text/javascript">
  function loginButton(){
  if(loginFrom.uname.value==""){
  alert("用户名不能为空");
  return;
  }
  if(loginFrom.upwd.value==""){
  alert("密码不能为空");
  return;
  }
  loginFrom.submit();
  }
  </script>
  <form action="dologin" name="loginFrom" method="post">
用户名:<input type="text" name="uname"/><br>
密码:<input type="password" name="upwd"/><br>
<input type="button" value="登录" onclick="loginButton()"/><br>
<a href="zc.jsp">注册</a>
</form>

  </body>
</html>
<%@page import="com.ff.entity.email"%>
<%@page import="com.ff.dao.emailDao"%>

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<html>
<head>
</head>

<body>
    <%
        request.setCharacterEncoding("utf-8");
        String uname = (String)session.getAttribute("uname");
        emailDao ed=new emailDao();
        List<email> list=ed.getMailByReceiver(uname);
    %>
    欢迎你,<%=uname%><br><a href="write.jsp">写邮件</a>

    <table width="500px" style="border: 1px solid pink;">
        <tr>
            <td>发件人</td>
            <td>主题</td>
            <td>状态</td>
            <td>时间</td>
            <td>操作</td>
            <td>操作</td>
        </tr>
        <%
                if (list.size() == 0) {
                out.print("还没有人给您写文件哦!!!");
                } else {
                for(int i=0;i<list.size();i++){
            %>
        <tr>
            <td>
                <%
                    out.print(list.get(i).getAddress());
                %>
            </td>
            <td>
                <a href="detail.jsp?id=<%=list.get(i). getId()%>"><%
                    out.print(list.get(i).getTitle());
                %>
                </a>
            </td>
            <td>
                <%
                    if (list.get(i).getState() ==0){
                            out.print("<img src='unread.png'></img>");
                        } else {
                            out.print("<img src='read.png'/>");
                        }
                %>
            </td>
            <td><%out.print(list.get(i).getTime()); %></td>
            <td><a href="write.jsp?address=<%=list.get(i).getAddress()%>">回复</a></td>
            <td><a href="del.jsp?id=<%=list.get(i).getId()%>">删除</a></td>
        </tr>
        <%}}%>
    </table>


</body>
</html>
<%@page import="com.ff.dao.emailDao"%>
<%@page import="com.ff.entity.email"%>
<%@page import="com.ff.dao.usersDao"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<html>
<head>


</head>

<body>
<form action="dowrite" method="post">
收件人:<input type="text" name="receiver" value="<%=request.getParameter("address")%>"/><br>
主题:<input type="text" name="title"/><br>
内容:<br><textarea rows="6" cols="60" name="contents"></textarea><br>
<input type="submit" value="发送"/></form>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<html>
<head>


</head>

<body>
    <script type="text/javascript">
        function zcButton() {
            if (loginForm.uname.value == "") {
                alert("用户名不能为空");
                return;
            }
            if (loginForm.upwd.value == "") {
                alert("密码不能为空");
                return;
            }
            if (loginForm.rupwd.value == "") {
                alert("未确认密码");
                return;
            }
            loginForm.submit();
        }
    </script>
    <form action="dozc" name="loginForm" method="post">
        请输入用户名:<input type="text" name="uname" /><br> 
        请输入密码:<input type="password" name="upwd" /><br> 
        确认密码:<input type="password" name="rupwd" /><br>
         <input type="button" value="注册" onclick="zcButton()" /><br> 
         <a href="login.jsp">返回登录</a>

    </form>
</body>
</html>
<%@page import="com.ff.dao.emailDao"%>
<%@page import="com.ff.dao.usersDao"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<html>
<head>


</head>

<body>
    <%
        request.setCharacterEncoding("utf-8");
        int id=Integer.parseInt(request.getParameter("id"));
        emailDao ed=new emailDao();
        ed.deleEmail(id);
        response.sendRedirect("main.jsp");
    %>
</body>
</html>
package com.ff.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 javax.servlet.http.HttpSession;

import com.ff.dao.emailDao;
import com.ff.dao.usersDao;

public class dologin extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public dologin() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        HttpSession session=request .getSession();
        
          request.setCharacterEncoding("utf-8");
           String uname= request.getParameter("uname");
           String upwd=request.getParameter("upwd");
           usersDao ud=new usersDao();
           emailDao ed=new emailDao();
           if(ud.login(uname, upwd)){
           session.setAttribute("uname", uname);
           request.getRequestDispatcher("main.jsp").forward(request, response);
           }else{
           out.print("登录失败,5秒后跳回登录页");
           response.setHeader("refresh", "5;url=login.jsp");
           }
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}
package com.ff.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 com.ff.dao.usersDao;

public class dozc extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public dozc() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html,charset=utf-8");
        PrintWriter out = response.getWriter();
        
        request.setCharacterEncoding("utf-8");
        String uname = request.getParameter("uname");
        String upwd = request.getParameter("upwd");
        String rupwd = request.getParameter("rupwd");
        if (upwd.equals(rupwd)) {
            usersDao ud = new usersDao();
            ud.register(uname, upwd);
            out.print("注册成功5秒返回登录页!!!");
            response.setHeader("refresh", "5;url=login.jsp");
        } else {
            out.print("两次密码不一致,5秒后跳回注册页!!!");
            response.setHeader("refresh", "5;url=zc.jsp");
        }
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}
package com.ff.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 javax.servlet.http.HttpSession;

import com.ff.dao.emailDao;
import com.ff.entity.email;

public class dowrite extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public dowrite() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html,charset=utf-8");
        PrintWriter out = response.getWriter();
        HttpSession session=request .getSession();
        request.setCharacterEncoding("utf-8");
        String address=(String)session.getAttribute("uname");
        String receiver=request.getParameter("receiver");
        String title=request.getParameter("title");
        String contents=request.getParameter("contents");
        email  e=new email();
        e.setAddress(address);
        e.setReceiver(receiver);
        e.setTitle(title);
        e.setContents(contents);
        emailDao ed=new emailDao();
        ed.addEmail(e);
        out.print("发送成功,3秒后跳回首页!!!");
        response.setHeader("refresh", "3;url=main.jsp");
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}
package com.ff.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 com.ff.dao.emailDao;
import com.ff.entity.email;

public class detail extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public detail() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        
        String id=request.getParameter("id");
        int uid=Integer.parseInt(id);
        emailDao ed=new emailDao();
        ed.update(uid);
        email  e=ed.lookEmail(uid);
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}
package com.ff.dao;

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



public class usersDao extends BaseDao{
    //登录
    public boolean login(String uname,String upwd){
        boolean f=false;
        //建立连接
        Connection conn=getConnection();
        //编写SQL语句
        String sql="select * from users where uname=? and upwd=?";
        PreparedStatement ps;
        try{
            ps=conn.prepareStatement(sql);
            ps.setString(1,uname);
            ps.setString(2, upwd);
            ResultSet rs=ps.executeQuery();
            if(rs.next()){
                f=true;
                closeAll(conn, ps, rs);
            }
        }catch (Exception e) {
            // TODO: handle exception
        }
        return f;
    }
    //注册
    public void register(String uname,String upwd) {
        Connection conn=getConnection();
        PreparedStatement ps=null;
        try{
            String sql="insert into users(uname,upwd)value(?,?)";
            ps=conn.prepareStatement(sql);
            ps.setString(1, uname);
            ps.setString(2, upwd);
            ps.executeUpdate();
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            closeAll(conn, ps, null);
        }
        
        
    }
    

}
package com.ff.dao;

import java.awt.image.ConvolveOp;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.omg.CORBA.PUBLIC_MEMBER;

import com.ff.entity.email;

public class emailDao extends BaseDao {
    //根据用户名查看全部邮件
    public List<email> getMailByReceiver(String uname) {
        List<email> list=new ArrayList<email>();
        Connection con=getConnection();
        String sql="select * from email where receiver=?";
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            ps=con.prepareStatement(sql);
            ps.setString(1,uname);
            rs=ps.executeQuery();
            while(rs.next()){
                email e=new email();
                e.setId(rs.getInt(1));
                e.setAddress(rs.getString(2));
                e.setReceiver(rs.getString(3));
                e.setTitle(rs.getString(4));
                e.setContents(rs.getString(5));
                e.setTime(rs.getDate(6));
                e.setState(rs.getInt(7));
                list.add(e);
            }
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            closeAll(con, ps, rs);
        }
        return list;
        
    }
    //根据id删除邮件
    public void deleEmail(int id) {
        Connection con=getConnection();
        String sql="delete from email where id="+id;
        PreparedStatement ps=null;
        try{
            ps=con.prepareStatement(sql);
            ps.executeUpdate();
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            closeAll(con, ps, null);
        }
    }
    //回复邮件写邮件,邮件状态1为未读
    public void addEmail(email e) {
        Connection con=getConnection();
        String sql="insert into email(address,receiver,title,contents,time,state)values(?,?,?,?,?,1)";
        PreparedStatement ps=null;
        try{
            ps=con.prepareStatement(sql);
            ps.setString(1,e.getAddress());
            ps.setString(2, e.getReceiver());
            ps.setString(3, e.getTitle());
            ps.setString(4, e.getContents());
            ps.setDate(5, new java.sql.Date(new Date().getTime()));
            ps.executeUpdate();
        }catch (Exception exception) {
            // TODO: handle exception
            exception.printStackTrace();
        }finally{
            closeAll(con, ps, null);
        }
        
        
    }
    //改变邮件状态
    public void update(int id) {
        Connection con=getConnection();
        String sql="update email set state='1' where id=?";
        PreparedStatement ps=null;
    try{
        ps=con.prepareStatement(sql);
        ps.setInt(1, id);
        ps.executeUpdate();
    }catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }finally{
        closeAll(con, ps, null);
    }
    
    }
    
    //查看邮件
    public email lookEmail(int id) {
        Connection con=getConnection();
        String sql="select id,address,receiver,title,contents,time from email where id=?";
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            ps=con.prepareStatement(sql);
            ps.setInt(1, id);
            rs=ps.executeQuery();
            while(rs.next()){
                email e=new email();
                e.setId(rs.getInt(1));
                e.setAddress(rs.getString(2));
                e.setReceiver(rs.getString(3));
                e.setTitle(rs.getString(4));
                e.setContents(rs.getString(5));
                e.setTime(rs.getDate(6));
                return e;
            }
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            closeAll(con, ps, rs);
        }
        
        return null;
    }
}
package com.ff.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class BaseDao {


    //获取连接
    protected Connection getConnection(){
        Connection conn=null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                // 2.建立连接
                conn = DriverManager.getConnection(
                        "jdbc:mysql://localhost:3306/test", "root", "123456");
            } catch (Exception e) {
                e.printStackTrace();
            } 
            return conn;
    }    
    

    
    
    //关闭连接
    protected void closeAll(Connection con,PreparedStatement ps,ResultSet rs){        
    try {
        if(rs != null)
            rs.close();
        if(ps != null)
            ps.close();
        if(con != null)
            con.close();
        
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
}

 

posted @ 2022-05-28 20:53  聂芳芳  阅读(6)  评论(0编辑  收藏  举报