public class BaseServlet extends HttpServlet{
public void service(HttpServletRequest req,HttpServletResponse resp){
//获取要调用的的方法名称
String methodName = request.getParameter(“method”);
// 获得Class,利用反射执行方法
Class clazz = this.getClass();
Method method = clazz.getMethod(methodName,HttpServletRequest.class,HttpSerlvetResponse.class);
//接收方法的返回值,如果不为null就转发
String path = (String)method.invoke(this,req,resp);
if(path != null){
req.getRequestDispatcher(path).forward(req,resp);
}
}
}
<!--用户名文本框-->
<input type="text" class="form-control" id="username" name="username" value="${cookie.username.value }" placeholder="请输入用户名">
<!--记住用户名复选框-->
<input type="checkbox" name="remember" value="true"> 记住用户名
String remember = request.getParameter("remember");
if("true".equals(remember)){
Cookie cookie = new Cookie("username", existUser.getUsername());
cookie.setPath(request.getContextPath());
cookie.setMaxAge(60*60*24);
response.addCookie(cookie);
}
<!--自动登录复选框-->
<input type="checkbox" name="autoLogin" value="true"> 自动登录
//仅需在session中没有用户信息,cookie中存在且正确的情况下才需要在把用户信息存到session中,其他情况直接放行
HttpServletRequest req = (HttpServletRequest) request;//转为HttpServletRequest对象
HttpSession session = req.getSession();//获取session
User existUser = (User) session.getAttribute("existUser");//获取session中的用户信息
if (existUser == null) {//如果用户信息不存在
Cookie[] cookies = req.getCookies();
Cookie c = CookieUtils.getCookie(cookies, "autoLogin");//获取保存登陆信息的cookie
if (c != null) {//如果cookie不为空,也就是登陆信息存在
String username = c.getValue().split("#")[0];//获取保存的用户信息
String password = c.getValue().split("#")[1];
User user = new User();
user.setUsername(username);
user.setPassword(password);
try {
existUser = new UserServiceImpl().login(user);//查询cookie中保存的是否正确
if (existUser != null) {//如果能查到,将该信息保存到session中
session.setAttribute("existUser", existUser);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
chain.doFilter(req, response);//其他条件直接放行
$("#username").bind("blur",function(){
if($(this).val()!=""){
$.ajax({
url:"${pageContext.request.contextPath}/UserServlet",
data:{username:$(this).val(),"method":"checkUsername"},
success:function(data){
if(data!=""){
if(data==0){//如果后台返回的值为0,则表示用户名可用
$("#msgSpan").html("<font class='msg' color='green'>用户名可用</font>");
$("#submit").prop("disabled",false);
}else if(data==1){//如果后台返回的值为1,则表示用户名不可用
$("#msgSpan").html("<font class='msg' color='red'>用户名不可用</font>");
$("#submit").prop("disabled",true);
}
}
}
});
}else{
$("#msgSpan").empty();
}
});
public String checkUsername(HttpServletRequest request,HttpServletResponse response){
String username = request.getParameter("username");
try {
User existUser = new UserServiceImpl().checkUsername(username);
if(existUser == null){
response.getWriter().print(0);
}else{
response.getWriter().print(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void sendMail(String to, String code){
Properties props = new Properties();
//props.setProperty("smtp", "localhost");
//props.setProperty("pop", "localhost");
Session session = Session.getInstance(props, new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("service@store.com", "111");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("service@store.com"));
message.addRecipient(RecipientType.TO, new InternetAddress(to));
message.setSubject("来自商城的激活邮件");
message.setContent("<h3>请点击激活</h3><h3><a href='http://localhost:8080/store_v2.0/UserServlet?method=active&code="+code+"'>http://localhost:8080/store_v2.0/UserServlet?method=active&code="+code+"</a></h3>","text/html;charset=UTF-8");
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
public String logOut(HttpServletRequest request, HttpServletResponse response){
Cookie cookie = new Cookie("autoLogin", "");
cookie.setPath(request.getContextPath());
cookie.setMaxAge(0);
response.addCookie(cookie);
request.getSession().invalidate();
return "/index.jsp";
}
缓存工具类
private static CacheManager cacheManager;//创建缓存管理对象
static{//从配置文件中读取缓存管理对象
cacheManager = CacheManager.create(CacheUtils.class.getClassLoader().getResourceAsStream("ehcache.xml"));
}
public static Object getValue(String cacheName,Object key){
try {
Cache cache = cacheManager.getCache(cacheName);
Element element = cache.get(key);
if(element!=null){
return element.getObjectValue();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void putValue(String cacheName,Object key,Object value){
try {
Cache cache = cacheManager.getCache(cacheName);
Element element = new Element(key,value);
cache.put(element);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void removeCache(String cacheName,Object key) {
Cache cache = cacheManager.getCache(cacheName);
cache.remove(key);
}
<-- 商品浏览记录 -->
<%
Cookie[] cookies = request.getCookies();
Cookie cookie = CookieUtils.findCookie(cookies, "history");
if(cookie==null){
out.print("<h3>您还没有浏览记录!</h3>");
return;
}
String value = cookie.getValue();
String[] ids = value.split("-");
ProductService productService = new ProductServiceImpl();
for(String id:ids){
Product product= productService.findByPid(id);
request.setAttribute("p", product);
%>
<li><img src="${pageContext.request.contextPath}/${p.pimage}" /></li>
<%
}
%>
private Product product;
private Integer count;
private Double subTotal;
private Map<String, CartItem> map = new LinkedHashMap<>();
private Double totalCount = 0d;
public void addItem(CartItem cartItem) {
String pid = cartItem.getProduct().getPid();
if(!this.map.containsKey(pid)){
this.map.put(pid, cartItem);
}else{
CartItem _cartItem = this.map.get(pid);
_cartItem.setCount(cartItem.getCount()+_cartItem.getCount());
}
totalCount+=cartItem.getSubTotal();
}
public void clearCart() {
this.map.clear();
this.totalCount = 0d;
}
public void removeItem(String pid) {
CartItem cartItem = this.map.remove(pid);
totalCount -= cartItem.getSubTotal();
}
<%
String token = UUIDUtils.getUUID();
request.getSession().setAttribute("token", token);
%>
<input type="hidden" name="token" value="${token }">
private Date ordertime;
private Double total;
private Integer state; // 1:未付款 2:已经付款,未发货. 3:已经发货,没有确认收货. 4:已经确认收货,订单结束.
private String address;
private String name;
private String telephone;
private User user;
private List<OrderItem> orderItems = new ArrayList<OrderItem>();
private String itemid;
private Integer count;
private Double subtotal;
private Product product;
private Order order;
//创建订单
Order order = new Order();
order.setOid(UUIDUtils.getUUID());
order.setOrdertime(new Date());
order.setTotal(cart.getTotalCount());
order.setState(1);
order.setUser(existUser);
//创建订单项
List<OrderItem> orderItems = order.getOrderItems();
Collection<CartItem> cartItems = cart.getMap().values();
for (CartItem cartItem : cartItems) {
OrderItem orderItem = new OrderItem();
orderItem.setItemid(UUIDUtils.getUUID());
orderItem.setCount(cartItem.getCount());
orderItem.setSubtotal(cartItem.getSubTotal());
orderItem.setProduct(cartItem.getProduct());
orderItem.setOrder(order);
orderItems.add(orderItem);//将订单项添加到订单中的集合
}
//调用dao层的save方法将订单保存到数据库
OrderService orderService = (OrderService) BeansFactory.getBean("OrderService");
orderService.save(order);
public List<Order> findByUid(String uid, int begin, int pageSize) throws Exception {
QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
String sql = "select * from orders where uid = ? order by ordertime desc limit ?,?";
List<Order> list = qr.query(sql, new BeanListHandler<Order>(Order.class), uid, begin, pageSize);//根据用户id查询订单,此时list中并没有product的信息
for (Order order : list) {
sql = "select * from orderitem o,product p where o.oid = ? and o.pid = p.pid";
List<Map<String, Object>> mapList = qr.query(sql, new MapListHandler(), order.getOid());
for (Map<String, Object> map : mapList) { // 遍历List,获取其中的每个Map
Product product = new Product(); // 创建商品对象
BeanUtils.populate(product, map); // 封装商品数据
OrderItem orderItem = new OrderItem(); // 创建订单项
BeanUtils.populate(orderItem, map); // 封装订单项数据
orderItem.setProduct(product); // 将商品信息设置到订单项中
order.getOrderItems().add(orderItem); // 将订单项添加到订单中
}
}
return list;
}
public Order findByOid(String oid) throws Exception {
QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
String sql = "select * from orders where oid = ?";
Order order = qr.query(sql, new BeanHandler<Order>(Order.class), oid);
sql = "select * from product p,orderitem o where o.oid = ? and o.pid = p.pid";
List<Map<String, Object>> maps = qr.query(sql, new MapListHandler(), oid);
for (Map<String, Object> map : maps) {
Product product = new Product();
BeanUtils.populate(product, map);
OrderItem orderItem = new OrderItem();
BeanUtils.populate(orderItem, map);
orderItem.setProduct(product);
order.getOrderItems().add(orderItem);
}
return order;
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |