Servlet+JSP项目

项目介绍

使用servlet和jsp对数据库中信息进行增删改查,
首先创建一个动态web项目,以下为代码及解析。

思路

  1. 在http://www.cssmoban.com/cssthemes/houtaimoban/index_5.shtml上下载对应模板然后进行修改汉化。
  2. 设计数据库连接并将增删改查封装,javabean,dao层及其实现
  3. 在servlet中进行方法调用和jsp页面之间的转发,交互。

com.lyx.entity

此包下的类为:
创建一个与数据库中列对应的属性,get,set方法,以及需要的构造方法(无参,有参,除了id的)

public class User {
	private int id;
	private String name;
	private int age;
	private String password;
	private String email;
	public User() {
		super();
	}
	
	public User(String name, int age, String password, String email) {
		super();
		this.name = name;
		this.age = age;
		this.password = password;
		this.email = email;
	}

	public User(int id, String name, int age, String password, String email) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.password = password;
		this.email = email;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + ", password=" + password + ", email=" + email
				+ "]";
	}
	
}

com.lyx.tools

这个类进行数据库的连接,并将增删改查封装到两个方法中

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

//这个类是具体的工具类,它主要完成数据库的连接和数据库的操作
//增删改一个方法,查询一个方法
public class BaseDbUtils {
	
	//进行数据库连接
	private static final String driver = "com.mysql.jdbc.Driver";
	private static final String url = "jdbc:mysql://localhost:3306/bigdata06?characterEncoding=utf-8";
	private static final String user = "root";
	private static final String password = "root";
	
	//定义资源方便关闭
	Connection connection = null;
	PreparedStatement preparedStatement = null;
	ResultSet resultSet = null;
	
	//加载驱动
	static {
		try {
			Class.forName(driver);
			System.out.println("加载驱动成功!");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	//获取连接
	public Connection getConnection() {
		try {
			connection = DriverManager.getConnection(url,user,password);
			System.out.println("获取连接成功!");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return connection;
	}
	
	//关闭资源
	public void closeAll() {
		if(resultSet!=null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(preparedStatement!=null) {
			try {
				preparedStatement.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(connection!=null) {
			try {
				connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
			
	}
	
	
	//增,删,改方法
	public int executeUpdate(String sql,Object...objects) {
		int num = 0;
		getConnection();
		try {
			preparedStatement = connection.prepareStatement(sql);
			for(int i = 0; i < objects.length; i++) {
				preparedStatement.setObject(i+1, objects[i]);
			}
			num=preparedStatement.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			closeAll();
		}
		return num;
	}
	
	//查方法
	//关闭资源取不到resultSet
	public ResultSet executeQuery(String sql,Object...objects) {
		getConnection();
		try {
			preparedStatement = connection.prepareStatement(sql);
			for(int i = 0; i < objects.length; i++) {
				preparedStatement.setObject(i+1, objects[i]);
			}
			resultSet=preparedStatement.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultSet;
	}
}

Email:

import java.util.Date;
import java.util.Properties;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import sun.security.util.Password;

public class Email {
	

    // 发件人的 邮箱 和 密码(替换为自己的邮箱和密码)
    // PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”), 
    //     对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。
    public static String myEmailAccount = "[email protected]";
    public static String myEmailPassword = "GQWJDUKVWNOJLPOH";

    // 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com
    // 网易163邮箱的 SMTP 服务器地址为: smtp.163.com
    public static String myEmailSMTPHost = "smtp.163.com";

    // 收件人邮箱(替换为自己知道的有效邮箱)
    public static String receiveMailAccount = "";
    
    // 1. 创建参数配置, 用于连接邮件服务器的参数配置
     static  Properties props = new Properties();  
	
	public void sendEmail(String receiveMailAccount,String username,String Password ) throws Exception{
		
		// 参数配置1
	     
        props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议(JavaMail规范要求)
        props.setProperty("mail.smtp.host", myEmailSMTPHost);   // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.auth", "true");            // 需要请求认证

        // PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启),
        //     如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误,
        //     打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。
        /*
        // SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接,
        //                  需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助,
        //                  QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看)
        final String smtpPort = "465";
        props.setProperty("mail.smtp.port", smtpPort);
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.socketFactory.port", smtpPort);
        */

        // 2. 根据配置创建会话对象, 用于和邮件服务器交互
        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);                                 // 设置为debug模式, 可以查看详细的发送 log

        // 3. 创建一封邮件
        MimeMessage message = createMimeMessage(session, myEmailAccount, receiveMailAccount,username,Password);

        // 4. 根据 Session 获取邮件传输对象
        Transport transport = session.getTransport();

        // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
        // 
        //    PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log,
        //           仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误
        //           类型到对应邮件服务器的帮助网站上查看具体失败原因。
        //
        //    PS_02: 连接失败的原因通常为以下几点, 仔细检查代码:
        //           (1) 邮箱没有开启 SMTP 服务;
        //           (2) 邮箱密码错误, 例如某些邮箱开启了独立密码;
        //           (3) 邮箱服务器要求必须要使用 SSL 安全连接;
        //           (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务;
        //           (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。
        //
        //    PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。
        transport.connect(myEmailAccount, myEmailPassword);

        // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
        transport.sendMessage(message, message.getAllRecipients());

        // 7. 关闭连接
        transport.close();
    }

    /**
     * 创建一封只包含文本的简单邮件
     *
     * @param session 和服务器交互的会话
     * @param sendMail 发件人邮箱
     * @param receiveMail 收件人邮箱
     * @return
     * @throws Exception
     */
    public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail,String username,String password) throws Exception {
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);

        // 2. From: 发件人(昵称有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改昵称)
        message.setFrom(new InternetAddress(sendMail, "人员管理系统", "UTF-8"));
        
        //    Cc: 抄送(可选)
        message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress("[email protected]", "USER_EE", "UTF-8"));

        // 3. To: 收件人(可以增加多个收件人、抄送、密送)
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, username+"用户", "UTF-8"));
     
        

        // 4. Subject: 邮件主题(标题有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改标题)
        message.setSubject("找回密码", "UTF-8");

        // 5. Content: 邮件正文(可以使用html标签)(内容有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改发送内容)
        message.setContent("尊敬的"+username+"你好,你的密码为:"+password, "text/html;charset=UTF-8");

        // 6. 设置发件时间
        message.setSentDate(new Date());

        // 7. 保存设置
        message.saveChanges();

        return message;
    }


}

com.lyx.dao

这个接口中写出对数据库操作的方法

import java.util.List;

import com.lyx.entity.User;

public interface UserDao {
	//写出接口,具体关于用户操作
	public int addUser(User user);
	public int delUser(int id);
	public int updateUser(User user);
	public User findUserById(int id);
	public List<User> getAllUser();
	public User findEmail(String emailaddress);
}

com.lyx.daoImpl

对dao接口进行实现

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.crypto.Data;

import com.lyx.dao.UserDao;
import com.lyx.entity.User;
import com.lyx.tools.BaseDbUtils;

public class DaoImpl extends BaseDbUtils implements UserDao{

	@Override
	public int addUser(User user) {
		// TODO Auto-generated method stub
		int num = 0;
		String sql = "insert into test01(name,age,password,email) values(?,?,?,?)";
		num = executeUpdate(sql, user.getName(),user.getAge(),user.getPassword(),user.getEmail());
		return num;
	}

	@Override
	public int delUser(int id) {
		// TODO Auto-generated method stub
		int num = 0;
		String sql = "delete from test01 where id=?";
		num = executeUpdate(sql, id);
		return num;
	}

	@Override
	public int updateUser(User user) {
		// TODO Auto-generated method stub
		int num = 0;
		String sql = "update test01 set name=?,age=?,password=?,email=? where id=?";
		num = executeUpdate(sql,user.getName(),user.getAge(),user.getPassword(),user.getEmail(),user.getId());
		return num;
	}

	@Override
	public User findUserById(int id) {
		// TODO Auto-generated method stub
		User user = null;
		String sql = "select name,age,password,email from test01 where id=?";
		ResultSet resultSet = executeQuery(sql, id);
		try {
			while(resultSet.next()) {
				user = new User(id,resultSet.getString(1),resultSet.getInt(2),resultSet.getString(3),resultSet.getString(4));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}

	@Override
	public List<User> getAllUser() {
		// TODO Auto-generated method stub
		User user = null;
		String sql = "select * from test01";
		ResultSet resultSet = executeQuery(sql);
		List<User> list = new ArrayList<User>();
		try {
			while(resultSet.next()) {
				user = new User(resultSet.getInt(1),resultSet.getString(2),resultSet.getInt(3),resultSet.getString(4),resultSet.getString(5));
				list.add(user);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public User findEmail(String emailaddress) {
		// TODO Auto-generated method stub
		User user = null;
		String sql = "select name,age,password,email from test01 where email=?";
		ResultSet resultSet = executeQuery(sql, emailaddress);
		try {
			while(resultSet.next()) {
				user = new User(resultSet.getString(1),resultSet.getInt(2),resultSet.getString(3),resultSet.getString(4));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}

}

com.lyx.servlet

  • LoginServlet(当点击提交do=指定内容)(登录)
    空使do为login,输入错误和为空都使do=login,如果do=login则请求转发到jsp(第一个方法)。
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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;

import com.lyx.daoimpl.DaoImpl;
import com.lyx.entity.User;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置字符集编码
	 
	    response.setContentType("text/html;charset=utf-8");
	    request.setCharacterEncoding("utf-8");
		//连接失败时js的弹窗
		PrintWriter printWriter = response.getWriter();
		//前端传来的一个标识,用它来进行具体的工作
		String does = request.getParameter("do");
		if(does==null || does.equals("")) {
			does="login"; //如果does为空登录失败,然后设置does,就会再跑到登录页面
		}
		login(does,request,response);
		loginValidate(printWriter,does,request,response);
	}
	
	//如果do为空,转发回login.jsp页面
	public void login(String does,HttpServletRequest request,HttpServletResponse response) {
		
			try {
				if(does.equals("login")) 
					request.getRequestDispatcher("login.jsp").forward(request,response);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return;
	}
	
	//如果do不为空,进入此验证方法
	public void loginValidate(PrintWriter printWriter, String does, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DaoImpl daoImpl = new DaoImpl();
		//验证前端的数据是不是loginValidate
		if(does.equals("loginValidate")) {
			System.out.println("已经进入验证方法");
			String username= request.getParameter("username");
			String password = request.getParameter("password");
			System.out.println(username+password);
			List<User> list = daoImpl.getAllUser();
			for (int i = 0; i <list.size(); i++) {
				System.out.println(list.get(i).getName());
				if (list.get(i).getName().equals(username)&&list.get(i).getPassword().equals(password)) {
					request.getRequestDispatcher("index.jsp").forward(request, response);
			        return;
				}else {
					printWriter.print(";");

				}
				
			}
		}
	}

}
  • LoginAddUserServlet(注册)
    直接调用daoImpl里的方法来增加数据,注册完之后转发到login.jsp
import java.io.IOException;
import java.io.PrintWriter;

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 com.lyx.dao.UserDao;
import com.lyx.daoimpl.DaoImpl;
import com.lyx.entity.User;
import com.sun.org.apache.xml.internal.serialize.Printer;

/**
 * 用户注册
 */
@WebServlet("/LoginAddUserServlet")
public class LoginAddUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginAddUserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("注册!!!");
		//设置编码格式
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		//从前端获取do
		String does = request.getParameter("do");
		System.out.println(does);
		//一会添加失败就会使用printwriter打印信息
		 //实现打印js
		PrintWriter printWriter = response.getWriter();

		DaoImpl daoImpl = new DaoImpl();
		
		addlist(does, request, response, printWriter, daoImpl);
	}
	
	public void addlist(String does,HttpServletRequest request,HttpServletResponse response,PrintWriter printWriter,DaoImpl daoImpl) {
		if(does.equals("addlist")) {
			String name = request.getParameter("name");
			String password = request.getParameter("password");
			int age = Integer.parseInt(request.getParameter("age"));
			String email = request.getParameter("email");
			User user = new User(name,age,password,email);
			daoImpl.addUser(user);
			System.out.println("成功写入!!");
			printWriter.print(";");
		}else {
			printWriter.print(";");
		}
	}

}
  • PasswordFindServlet(找回密码)
    获取写入的邮箱,并根据邮箱获取账号和密码并将其发送到指定邮箱,发送方法再tools中。
import java.io.IOException;
import java.io.PrintWriter;

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 com.lyx.daoimpl.DaoImpl;
import com.lyx.entity.User;
import com.lyx.tools.Email;

/**
 * Servlet implementation class PasswordFindServlet
 */
@WebServlet("/PasswordFindServlet")
public class PasswordFindServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PasswordFindServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置编码格式
			response.setContentType("text/html;charset=utf-8");
			request.setCharacterEncoding("utf-8");
			//从前端获取do
			String does = request.getParameter("do");
			//一会添加失败就会使用printwriter打印信息
			//实现打印js
			PrintWriter printWriter = response.getWriter();

			DaoImpl daoImpl = new DaoImpl();
			try {
				eamil(daoImpl,does, printWriter, request, response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	public void eamil(DaoImpl daoImpl,String does,PrintWriter printWriter,HttpServletRequest request,HttpServletResponse response) throws Exception {
		if(does.equals("email")) {
			String emailaddress = request.getParameter("email");
			User user = daoImpl.findEmail(emailaddress);
			if(user!=null) {
				String username = user.getName();
				String password = user.getPassword();
				Email email = new Email();
				email.sendEmail(emailaddress, username, password);
				printWriter.print(";");
				return;
			}else {
				printWriter.print(";");
				return;
			}
		}
	}

}
  • SelectServlet(查询)
    创建一个session域然后将查找出来的对象放在session域中再在jsp页面中显示。
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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;

import com.lyx.dao.UserDao;
import com.lyx.daoimpl.DaoImpl;
import com.lyx.entity.User;

/**
 * Servlet implementation class SelectServlet
 */
@WebServlet("/SelectServlet")
public class SelectServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SelectServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("已经用户管理的列出所有的类");
//		设置编码格式
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		//完成的功能就是从数据库查询数据出来,封装对象,写入session
		
		String dos=request.getParameter("do");
		
        PrintWriter printWriter=response.getWriter();// 负责打印js的内容
		
		UserDao userDao= new DaoImpl();
		HttpSession session=request.getSession();
		
		selectList(dos,session, request, response, printWriter, userDao);
  }
	
	public void selectList(String dos,HttpSession session,HttpServletRequest request, HttpServletResponse response,PrintWriter printWriter,UserDao userDao) throws ServletException, IOException{
		if (dos.equals("user-list")) {
			List<User> user_list=userDao.getAllUser();
		    session.setAttribute("user_list", user_list);
		    request.getRequestDispatcher("user-list.jsp").forward(request, response);
			return;
		    
			
		}
	}

}
     <c:forEach items="${user_list}" var="list">
     <tr>
         <td>${list.id }</td>
         <td>${list.name }</td>
         <td>${list.age }</td>
         <td>${list.email }</td>
         <td>
         <a href="EditServlet?do=getEdit&id=${list.id }">修改</a>
         <a href="DeleteServlet?do=del&id=${list.id}" onclick="javascript:return confirm('确认删除吗?');">删除</a>
         </td>
     </tr>
     </c:forEach>
  • EditServlet
    先根据daoimpl中的findUserById()方法查询到对应id的信息存在session域中,并转发到user-edit页面上。然后再将数据修改后点击提交提交在do=edit的方法中进行修改,修改后将页面返回到user-list
import java.io.IOException;
import java.io.PrintWriter;

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;


import com.lyx.daoimpl.DaoImpl;
import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;


@WebServlet("/EditServlet")
public class EditServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
    public EditServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("修改的操作");
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String dos=request.getParameter("do");
		int id=Integer.valueOf(request.getParameter("id"));
		HttpSession session=request.getSession();
		DaoImpl userDao=new DaoImpl();
		PrintWriter printWriter=response.getWriter();
		edit(dos, id, userDao, session, request, response);
		edituser(printWriter,dos, userDao, session, request, response);
	}
	
	
	public void edit(String dos,int id,DaoImpl userDao,HttpSession session,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
	
		if (dos.equals("getEdit")) {
			com.lyx.entity.User user=userDao.findUserById(id);
			user.setId(id);
			session.setAttribute("user", user);
			request.getRequestDispatcher("user-edit.jsp").forward(request, response);
			return;
		}
	}
	
	public void edituser(PrintWriter printWriter,String dos,DaoImpl userDao,HttpSession session,HttpServletRequest request, HttpServletResponse response){
		if (dos.equals("edit")) {
			int id=Integer.valueOf(request.getParameter("id"));
			String name=request.getParameter("name");
			int age=Integer.valueOf(request.getParameter("age"));
			String password=request.getParameter("password");
			String email=request.getParameter("email");
			//System.out.println(id+name+"\t"+password);
			com.lyx.entity.User user=new com.lyx.entity.User(id, name, age, password, email);
			userDao.updateUser(user);
			printWriter.print("");
			return;
		}
	}
}

user-list

 <a href="EditServlet?do=getEdit&id=${list.id }">修改</a>

user-edit

			<div class="portlet-body form">

					<form action="EditServlet?do=edit" method="post" class="horizontal-form">
  • DeleteServlet(直接判断是否删除)
import java.io.IOException;
import java.io.PrintWriter;

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;

import com.lyx.daoimpl.DaoImpl;

/**
 * Servlet implementation class DeleteServlet
 */
@WebServlet("/DeleteServlet")
public class DeleteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("删除的操作");
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String dos=request.getParameter("do");
		int id=Integer.valueOf(request.getParameter("id"));
		HttpSession session=request.getSession();
		DaoImpl userDao=new DaoImpl();
		PrintWriter printWriter=response.getWriter();
		delete(printWriter, dos, id, userDao, request, response);
	}
	
	public void delete(PrintWriter printWriter,String dos,int id,DaoImpl userDao,HttpServletRequest request, HttpServletResponse response) {
		if (dos.equals("del")) {
			userDao.delUser(id);
			printWriter.print("");
			return;
		}else {
			printWriter.print("");
			return;
		}
	}

}

项目难点

  1. 对开始的请求转发含义模糊不清(login)
    将do置为login表示转发在login.jsp页面。
  2. 找回密码需要邮箱账号密码。
  3. 在修改时的思路需要更加理解。
  4. 每个Servlet之间do,jsp文件之间的联系。

你可能感兴趣的:(学习笔记,小项目)