package cn.hnshxy.xg;
import java.io.IOException;
import java.util.List;
import java.util.Map;
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.mysql.cj.Session;
@WebServlet("/jielong")
public class JieLong extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// response.getWriter().append("Served at: ").append(request.getContextPath());
request.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
String cy=request.getParameter("chengyu");
String time=request.getParameter("time");
String history=(String) session.getAttribute("history");
String msg=null;
String first=(String) session.getAttribute("first");
System.out.println("first="+first);
// String first=null;
boolean isUserWin=false;
if(cy!=null) {//提交表单过来的
cy=cy.trim();
try {
isUserWin=(boolean) session.getAttribute("isUserWin");
if(isUserWin)throw new Exception("不用刷新,你都是最棒的~");
if(time==null||time.isEmpty())throw new Exception("检测到非法操作~");
if(((String)session.getAttribute("time")).equals(time))throw new Exception("请不要刷新页面~");
if(cy.isEmpty())throw new Exception("请输入接龙的成语");
if(cy.length()<3||cy.length()>14)throw new Exception("成语应该在3到14个汉字之内");
if(first!=null && !cy.startsWith(first))throw new Exception("请输入以“"+first+"”开头的成语");
DBHelper db=new DBHelper();
List<Map<String,Object>> list=db.executeQuery("select cy from chengyu where cy=?",cy);
if(list==null)throw new Exception(db.getErrorMessage());
if(list.size()==0) throw new Exception(msg="你输入的“"+cy+"”不是成语~");//用户输入的不是成语
//用户输入的是成语
history+=","+cy;//将用户接龙的成语加入接龙历史
list=db.executeQuery("select cy from chengyu where first=? order by rand() limit 1", cy.substring(cy.length()-1));
if(list==null)throw new Exception(db.getErrorMessage());
if(list.size()==0) {
msg="恭喜你战胜了计算机~";
isUserWin=true;
}else {
cy=(String) list.get(0).get("cy");//现在存储的是计算机接龙的成语
history+=","+cy;//将计算接龙的成语加入接龙的历史
first=cy.substring(cy.length()-1);
}
}catch(Exception e) {
msg=e.getMessage();
}
}else {
first=null;
history="";
time="0";
}
// history=",一清二白,白首相知,知根知底,低眉垂眼,眼疾手快,快马加鞭";
// msg="<script>alert('xiaoguo')</script>一清二白";
request.setAttribute("msg", msg);
session.setAttribute("first", first);
session.setAttribute("time", time);
session.setAttribute("history", history);
// session.setAttribute("length", history.length());
session.setAttribute("isUserWin", isUserWin);
request.getRequestDispatcher("/v1/index.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}