【发布时间】:2018-07-12 15:18:34
【问题描述】:
我想从给定的url 中获取查询字符串的传递值,例如:http://localhost:8080/app?contentid=10 我想从我的 spring 控制器中的上述 url 中获取 contentid is: 10 的值,我怎样才能得到这个?
请注意,如果我在那里传递任何值(如 10、50,100、200 等 - 它可以是任何数字),所以无论我传递给 contentid,该值都应该进入我的控制器。我只想从那个url 中获取这个contentid 值,而不是从我的html 页面或者我不想从我的html 页面传递。目前我从控制器中的以下代码中获得null,我没有获得传递值(比如来自url 的10)。我怎样才能做到这一点?提前感谢您的帮助!
app.html:
<form action="#" th:action="@{/app}" th:object="${TestData}" method="post">
<div class="form-group">
<label for="firstname">First Name: </label> <input type="text"
class="form-control" id="firstname" name="firstname" ></textarea>
</div>
<div class="form-group">
<label for="secondname">Second Name:</label> <input type="text"
class="form-control" id="secondname" name="secondname" />
</div>
<button type="submit" value="Submit">Submit</button>
</form>
TestData.java:
public class TestData implements Serializable{
private String firstname;
private String secondname;
private int contentid;
//setters and getters
public TestData() {}
public TestData(String firstname, String secondname, int contentid, ){
this.firstname = firstname;
this.secondname = secondname;
this.contentid = contentid;
}
@Override
public String toString() {
return String.format(
"TestData[firstname=%s, secondname=%s, contentid=%d]",
firstname, secondname, contentid);
}
}
控制器:
public class TestDataController {
@Autowired
TestService testDataService;
@RequestMapping(value="/app", method=RequestMethod.POST)
public String testDataSubmit(@RequestParam(required=false) Integer contentid, @ModelAttribute TestData testData, Model model, HttpServletRequest request) {
String id = request.getQueryString();
System.out.println("My Id: "+id);//null
System.out.println("URL Parameter: "+testData.getContentid());//0
System.out.println("URL Parameter passed objectid: "+contentid); //null
testDataService.saveTestDataDetails(testData);
return "app";
}
}
服务:
@Service
public class TestService {
@PersistenceContext
private EntityManager entityManager;
public void saveTestDataDetails(TestData testData) {
StoredProcedureQuery sp = entityManager.createStoredProcedureQuery("APP.TESTDATA");
sp.registerStoredProcedureParameter("firstname", String.class, ParameterMode.IN);
sp.registerStoredProcedureParameter("secondname", Integer.class, ParameterMode.IN);
sp.registerStoredProcedureParameter("contentid", Integer.class, ParameterMode.IN);
sp.setParameter("firstname", testData.getFirstname());
sp.setParameter("secondname", testData.getSecondname());
sp.setParameter("contentid", testData.getContentid());
sp.execute();
}
}
【问题讨论】:
-
请提供工作代码示例,例如在您的第二个代码 sn-p 中,没有变量
userComments2。 -
@DominikSandjaja,抱歉我已经更新了,这是我的拼写错误。
-
将 contentid 作为请求参数发送。问题出在哪里?
-
@Patrick,我如何发送 contentid 作为请求参数,我可以知道请获取该值
-
试试这个:
th:action="@{/app?contentid=10}"
标签: java spring spring-mvc spring-boot query-string