第十三次作业

上机作业(邮件功能)的控制层代码改用为servlet实现。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
  <head>
   
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  
  <body>
  <script type="text/javascript">
        function validate(){
            if(loginForm.uname.value==""){
                alert("账号不能为空!");
                return;
            }
            if(loginForm.upwd.value==""){
                alert("密码不能为空!");
                return;
            }
            loginForm.submit();
        }
    </script>
    <form action="logServlet">
                 用户名:<input type="text" name="uname" /> 密码:<input type="password"
            name="upwd" /><input type="submit" value="登录" />
    </form>
    <form action="register.jsp">
            <br> 没有账号需要注册?<input type="submit" value="注册" />
    </form>
  </body>
</html>

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="com.bk.dog.MailDao"%>
<%@page import="com.bk.e.Mail" %>
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  <body>
 <%
    MailDao md=new MailDao();
    String uname=(String)session.getAttribute("uname");
    List<Mail> list=md.getMailByReceiver(uname);
%>
      欢迎你 <% out.print(uname); %><a href="write.jsp">写邮件</a>
       <table height="20px" width="100%" align="center" border="1">
       <tr>
           <td>发件人</td>
           <td>主题</td>
           <td>状态</td>
           <td>时间</td>
           <td>回复</td>
           <td>删除</td>
       </tr>
       <%
    for(int i=0;i<list.size();i++){%>
    
    <tr>
    <td><%=list.get(i).getUsername()%></td>
    <td><a href="read.jsp?id=<%=list.get(i).getMsgid()%>"><%=list.get(i).getTitle()%></a></td>
    <td><%if(list.get(i).getState()==1){ 
    out.println("w");
    %>
    <%}else{ 
    out.println("y");
    %>
    <%} %>
    </td>
    <td><%=list.get(i).getMsg_create_date() %></td>
    <td><a href="write.jsp?reply=<%=list.get(i).getUsername()%>">回复</a></td>
    <td><a href="deltServlet?id=<%=list.get(i).getMsgid()%>">删除</a></td>
    </tr>
    <%} %>
   </table>
  </body>
</html>

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="com.bk.dog.MailDao" %>
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  <body>
    <%
        String Id = request.getParameter("id");
        int msgid = Integer.parseInt(Id);
        MailDao md = new MailDao();
        md.chaK(msgid);
        out.println(md.modify(msgid));
        
    %>
    <br>
    <a href="main.jsp">返回</a>
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>    
    <title>My JSP 'index.jsp' starting page</title>    
  </head> 
  <body>
    <script type="text/javascript">
        function validate(){
            if(resForm.uname.value==""){
                alert("账号不能为空!");
                return;
            }
            if(resForm.upwd.value==""){
                alert("密码不能为空!");
                return;
            }
            resForm.submit();
        }
    </script>
    <form action="registerServlet">
     <b>用户名</b>
            <input type="text" name="uname" />
            <br />
            <b>密码</b>
            <input type="text" name="upwd" />
            <br />
            <input type="submit" value="注册" />    
            <a href="log.jsp">登录</a>
    </form>
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
  <head>
   
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  
  <body>
    <form action="writServelt">
             收件人:<input type="text" name="sendto" value="<%=request.getParameter("reply") %>"><br> 
        主题: <input  type="text" name="title" ><br>
        内容    <textarea rows="6" cols="20" name="content"></textarea>
    <br>
    <input type="submit" value="发送"> 
    </form>
  </body>
</html>
package com.bk.dog;
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?useUnicode=true&characterEncoding=utf8", "root", "jth12345");
            } 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();
        }
    }
    
}
package com.bk.dog;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.bk.e.Mail;

public class MailDao extends BaseDao{
    //添加邮件
    public void addMail(Mail m){
        Connection conn=getConnection();
        String sql="insert into mail(username,title,msgcontent,state,sendto,msg_create_date) values(?,?,?,1,?,?)";
        PreparedStatement ps=null;
        try {
            ps=conn.prepareStatement(sql);
            ps.setString(1, m.getUsername());
            ps.setString(2, m.getTitle());
            ps.setString(3, m.getMsgcontent());
            ps.setString(4, m.getSendto());
            ps.setDate(5, new java.sql.Date(new Date().getTime()));
            ps.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            closeAll(conn, ps, null);
        }
    }
    public static void main(String[] args) {
        MailDao md=new MailDao();
        md.delMail(4);
    }    
    //删除邮件(根据id)
    public void delMail(int id){
        Connection con=getConnection();
        String sql="delete from mail where msgid="+id;
        PreparedStatement ps=null;
        try {
            ps=con.prepareStatement(sql);
            ps.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            closeAll(con, ps, null);
        }
    }
    //修改
    
    public Mail chaK(int msgid){
        Mail m=null;
        Connection con=getConnection();
        ResultSet rs=null;
        PreparedStatement ps=null;
        String sql="select * from msg where msgid=?";
        try {
            ps=con.prepareStatement(sql);
            ps.setInt(1, msgid);
            rs=ps.executeQuery();
            while(rs.next()){
                m=new Mail();
                m.setMsgid(rs.getInt("msgid"));
                m.setUsername(rs.getString("username"));
                m.setTitle(rs.getString("title"));
                m.setMsgcontent(rs.getString("msgcontent"));
                m.setState(rs.getInt("state"));
                m.setSendto(rs.getString("sendto"));
                m.setMsg_create_date(rs.getDate("msg_create_date"));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            closeAll(con, ps, rs);
        }
        return m;
    }
    
    public int  modify(int msgid){
        int t=1;
        Connection con=getConnection();
        PreparedStatement ps=null;
        String sql="update msg set state=1 where msgid=?";
        try {
            ps=con.prepareStatement(sql);
            ps.setInt(1, msgid);
            t=ps.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            closeAll(con, ps, null);
        }
        return t;
    }
    
    //查看
    public List<Mail> getMailByReceiver(String uname){
        List<Mail> list=new ArrayList<Mail>();
        Connection con=getConnection();
        String sql="select * from mail where sendto=?";
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            ps = con.prepareStatement(sql);
            ps.setString(1,uname);
            rs=ps.executeQuery();
            while(rs.next()){
                //每读取一行,创建一个对象,对象放到集合中
                Mail m=new Mail();
                m.setMsgid(rs.getInt(1));
                m.setUsername(rs.getString(2));
                m.setTitle(rs.getString(3));
                m.setMsgcontent(rs.getString(4));
                m.setState(rs.getInt(5));
                m.setSendto(rs.getString(6));
                m.setMsg_create_date(rs.getDate(7));
                list.add(m);                
            }            
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            closeAll(con, ps, rs);
        }        
        return list;
    }
}
package com.bk.dog;

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

public class UsersDao extends BaseDao{

    public boolean login(String name,String pwd){
        boolean f=false;
        Connection conn=getConnection();
        String sql="select * from users where uname=? and upwd=?";
        PreparedStatement ps;
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);//第一个?赋值为name
            ps.setString(2, pwd);
            ResultSet rs=ps.executeQuery();
            if(rs.next())//查到结果了
                f=true;
            closeAll(conn, ps, rs);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }        
        return f;
    }
    public int register(String uname, String upwd) {
        Connection con = getConnection();
        PreparedStatement ps = null;
        int s = 0;
        try {
            String sql = "insert into users(uname,upwd) values(?,?)";
            ps = con.prepareStatement(sql);
            ps.setString(1, uname);
            ps.setString(2, upwd);
            s = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(con, ps, null);
        }
        return s;
    }

}
package com.bk.e;

import java.util.Date;

public class Mail {

    private int msgid;
    private String username;
    private String title;
    private String msgcontent;
    private int state;
    private String sendto;
    private Date msg_create_date;
    public int getMsgid() {
        return msgid;
    }
    public void setMsgid(int msgid) {
        this.msgid = msgid;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getMsgcontent() {
        return msgcontent;
    }
    public void setMsgcontent(String msgcontent) {
        this.msgcontent = msgcontent;
    }
    public int getState() {
        return state;
    }
    public void setState(int state) {
        this.state = state;
    }
    public String getSendto() {
        return sendto;
    }
    public void setSendto(String sendto) {
        this.sendto = sendto;
    }
    public Date getMsg_create_date() {
        return msg_create_date;
    }
    public void setMsg_create_date(Date msg_create_date) {
        this.msg_create_date = msg_create_date;
    }
    
}
package com.bk.e;

public class Users {

    int id;
    String uname;
    String upwd;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public String getUpwd() {
        return upwd;
    }
    public void setUpwd(String upwd) {
        this.upwd = upwd;
    }
    
}

package com.sev;
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.bk.dog.MailDao;

public class deltServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public deltServlet() {
        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 {
         request.setCharacterEncoding("utf-8");
            int id=Integer.parseInt(request.getParameter("id"));
            MailDao md=new MailDao();
            md.delMail(id);
            response.sendRedirect("main.jsp");
    }

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

}
package com.sev;

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.bk.dog.MailDao;
import com.bk.dog.UsersDao;

public class logServlet extends HttpServlet {

    public logServlet() {
        super();
    }

    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

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

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

        request.setCharacterEncoding("utf-8");
        String uname=request.getParameter("uname");
        String upwd=request.getParameter("upwd");
        UsersDao ud=new UsersDao();
        MailDao md=new MailDao();
        if(ud.login(uname, upwd)){    
        request.getSession().setAttribute("uname", uname);    
        request.getRequestDispatcher("main.jsp").forward(request, response);
    }else{
        response.setHeader("refresh", "5;url=log.jsp");
    }
    }
    
    public void init() throws ServletException {
        // Put your code here
    }

}
package com.sev;

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.bk.dog.MailDao;
import com.bk.dog.UsersDao;

public class registerServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public registerServlet() {
        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 {

         request.setCharacterEncoding("utf-8");
         String uname = request.getParameter("uname");
         String upwd = request.getParameter("upwd");
         UsersDao ud=new UsersDao();
         MailDao md=new MailDao();
         if(ud.register(uname, upwd)>0){    
            request.getSession().setAttribute("uname", uname);    
            request.getRequestDispatcher("log.jsp").forward(request, response);
        }else{
            response.setHeader("refresh", "3;url=register.jsp");
        }
    }

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

}
package com.sev;

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.bk.dog.MailDao;
import com.bk.e.Mail;

public class writServelt extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public writServelt() {
        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 {
          request.setCharacterEncoding("utf-8");
             String uname=request.getParameter("uname");
             String title=request.getParameter("title");
             String sendto=request.getParameter("sendto");
             String content=request.getParameter("content");
             Mail m=new Mail();
             m.setUsername(uname);
             m.setSendto(sendto);
             m.setTitle(title);
             m.setMsgcontent(content);
             MailDao md=new MailDao();
             md.addMail(m);
        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
    }

}

 

posted @ 2022-05-29 17:26  叶鑫宇  阅读(7)  评论(0编辑  收藏  举报