我不懂JSP。我编写了以下 Java JDBC 代码,必须将其集成到 JSP 中。
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
public class searchlink{
public static void main(String args[]) throws Exception {
Connection con=null;
Statement stmt=null;
Statement stmtR=null;
String link="http://www.topix.com/rss/city/ellensburgwa";
String source="Sample";
if(con==null){
SQLConnection.setURL("jdbc:sqlserver://192.168.2.53\\SQL2005;user=sa;password=365media;DatabaseName=LN_ADWEEK");
con=SQLConnection.getNewConnection();
stmt=con.createStatement();
stmtR=con.createStatement();
}
ResultSet rs;
boolean hasRows=false;
rs=stmt.executeQuery("select url from urls where url='"+link+"'");
while(rs.next()){
hasRows=true;
//String mem=rs.getString(1);
System.out.println("This URL already exists in DB");}
if (!hasRows)
{
PreparedStatement insertUrlStatement = con.prepareStatement("INSERT INTO urls VALUES(?, ?, ?, ?, ?)");
insertUrlStatement.setInt(1, 21211);
insertUrlStatement.setString(2, link);
insertUrlStatement.setString(3, source);
insertUrlStatement.setInt(4, 1);
insertUrlStatement.setInt(5, 0);
insertUrlStatement.executeUpdate();
}
}
}
最初,我的任务是创建一个文本框,并将用户在其中输入的值分配给上面代码中名为 link 的字符串。
请建议如何为此构建 JSP 程序。另外,请告诉我是否需要对上面的 Java 代码进行任何更改以集成到 JSP 中,或者我可以将整个程序包含在 <% content %>
中。 .
最佳答案
首先,你应该avoid在 JSP 文件中编写 Java 代码。
这是一步一步:
至少学习 HTTP 和 HTML。说到这里,您需要了解 HTTP 的全部内容并区分“服务器端”和“客户端”概念。您还需要学习 HTML 作为网络标记语言和 HTML forms收集用户输入。 This answer contains helpful links 。
学习 JSP 和 Servlet。您需要了解 JSP 是一种基于 Java 的 View 技术,它提供了编写 HTML/CSS/JS 的模板,然后将其发送到 Web 浏览器。 This answer contains helpful links .
学习了 1 和 2 后,开始使用带有必要输入字段的简单 HTML 表单创建 JSP 文件:
<form action="servleturl" method="post"> <input type="text" name="link"> <input type="text" name="source"> <input type="submit"> </form>
然后创建一个类
extends
HttpServlet
它收集这些输入参数并保存在doPost()
的数据库中方法:protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String link = request.getParameter("link"); String source = request.getParameter("source"); LinkDAO dao = new LinkDAO(); try { dao.save(link, source); } catch (SQLException e) { throw new ServletException("Saving in DB failed", e); } request.getRequestDispatcher("result.jsp").forward(request, response); }
将此 servlet 映射到
web.xml
文件url-pattern
的servleturl
(至少,它应该与您的<form action>
指向的位置相同)。然后创建一个 DAO 类来执行必要的 JDBC 操作:
public class LinkDAO { public void save(String link, String source) throws SQLException { // Your original code here. You should however modify it to make it // free of potential resource leaking. } }
要了解更多如何开始使用 DAO 模式,您可能会发现 this article有用。
关于java - 如何在 JSP 中收集用户输入,以便将其存储在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3526078/