这篇文章介绍一下如何实现成语接龙。严格意义上来说我实现的是四个字的词语接龙。没有引入成语库,只判断是否为四个字以及前一个词最后一个字和后一个词第一个字是否相同。用两个jsp页面就可以实现,非常简单基础。
不知道文件建在哪看一看前面的文章,写了很多次。
chengyu_jielong.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<h1>成语接龙</h1>
<%
if(session.getAttribute("words")!=null){%><h2>已经说过的成语:</h2><br><%
String words = (String)session.getAttribute("words");
%>
<%=words %>
<%
}
%>
<form action="chengyu_jielong_post.jsp">
<b>成语</b><input type="text" name="word"><br>
<input type="submit">
</form>
</html>
chengyu_jielong_post.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.List" %>
<%
String words = null;
if(session.getAttribute("words")!=null){
words = (String)session.getAttribute("words");
}
if(request.getParameter("word")!=null){
String word = request.getParameter("word");
if(words==null||word.length()==4&&word.charAt(0) ==words.charAt(words.length()-1)){
if(words==null){
words="";
}
session.setAttribute("words",words+"=>"+word);
%>
<html><script>alert("<% out.print(word); %>接龙成功,跳转至chengyu_jielong.jsp");window.location="chengyu_jielong.jsp"</script></html>
<%
}else{
%>
<html><script>alert("<%=word.charAt(0) ==words.charAt(words.length()-1)%>接龙失败,跳转至chengyu_jielong.jsp");window.location="chengyu_jielong.jsp"</script></html>
<%
}
}
%>
如果已经生成了web.xml文件就不用再建了,把其他的建好,代码放进去。运行失败的话,再改web.xml的代码。
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>Experiments</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
运行结果