servlet层
package com.name.servlet;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import com.name.bean.Product;
import com.name.service.FindAllService;
public class FindAll extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//设置编码
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
//获取method请求参数的内容
String parameter = request.getParameter("method");
//如果找到这个内容
if(parameter.equals("findall")){
//用集合接收,请求转发到jsp页面
try {
FindAllService all=new FindAllService();
List<Product> list=all.findall();
//把集合加入域中
request.setAttribute("list", list);
//请求转发
request.getRequestDispatcher("/list.jsp").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
//如果查询时出现异常
//请求转发到一个页面,提示出错
request.setAttribute("msg", "当前查询出现错误");
request.getRequestDispatcher("/error.jsp").forward(request, response);
}
}else if(parameter.equals("add")){
//从index.jsp链接到这里,然后..
//请求转发到填信息的页面,好处是避免填信息页面的地址直接暴露
//在创建的add2里填信息
request.getRequestDispatcher("/add2.jsp").forward(request, response);
}else if(parameter.equals("add2")){
//填完信息,点击提交后,到这里
try {
Product p=new Product();
Map<String, String[]> map = request.getParameterMap();
//第三方jar包,实现map集合里的内容复制到bean中
BeanUtils.populate(p, map);
String pname = p.getPname();
System.out.println(pname);
p.setPdate(new Date().toLocaleString());
//调用service
FindAllService add=new FindAllService();
//添加信息,需要传入参数,第一次做的时候没传入,最后测试的时候都是null
add.add(p);
//再次请求转发,这次转发到list.jsp,添加成功后,显示一次所以的商品
request.getRequestDispatcher("/findall?method=findall").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
//如果出现错误,请求转发到error页面
request.setAttribute("msg", "添加商品出错");
request.getRequestDispatcher("/error.jsp").forward(request, response);
e.printStackTrace();
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
DAO层