将整数变量从jsp传递给servlet

时间:2014-08-12 07:33:25

标签: jsp servlets

我有一个jsp页面,其中有两个变量是标志变量....我想将这些变量传递给servlet。我该如何将这些变量传递给servlet?

这是我的jsp页面。

<html>
<head>
<title>Student Registration Form</title>
<style type="text/css">
h3{font-family: Calibri; font-size: 22pt; font-style: normal; font-weight: bold; color:SlateBlue;
text-align: center; text-decoration: underline }
table{font-family: Calibri; color:white; font-size: 11pt; font-style: normal;
text-align:; background-color: SlateBlue; border-collapse: collapse; border: 2px solid navy}
table.inner{border: 0px}
</style>
</head>

<body>

<h3>Create Category</h3>
<form action="insert_category" method="POST">

<table align="center" cellpadding = "10">

<tr>
<td>Category Name</td>
<td><input type="text" name="category_name" maxlength="30"/>
(max 30 characters a-z and A-Z)
</td>
</tr>


    <%
int flag=1;
int operation=1;
request.setAttribute("flag", String.valueOf(flag));
request.setAttribute("operation", String.valueOf(operation));
%>

<tr>
<td>Category Code</td>
<td><input type="text" name="category_code" maxlength="30"/>
(max 30 characters a-z and A-Z)
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</td>
</tr>
</table>

</form>

</body>
</html>

的Servlet

package com.kunal.servlet;

import java.io.IOException;
import java.sql.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CreateCategory
 */
@WebServlet("/CreateCategory")
public class InsertCategory extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public InsertCategory() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String category__name=request.getParameter("category_name");
        String category_code=request.getParameter("category_code");
        int flag=(int)request.getAttribute("flag");
        int operation=(int)request.getAttribute("operation");
        if(flag==1 && operation==1)
        {
        String connectionURL = "jdbc:mysql://localhost:3306/agro";

        Connection connection = null;
        long catcode=Integer.parseInt(category_code);
        try {
            // Load the database driver
            Class.forName("com.mysql.jdbc.Driver");
            // Get a Connection to the database
            connection = DriverManager.getConnection(connectionURL, "root", "");
            //Add the data into the database

            //String sql = "insert into sample values(?,?)";

            PreparedStatement pst = connection.prepareStatement("INSERT into tbl_category VALUES(?,?,?)");

            pst.setString(1,null);
            pst.setString(2,category__name);
            pst.setLong(3,catcode);

            int numRowsChanged = pst.executeUpdate();
            if(numRowsChanged!=0){
                System.out.println("Successfull execution");
                RequestDispatcher rd = request.getRequestDispatcher("adminhome.jsp");
                rd.forward(request, response);
            }
            else{
                            System.err.println("Problem with the insertion query");
            }
            pst.close();
            }
            catch(ClassNotFoundException e){
                            e.printStackTrace();
            }
            catch(SQLException e){
                            e.printStackTrace();
            }
            catch (Exception e){
                            e.printStackTrace();
            }
            finally {
            // Always close the database connection.
            try {
            if (connection != null) connection.close();
            }
            catch (SQLException ignored){
            }
            }
        }
    }
}

我不能使用getParameters()方法,因为这些只是两个变量。有没有办法将这些传递给servlet?我得到一个NullPointerException

栈跟踪

Aug 12, 2014 1:22:10 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
Aug 12, 2014 1:22:11 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Agro' did not find a matching property.
Aug 12, 2014 1:22:11 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Aug 12, 2014 1:22:11 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Aug 12, 2014 1:22:11 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Aug 12, 2014 1:22:11 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Aug 12, 2014 1:22:11 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 673 ms
Aug 12, 2014 1:22:11 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Aug 12, 2014 1:22:11 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.9
Aug 12, 2014 1:22:11 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Aug 12, 2014 1:22:11 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Aug 12, 2014 1:22:11 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Aug 12, 2014 1:22:11 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 675 ms
Aug 12, 2014 1:22:25 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [InsertServlet] in context with path [/Agro] threw exception
java.lang.NullPointerException
    at com.kunal.servlet.InsertCategory.doPost(InsertCategory.java:42)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

3 个答案:

答案 0 :(得分:1)

简单includeimport JSP中的Servlet,并将值作为请求参数传递。

尽量避免使用Scriplet,而是使用更易于使用且不易出错的JavaServer Pages Standard Tag LibraryExpression Language

JSP:

<jsp:include page="/myServlet?flag=1&operation=1"/>

OR

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:import url="/myServlet?flag=1&operation=1"/>

的Servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    System.out.println(request.getParameter("flag"));
    System.out.println(request.getParameter("operation"));
}

如果您使用的是表单,那么它应该是

<form action="${pageContext.servletContext.contextPath}/insert_category"

或者在request属性

中设置它

JSP:

<c:set var="flag" value="1" scope="request"/>
<c:set var="operation" value="1" scope="request"/>
<c:import url="/test2"/>

Setvlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    System.out.println(request.getAttribute("flag"));
    System.out.println(request.getAttribute("operation"));
}

答案 1 :(得分:1)

如果您希望在表单提交时传递flagoperation参数,则可以将其存储在隐藏字段中,这样当您提交表单时,它将使用您的表单参数发送。

<form action="insert_category">
    <input type="hidden" name="flag" value="1">
    <input type="hidden" name="operation" value="1">  

    ....rest of your code  

</form>

在服务器端,您可以通过request.getParameter()获取此参数,如下所示:

int flag=(int)request.getParameter("flag");
int operation=(int)request.getParameter("operation");    

OR
您可以将此参数存储在session中,并从服务器端的会话中获取值,例如:

你在JSP中的

        <%                          
            session.setAttribute("flag", String.valueOf(flag));
            session.setAttribute("operation", String.valueOf(operation));
        %>      

在servlet的服务器端:

HttpSession session = request.getSession();
int flag=(int)session.getAttribute("flag");
int operation=(int)session.getAttribute("operation"); 

愿这对你有所帮助。

答案 2 :(得分:0)

您有许多选项,例如请求范围,会话范围等 试试这样的事情

request.setAttribute("flag", flag);
request.setAttribute("operation", operation);

获取像这样的属性

int flag = Integer.parseInt(request.getAttribute("flag"));
int operation = Integer.parseInt(request.getAttribute("operation"));

同样,您可以使用session对象来设置和获取属性

修改:您的表单操作网址为insert_category,因此请更改

@WebServlet("/CreateCategory")

@WebServlet("/insert_category")

当你使用基于注释的网址映射时,我希望你没有web.xml中的映射