我做了一个简单的例子实现jsp和servlet之间的传值,由于我是新手,刚刚接触jsp和servlet,所以花了好多的时间来实现,下面就把源码和遇到的问题写下来,方便自己复习,也希望可以帮到有需要的同学。
index.jsp
</pre><p></p><p></p><pre name="code" class="html"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="servlet.seg"%>
<%@ page import="Struct.word"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<% String word=(String)request.getAttribute("word"); %>
<%String name="请输入";
name=(String)request.getAttribute("name"); %>
<!-- 上面这句话是从servlet里面接收数据 -->
<body>
<form name="form" action="seg" method=post>
<input type="text" name=name>
<input type="textarea" name=pas value=<%=word%> >
<input type="submit" value="submit"></form> <br>
</body>
</html>
seg.java
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Struct.word;
import word_segment.NlpirTest;
import GUI.word_data;
//获取从jsp传来的text值,并且进行分词
public class seg extends HttpServlet{
List<word> data=new ArrayList<word>();//获得的分词
List<word> keyWordsp=new ArrayList<word>();//获得的情感词
List<word> keyWordsn=new ArrayList<word>();//情感词
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
//获取text值
resp.setContentType("text/html,charset=utf-8");
req.setCharacterEncoding("utf-8");
String text=req.getParameter("name");
word_data a=new word_data();
word_segment.NlpirTest nlpirTest = new word_segment.NlpirTest();
String result=nlpirTest.word_seg(text);
data=a.getword(result);
//PrintWriter out=resp.getWriter();
if(data.size()>0)
{
result=result.replace(" ", "");
req.setAttribute("word",result);
req.getRequestDispatcher("/index.jsp").forward(req, resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(req, resp);
}
}
web.xml中加入
<servlet>
<servlet-name>seg</servlet-name>
<servlet-class>servlet.seg</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>seg</servlet-name>
<url-pattern>/seg</url-pattern>
</servlet-mapping>
实现的功能如下
就是在第一个框里输入一段话,单击按钮提交后会把分词结果显示在第二个框里面,现在有一个疑问,就是不知道怎么可以再第二个页面里保持第一个框里的