以下是从jsp页面获取参数的servlet。
我正在尝试运行以下代码 -
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.swing.JFrame;
public class oneServlet extends HttpServlet {
public static Connection getConnection() throws Exception {
String driver = "org.postgresql.Driver";
String url = "jdbc:postgresql://10.1.11.112:5432/pack";
String username = "pack";
String password = "pack";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static void main(String[] args) throws Exception {
String user=request.getParameter("t1");
String pass=request.getParameter("t2");
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String queryTest = "select username,password from login";
pstmt = conn.prepareStatement(queryTest);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String username=rs.getString(1);
String password=rs.getString(2);
if(user.equals(username) && pass.equals(password))
{
JFrame frame = new JFrame("/LoginSuccess.jsp");
}
else
{
System.out.println("Login Failed,Please try Againe");
}
}}
catch (Exception e) {
e.printStackTrace();
} finally {
pstmt.close();
conn.close();
}
}
}
在request.getParameter中显示错误“请求无法解析。任何人都可以帮我解决此问题。
答案 0 :(得分:1)
当您展开HttpServlet
时,您需要覆盖以doGet
和doPost()
为参数的HttpServletRequest
和HttpServletResponse
。
示例:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
.......
String user=request.getParameter("t1"); //Use request variable to do get...
}
答案 1 :(得分:1)
Servlet没有main(),它们由SelvletContainer或Webserver(如tomcat)执行
在你的场景中。
public void doGet(){
String user=request.getParameter("t1");
String pass=request.getParameter("t2");
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String queryTest = "select username,password from login";
pstmt = conn.prepareStatement(queryTest);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String username=rs.getString(1);
String password=rs.getString(2);
if(user.equals(username) && pass.equals(password))
{
//JFrame frame = new JFrame("/LoginSuccess.jsp");
request.getRequestDispatcher().redirect("/LoginSuccess.jsp");
}
else
{
System.out.println("Login Failed,Please try Againe");//This will print at the console
}
}}
catch (Exception e) {
e.printStackTrace();
} finally {
pstmt.close();
conn.close();
}
详细了解servlets