简体   繁体   English

如何从jsp页面获取ID到servlet?

[英]How to get id from jsp page to servlet?

I have a list of users registered on a website and when the admin clicks to approve, it must fetch the id and then move that row to another table called login... now the problem here is from jsp how to fetch id in servlet so that it can be passed into a method to service and DAO layers. 我有一个在网站上注册的用户列表,当管理员单击批准时,它必须获取ID,然后将该行移至另一个名为login的表...现在的问题是jsp如何在servlet中获取ID,因此可以将其传递给服务和DAO层的方法。

Below is my jsp: 下面是我的jsp:

<tr bgcolor="white">
<td><b>id</b></td>
<td><b>FirstName</b></td>
<td><b>LastName</b></td>
<td><b>Gender</b></td>
<td><b>Category</b></td>
<td><b>DateOfBirth</b></td>
<td><b>Age</b></td>
<td><b>Address</b></td>
<td><b>Country</b></td>
<td><b>State</b></td>
<td><b>City</b></td>
<td><b>PinCode</b></td>
<td><b>EmailId</b></td>
<td><b>ContactNo</b></td>
<td><b>MobileNo</b></td>
</tr>


 <c:forEach items="${clients}" var="client">
 <tr>
            <td><c:out value="${client.id}"/></td>
            <td><c:out value="${client.firstName}"/></td>
            <td><c:out value="${client.lastName}"/></td>
            <td><c:out value="${client.gender}"/></td>
            <td><c:out value="${client.category}"/></td>
            <td><c:out value="${client.date}"/></td>
            <td><c:out value="${client.age}"/></td>
            <td><c:out value="${client.address}"/></td>
            <td><c:out value="${client.country}"/></td>
            <td><c:out value="${client.state}"/></td>
            <td><c:out value="${client.city}"/></td>
            <td><c:out value="${client.pinCode}"/></td>
            <td><c:out value="${client.emailId}"/></td>
            <td><c:out value="${client.contactNo}"/></td>
            <td><c:out value="${client.mobileNo}"/></td>
            <td><a href="ClientApproveServlet?id=${client.id}">APPROVE</a></td> // I have fetched the id here
            <td><a href="Reject.jsp">REJECT</a></td>
            <td><a href="OnHold.jsp">ONHOLD</a></td>

            </tr>
      </c:forEach>

Stack TRace: 堆栈跟踪:

java.lang.RuntimeException: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
    at com.affiliate.DAO.ClientApproveDAO.insertClient(ClientApproveDAO.java:28)
    at com.affiliate.service.ClientApproveService.clientApprove(ClientApproveService.java:12)
    at com.affiliate.servlet.ClientApproveServlet.doGet(ClientApproveServlet.java:35)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4190)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4122)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2812)
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1811)
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1725)
    at org.apache.tomcat.dbcp.dbcp.DelegatingStatement.executeUpdate(DelegatingStatement.java:228)
    at org.apache.tomcat.dbcp.dbcp.DelegatingStatement.executeUpdate(DelegatingStatement.java:228)
    at com.affiliate.DAO.ClientApproveDAO.insertClient(ClientApproveDAO.java:23)
    ... 23 more

Hey i resolved it changing my DAO like this: 嘿,我解决了这样更改我的DAO的问题:

public class ClientApproveDAO {

        private DataSource dataSource;
        public void setDataSource(DataSource dataSource) {
       this.dataSource = dataSource;
    }
    Connection conn=null;
    PreparedStatement statement=null;
    ResultSet rs=null;


    public void insertClient(int id) {    
        try{
            conn=dataSource.createConnection();
            PreparedStatement ps=conn.prepareStatement("insert into login(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

            ps.executeUpdate("insert into login(id,FirstName,LastName,Gender,Category,Dateofbirth,Age,Address,Country,State,city,PinCode,EmailId,ContactNo,MobileNo)select * from register where id="+id+"");
            ps.setInt(1, id);

        }
        catch (SQLException e) {
            throw new RuntimeException(e);

    } finally {
            if (rs != null) try { rs.close(); } catch (SQLException ignore) {}
        if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
        if (conn != null) try { conn.close(); } catch (SQLException ignore) {}
    }


    }

}

Thank you all for all the help and this is my final code its working absolutely fine and as desired. 谢谢大家提供的所有帮助,这是我的最终代码,它的工作绝对正常且符合要求。

Remove space between $ and {client.id} 删除${client.id}之间的{client.id}

<a href="ClientApproveServlet?id= $ {client.id}">
                                   ↑  

Should be 应该

<a href="ClientApproveServlet?id=${client.id}">

Update 更新

It means that we overcame NumberFormat. 这意味着我们克服了NumberFormat。 Now, error is in insertClient() method. 现在,insertClient()方法中出现错误。

I can say from exception your syntax of insert statement is wrong. 我可以从异常中说出您的插入语句语法错误。

Just add the condition where id=? 只需添加条件where id=? , because select * from register fetch all the records. ,因为select * from register获取所有记录。

PreparedStatement ps=conn.prepareStatement("insert into login(id,FirstName,
     LastName,Gender,Category,Dateofbirth,Age,Address,Country,State,city,
     PinCode,EmailId,ContactNo,MobileNo)select * from register where id=?");
ps.setInt(1, id);

Just check your SQL query. 只需检查您的SQL查询。 My point of view your column count are not matching. 我的观点是您的栏数不匹配。 Try to give like 尝试给像

select id,firstname... etc 

instead of 代替

select * from tablename 

I think you have a space in $ {client.id} just remove it will work. 我认为$ {client.id}中有一个空格,将其删除即可。

 <a href="ClientApproveServlet?id= ${client.id}">

I think you query also not well formatted try: 我认为您的查询格式也不正确,请尝试:

 String query ="insert into login(id,FirstName,LastName,Gender,Category,Dateofbirth,Age,"
 " Address,Country,State,city,PinCode,EmailId,ContactNo,MobileNo)"+
 " select id,..,..,.. FROM register; ";

you must change insert code following as: 您必须将插入代码更改为:

insert into login (FirstName,LastName,Gender,Category,

                     Dateofbirth,Age,Address,Country,State,city,PinCode,

                     EmailId,ContactNo,MobileNo)values(?,?,?,?,?,?,?,?,?,?);

you should check this user model like as: 您应该像这样检查该用户模型:

private int userid;
public int getUserid()
{
return userid;  
}
public void setUserid(int userid)
{
this.userid=userid; 
}

you should change this type for your insert type: 您应该为插入类型更改此类型:

public void addUser(User user)
    {
        try
        {
            PreparedStatement preparedStatement=connection.prepareStatement("insert into users (firstname,lastname,dob,email)values(?,?,?,?)");

            preparedStatement.setString(1, user.getFirstName());
            preparedStatement.setString(2, user.getLastName());
            preparedStatement.setDate(3, new java.sql.Date(user.getDob().getTime()));
            preparedStatement.setString(4, user.getEmail());
            preparedStatement.executeUpdate();
        }
        catch(SQLException e)
        {
            e.printStackTrace();
        }
    } 

ok you can try this 好,你可以试试看

before executing this line 在执行此行之前

public void insertClient(int id) {    
        try{
            conn=dataSource.createConnection();
            PreparedStatement ps=conn.prepareStatement("insert into login(id,FirstName,LastName,Gender,Category,Dateofbirth,Age,Address,Country,State,city,PinCode,EmailId,ContactNo,MobileNo)select * from register");
            ps.setInt(1, id);
            ps.executeUpdate();
        }
        catch (SQLException e) {
            throw new RuntimeException(e);

add this to it 将此添加到它

 String x=null;
 Resultset rs=conn.prepareStatement("select id from old_table where FirstName='request.getParameter('firstname')'and LastName='request.getParameter('lastname')'.......and so on.
while(rs.next){
x=rs.getString('id');
}

then use this x and pass it in your insert statement.. 然后使用此x并将其传递到您的插入语句中。

Easiest way is to put them into session or in cookies, if there is only one or two values. 如果只有一个或两个值,则最简单的方法是将它们放入会话或cookie中。

session.setAttribute("id",id);
cookie.setAttribute("name",name);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM