我有一个关于 servlet 重定向到同一个初始页面的问题。 以下是场景: 假设一个用户想要购买一件商品,于是他填写了金额并提交了。表单被提交给一个 servlet,可用的数量将根据数据库中的可用数量进行检查。因此,如果订购的商品数量超过可用数量,servlet 将重定向到同一页面,但会显示一条消息,如“商品不可用”。 所以我的问题是如何实现这个案例。如何使用错误消息重定向到相同的初始页面。我不想在这里使用ajax。
以下是我对它的看法: 1.)如果生成错误,我是否应该设置上下文属性,然后在重定向后在初始页面中再次检查它并显示已设置的消息。
此类 Activity 的最佳做法是什么?
最佳答案
最常见和推荐的方案(用于 Java serlvets/JSP 世界中的服务器端验证)是将一些错误消息设置为请求属性(在请求范围中) 然后使用 Expression Language 在 JSP 中输出此消息(见下面的例子)。如果未设置错误消息 - 将不会显示任何内容。
但是当在请求中存储错误消息时,您应该转发请求到初始页面。重定向时不适合设置请求属性,因为如果您使用重定向,它将是一个完全新请求并且请求属性在请求之间重置。
如果您想将请求重定向到引用页面(您从中提交数据的页面),那么您可以在 session 中存储一条错误消息(在 session 范围),即设置一个 session 属性。但在这种情况下,您还需要在提交的请求正确时从 session 中删除该属性,否则只要 session 存在,就会出现错误消息。
至于context 属性,它意味着可用于整个网络应用程序(应用程序范围)和所有用户,而且它与网络一样存在应用程序生命周期,这对您的情况几乎没有用。如果您将错误消息设置为应用程序属性,它将对所有用户可见,而不仅仅是提交错误数据的用户。
好的,这是一个原始的例子。
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Test application</display-name>
<servlet>
<servlet-name>Order Servlet</servlet-name>
<servlet-class>com.example.TestOrderServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Order Servlet</servlet-name>
<url-pattern>/MakeOrder.do</url-pattern>
</servlet-mapping>
</web-app>
order.jsp
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Test page</h1>
<form action="MakeOrder.do" method="post">
<div style="color: #FF0000;">${errorMessage}</div>
<p>Enter amount: <input type="text" name="itemAmount" /></p>
<input type="submit" value="Submit Data" />
</form>
</body>
</html>
package com.example;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
public class TestOrderServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int amount = 0;
try {
amount = Integer.parseInt(request.getParameter("itemAmount"));
} catch (NumberFormatException e) {
// do something or whatever
}
if ((amount > 0) && (amount < 100)) { // an amount is OK
request.getRequestDispatcher("/index.jsp").forward(request, response);
} else { // invalid amount
// Set some error message as a request attribute.
if (amount <= 0) {
request.setAttribute("errorMessage", "Please submit an amount of at least 1");
}
if (amount > 100){
request.setAttribute("errorMessage", "Amount of items ordered is too big. No more than 100 is currently available.");
}
// get back to order.jsp page using forward
request.getRequestDispatcher("/order.jsp").forward(request, response);
}
}
}
TestOrderServlet.java
package com.example;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
public class TestOrderServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int amount = 0;
try {
amount = Integer.parseInt(request.getParameter("itemAmount"));
} catch (NumberFormatException e) {
// do something or whatever
}
if ((amount > 0) && (amount < 100)) { // an amount is OK
// If the session does not have an object bound with the specified name, the removeAttribute() method does nothing.
request.getSession().removeAttribute("errorMessage");
request.getRequestDispatcher("/index.jsp").forward(request, response);
} else { // invalid amount
// Set some error message as a Session attribute.
if (amount <= 0) {
request.getSession().setAttribute("errorMessage", "Please submit an amount of at least 1");
}
if (amount > 100){
request.getSession().setAttribute("errorMessage", "Amount of items ordered is too big. No more than 100 is currently available.");
}
// get back to the referer page using redirect
response.sendRedirect(request.getHeader("Referer"));
}
}
}
相关阅读:
关于java - Servlet 重定向到同一页面并显示错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14632252/
我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案
所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我的问题的一个例子是体育游戏。一场体育比赛有两支球队,一支主队和一支客队。我的事件记录模型如下:classTeam"Team"has_one:away_team,:class_name=>"Team"end我希望能够通过游戏访问一个团队,例如:Game.find(1).home_team但我收到一个单元化常量错误:Game::team。谁能告诉我我做错了什么?谢谢, 最佳答案 如果Gamehas_one:team那么Rails假设您的teams表有一个game_id列。不过,您想要的是games表有一个team_id列,在这种情况下
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我