我想用jsp:
处理这个表单字段<div class="control-group">
<!-- Text input-->
<label class="control-label" for="input01">Email:</label>
<div class="controls">
<input name="email" placeholder="email"
class="input-xlarge" type="text"
value="<%=request.getParameter("email")%>">
</div>
</div>
<div class="control-group">
<!-- Text input-->
<label class="control-label" for="input01">Password:</label>
<div class="controls">
<input name="password" placeholder="password"
class="input-xlarge" type="text"
value="<%=request.getParameter("password")%>">
</div>
</div>
当我按提交时,我得到一个
的NullPointerException
那是我的servlet方法:
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
logger.log(Level.INFO, "Creating User!!!");
logger.info("Request: " + req.toString());
PrintWriter out = resp.getWriter();//Here I get the null Pointer exception
String email = req.getParameter("email");
String password = req.getParameter("password");
logger.info(email + password);
try {
user.insert(email, password);
Log.info("Inserted: " + email + " " + password);
} catch (Exception e) {
String msg = DAOUser.getErrorMessage(e);
out.print(msg);
}
}
如何修复此空指针异常?
更新
我的servlet:
public class DAOServletUser extends HttpServlet {
private static final long serialVersionUID = 6820994892755862282L;
private static final Logger logger = Logger.getLogger(DAOServletUser.class.getCanonicalName());
/**
* Get the entities in JSON format.
*/
public DAOServletUser() {
super();
}
public IDAOUser user;
/**
* Create the entity and persist it.
*/
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
logger.log(Level.INFO, "Creating User!!!");
logger.info("Request: " + req.toString());
if(resp==null) {
System.out.println("Respond is NULL!!!");
}
PrintWriter out = resp.getWriter();//Here I get the null Pointer exception
String email = req.getParameter("email");
if(email==null) {
System.out.println("email is null");
} else {
System.out.println("email is NOT null");
}
String password = req.getParameter("password");
if(password==null) {
System.out.println("password is null");
} else {
System.out.println("password is NOT null");
}
logger.info(email + "::" + password);
try {
user.insert(email, password);
Log.info("Inserted: " + email + " " + password);
} catch (Exception e) {
String msg = DAOUser.getErrorMessage(e);
out.print(msg);
}
}
答案 0 :(得分:2)
我假设IDAOUser
是一个界面。要在Java中实现接口,可以在类级别使用implements
关键字,如下所示:
public class DaoUserImpl implements IDAOUser {
public void insert(String email, String password) {
// your code for inserting goes here
}
}
在servlet类中,而不是
public IDAOUser user;
像这样实例化(使用new
关键字)
public IDAOUser user = new DaoUserImpl();
然后,您可以在不是user.insert(email,password)
的对象上调用null
。
如果DaoUserImpl使用共享实例数据,您必须小心这个解决方案可能出现的多线程问题。您可能需要每个请求一个类的实例。