问题
I have a JSP page with a textarea and a button, a servlet and a new jsp:
My 3 problems are:
- My analysis.jsp is empty. My borwser opens a new tab but without the text "Hello World"
- The variable "sql" in my java class is empty too. It should contain the text from my textarea
- How can I hand over after my variable sql isn't empty (after analyze) new new code to a new jsp
index.jsp
<form action="ServletName" method="post" target="_blank">
<div class="form-group">
<label for="codeEditor" style="margin-top: 15px;">Code:</label>
<textarea name="codeEditor" class="form-control" id="codeEditor" rows="15" style="resize: none;"></textarea>
</div>
<div class="analysisButton">
<button type="submit" id="startAnalysis" class="btn btn-default btn-block" style="margin-top: 10px;">Start analysis</button>
</div>
</form>
ServletName.java
protected void doPost(...) ...{
String sql = request.getParameter("codeEditor");
response.sendRedirect("/analysis.jsp");
}
analysis.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
Many thanks in advance
UPDATE: nevermind the variable sql isn't empty <(^,^<) but the other 2 questions are open :)
回答1:
Yes, this may be as simple as
JSP
<form action="some_url" method="post" >
<inputarea name="sqlQuery" >
<input type="submit" value="Sql query" >
<form >
In your servlet, you'll have something like
Servlet
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
...//check that the request is correct
String query = request.getParameter("sqlQuery");//name of textarea
try{
Connection conn = getConnection();//Search SO for how to get a connection
PreparedStatement stmt = conn.prepareStatement(query);
//if your query has any arguments(?) (e.g select * from tbl where id=?), then you should set them too
//stmt.setInt(1, 1000);
ResultSet rs = stmt.executeQuery();
while(rs.next()){
//get database dana here
int someIntVal = rs.getInt("intColumn");
String someStr = rs.getString("someStringColumn");
}catch(SQLException e){
//handle exception
}
}
回答2:
You could do this using a simple form submit:
<form method="POST" action="/myServletPath">
<inputarea name="sqltext" ...
Your servlet (with url mapping 'myServletPath') can then, in the doPost method:
String sql = request.getParameter("sqltext")...
And then do whatever you want.
WARNING: If this is code for your production application, then be aware of SQL injection attacks. This is typically code you wouldn't write for any application that trusts users other than yourself.
来源:https://stackoverflow.com/questions/35203460/jsp-hand-over-text-to-java-and-another-jsp