thymeleaf怎样获取到springboot fastjson传递的json对象

6704人阅读
spring(10)
提交post对象应该是很简单的,但是掉ajax的坑里去了。
1,首先,HelloWorld.java&代码中加入:
@RequestMapping(value=&/trequest&, method = RequestMethod.POST)
@ResponseBody
public UserInfo trequest(@RequestBody UserInfo pu){
UserInfo u = new UserInfo();
u.setUserCode(pu.getUserCode());
u.setUserName(pu.getUserName());
u.setDeptCode(pu.getDeptCode());
2,在static目录下,新建index.html文件:
&!DOCTYPE html PUBLIC &-//W3C//DTD XHTML 1.0 Transitional//EN& &http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&&
&meta http-equiv=&Content-Type& content=&text/ charset=utf8& /&
&meta name=&viewport& content=&width=device-width, initial-scale=1&&
&title&json调试器&/title&
&link rel=&stylesheet& href=&jquery/jquery.mobile-1.3.2.min.css&&
&script src=&jquery/jquery-1.8.3.min.js&&&/script&
&script src=&jquery/jquery.mobile-1.3.2.min.js&&&/script&
&div data-role=&page&&
&div data-role=&header&&
&h1&json调试器&/h1&
&div data-role=&content&&
&form method=&post& name=&qform&&
&label for=&qname&&请输入URL:&/label&
&input type=&text& name=&urltext& id=&urltext& value=&http://localhost:8090/trequest& /&
&label for=&qname&&请输入Request内容:&/label&
id=&requesttext&&&/textarea&
&input type=&button& id=&btnPostJson& data-inline=&true& onclick=&postJson();& value=&提交& /&
&label id=&responsttxt&&&/label&
&div data-role=&footer&&
&h4 id=&foottext&&&/h4&
console.log(&come in!&);
function postJson() {
console.log(document.getElementById('requesttext').value);
type : &POST&,
: qform.urltext.value,
cache : false,
data : document.getElementById('requesttext').value,
success : onSuccessResult,
error : onErrorResult
function onSuccessResult(data,status){
console.log(data);
var jsondata = JSON.stringify(data);
console.log(jsondata);
showText(jsondata);
function onErrorResult(xmlhttprequest, textstatus, errorthrown){
//进行错误处理
showText(errorthrown);
function showText(txt) {
var showingtxt = document.getElementById(&responsttxt&);
showingtxt.innerHTML = '&label id=&responsttxt&&' + txt + '&/label&';
&3,这里,前端用了jquery,需要在static目录下,建立子目录:jquery,
然后上传几个jquery文件。文件打包下载:
4,进入页面,点击,报错:
{&timestamp&:0,&status&:415,&error&:&Unsupported Media Type&,&exception&:&org.springframework.web.HttpMediaTypeNotSupportedException&,&message&:&Content type 'application/x-www-form-charset=UTF-8' not supported&,&path&:&/trequest&}
5,原来,ajax做post的时候,默认是Content type 'application/x-www-form-charset=UTF-8'
在“$.ajax({&”之前,需要加上:
$.ajaxSetup({
contentType : 'application/json'
然后访问:
http://localhost:8090/
request内容填入:
{&userCode&:&h002&,&userName&:&u name&}
可以得到结果:
{&userCode&:&h002&,&userName&:&u name&,&deptCode&:null}
搞定,打完收功!
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:779449次
积分:5170
积分:5170
排名:第5297名
原创:54篇
评论:423条
(2)(4)(7)(2)(1)(5)(3)(19)(17)Spring Boot集成thymeleaf/Jsp, 热部署以及注意点 - 简书
Spring Boot集成thymeleaf/Jsp, 热部署以及注意点
源码地址::scuhzq/springbootjsporthyme.git
1,Spring Boot框架搭建。
简介Springboot,简单来说,就是牺牲项目的自由度来减少配置的复杂度。1,比如Application.java的放置位置(application.java 文件不能直接放在main/java文件夹下,必须要建一个包把他放进去。),html、static、properties、test文件等目录位置固定。2,内置了tomcat服务器,不需要额外搭建。3,构建rest API。使用@RestController注解。 ==
@Controller + @ResponseBody当我们后台写一些数据接口,就可以借助它来编写restful风格的api。4,restful架构,是一种规范,或者说一种命名风格。简单的比如添加、删除、获取信息、获取列表等,/book/add、/book/delete、/book/{id}/info、/book/list等。5,推荐几个工具。测试接口:postmanIDE:IDEA项目依赖管理:gradle(非xml格式的)文档书写:markdown (MacDown, mac系统)文本工具:Sublime
1)官网下载项目框架代码。
Paste_Image.png
2)选择指定的构建环境,项目组以及项目名, 选择项目依赖(可选)。
Paste_Image.png
3)将框架代码导入IDE。推荐使用IDEA工具。
Paste_Image.png
Paste_Image.png
构建项目的时候,最好开个代理,或者能翻墙的网络。推荐个工具,Shadowsocks
Paste_Image.png
4)项目结构
1,java:业务代码。2,springboot的启动类,(直接放在group路径下,com.hzq)。eg:Controller、Service、DAO中。3, static放置静态资源。js,images等。templates放置模板(页面)。推荐使用thymeleaf,也可以集成Jsp。
Paste_Image.png
Paste_Image.png
Paste_Image.png
5)启动Spring boot项目。(Springboot内置了tomcat,已bootRun的方式启动即可。)
Paste_Image.png
找不到gradle。
Paste_Image.png
1,对于项目部署到服务器上的。./gradlew bootRun &(&表示以进程后台方式运行,关闭当前session,不会停止运行。)2,也可以将springboot项目打war包,然后(写部署脚本)部署到tomcat中。
6)有的小伙伴忘记关闭代理, 这时候访问localhost:8080或者120.0.0.1:8080可能会访问不了,ERR_EMPTY_RESPONSE。
2,SpringBoot集成Thymeleaf。
1)依赖引入。compile('org.springframework.boot:spring-boot-starter-thymeleaf')2)配置文件。spring.thymeleaf.cache=false//用于页面热部署。spring.thymeleaf.encoding=utf-8spring.thymeleaf.mode=HTML5server.port=80093)配置文件可以使用application.propertiesspring.profiles.active=local //指定使用哪个配置文件。 正常情况下,local、dev、prod的配置文件是不同的。application-local.propertiesapplication-dev.propertiesapplication-prod.properties4)Springboot页面热部署。
&groupId&org.springframework.boot&/groupId&
&artifactId&spring-boot-maven-plugin&/artifactId&
&configuration&
&fork&true&/fork&
&/configuration&
&/plugins&&/build&
gradlebootRun {
addResources = true}
3,springboot集成jsp。
1)添加依赖。compile('org.apache.tomcat.embed:tomcat-embed-jasper')添加jsp支持的类。2)配置文件application.properties文件加上如下配置。spring.mvc.view.prefix=/WEB-INF/jsp/spring.mvc.view.suffix=.jsp3)在webapp下建立目录。/WEB-INF/jsp/resources
资源文件夹引用资源。
&c:set var="ctx" value="${pageContext.request.contextPath}/resources"/&4) 将thymeleaf相关的依赖以及配置去掉。
1)基于maven和gradle来构建的项目,会涉及到group以及artifact。
项目eg: mons
1, group一般指定域。org.apache就是这个项目的group。指定了项目的域。我们命名一般是pany(公司名称)。
2,artifact一般指定项目名。命名代表项目的含义。
3,当把项目发布到maven仓库中的时候,我们需要通过『坐标』来找到该项目。例如 pany1.test项目。
2)本地项目提交到github。
Paste_Image.png
Paste_Image.png
1,git init
2,git add
3,git commit
4,与github建立关联。git remote add origin :scuhzq/springbootjsporthyme.git
5,git push -u origin master
Paste_Image.pngspring-boot-web-ui及thymeleaf基本使用 -
- ITeye博客
博客分类:
视图控制层代码demo如下:
@Controller
@RequestMapping("/")
public class MessageController {
private final MessageRepository messageR
@Autowired
public MessageController(MessageRepository messageRepository) {
this.messageRepository = messageR
@RequestMapping
public ModelAndView list() {
Iterable&Message& messages = this.messageRepository.findAll();
return new ModelAndView("messages/list", "messages", messages);
@RequestMapping("{id}")
public ModelAndView view(@PathVariable("id") Message message) {
return new ModelAndView("messages/view", "message", message);
@RequestMapping(params = "form", method = RequestMethod.GET)
public String createForm(@ModelAttribute Message message) {
return "messages/form";
@RequestMapping(method = RequestMethod.POST)
public ModelAndView create(@Valid Message message, BindingResult result,
RedirectAttributes redirect) {
if (result.hasErrors()) {
return new ModelAndView("messages/form", "formErrors", result.getAllErrors());
message = this.messageRepository.save(message);
redirect.addFlashAttribute("globalMessage", "Successfully created a new message");
return new ModelAndView("redirect:/{message.id}", "message.id", message.getId());
@RequestMapping("foo")
public String foo() {
throw new RuntimeException("Expected exception in controller");
注:@Controller:1:spring的控制层。2:spring的注解之一放在类名之前3:spring配置文件中如果配置了扫描包路径,自动检测该注释的类并注入。4:spring控制层可以接收请求,并且返回响应。
@RequestMapping:用户请求路径是http://localhost:8080/项目名/类的@RequestMapping的value值/方法的@RequestMapping的value值。
@Autowired:依赖注入。
@PathVariable:rest访问方式获取参数传递
ModelAndView:一次性返回model和view2个对象,有7个构造函数,用来设定返回对象和视图,也可以用set方法设置。
@ModelAttribute:获取页面传递参数。也可以这样用
@ModelAttribute("user")
public User addAccount() {
return new User("jz","123");
@RequestMapping(value = "/helloWorld")
public String helloWorld(@ModelAttribute("user") User user) {
user.setUserName("jizhou");
return "helloWorld";
@SessionAttributes("user")用户同上只是使用范围不同而已。
RedirectAttributes:我的理解是controller控制层跳转到控制层传递参数用的。
@Valid:对实体类的一个验证。验证符合jpa的标准。要和BindingResult result配合使用,如果验证不通过的话,result.hasErrors(),跳转 。如一个实体类标准:
import javax.validation.constraints.M
import javax.validation.constraints.NotN
import org.hibernate.validator.constraints.NotB
public class User {
@NotBlank(message="用户名不能为空")
public String getUsername() {
public void setUsername(String username) {
this.username =
@NotNull(message="密码不能为null")
public String getPassword() {
public void setPassword(String password) {
this.password =
@Min(value=10, message="年龄的最小值为10")
public int getAge() {
public void setAge(int age) {
this.age =
最后个方法就是抛出页面异常.
html主要用ThyMeleaf标签,Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fern&ndez创建,该作者还是Java加密库Jasypt的作者。
form.html代码如下:
&!DOCTYPE html&
&html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
layout:decorator="layout"&
&title&Messages : Create&/title&
&h1 layout:fragment="header"&Messages : Create&/h1&
&div layout:fragment="content"
class="container"&
&form id="messageForm"
th:action="@{/(form)}"
th:object="${message}"
action="#"
method="post"&
&div th:if="${#fields.hasErrors('*')}"
class="alert alert-error"&
&p th:each="error : ${#fields.errors('*')}"
th:text="${error}"&
Validation error
&div class="pull-right"&
&a th:href="@{/}" href="messages.html"&
&label for="summary"&Summary&/label&
&input type="text"
th:field="*{summary}"
th:class="${#fields.hasErrors('summary')} ? 'field-error'"/&
&label for="text"&Message&/label&
th:field="*{text}"
th:class="${#fields.hasErrors('text')} ? 'field-error'"&&/textarea&
&div class="form-actions"&
&input type="submit" value="Create"/&
list.html代码如下:
&!DOCTYPE html&
&html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
layout:decorator="layout"&
&title&Messages : View all&/title&
&h1 layout:fragment="header"&Messages : View all&/h1&
&div layout:fragment="content" class="container"&
&div class="pull-right"&
&a href="form.html" th:href="@{/(form)}"&Create Message&/a&
&table class="table table-bordered table-striped"&
&td&ID&/td&
&td&Created&/td&
&td&Summary&/td&
&tr th:if="${messages.empty}"&
&td colspan="3"&
No messages
&tr th:each="message : ${messages}"&
&td th:text="${message.id}"&1&/td&
&td th:text="${#calendars.format(message.created)}"&
July 11, :16 PM CDT
&a href="view.html"
th:href="@{'/' + ${message.id}}"
th:text="${message.summary}"&
The summary
view.html代码如下:
&html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
layout:decorator="layout"&
&title&Messages : View&/title&
&h1 layout:fragment="header"&Messages : Create&/h1&
&div layout:fragment="content"
class="container"&
&div class="alert alert-success"
th:if="${globalMessage}"
th:text="${globalMessage}"&
Some Success message
&div class="pull-right"&
&a th:href="@{/}" href="list.html"&
&dt&ID&/dt&
&dd id="id" th:text="${message.id}"&123&/dd&
&dt&Date&/dt&
&dd id="created"
th:text="${#calendars.format(message.created)}"&
July 11, :16 PM CDT
&dt&Summary&/dt&
&dd id="summary"
th:text="${message.summary}"&
A short summary...
&dt&Message&/dt&
&dd id="text"
th:text="${message.text}"&
A detailed message that is longer than the summary.
注th标签的引用就是首先要注入标签头,xmlns:th="http://www.thymeleaf.org"放入html标签内就可以了,
# 代表 获取对象 从 messages bundle 也就是消息的资源本地化文件
$ 表示从model里面获取
&div class="col-sm-9"&
&input type="text" th:field="*{id}" placeholder="Order Id" class="col-xs-10 col-sm-5" /&
&p style="color:red" th:if="${#fields.hasErrors('*{id}')}" th:errors="*{id}"&&/p&
th:fragment=“public” 相当于 include标签
th:each="user : ${users}" 相当于c:foreach
&tr th:each="user : ${users}"&
&td th:text="${user.id}"&01&/td&
&td th:text="${user.name}"&朱遇平&/td&
&td th:text="${user.xx}"&java&/td&
&td th:text="${user.xx}"&程序员&/td&
th:href="@{/}"动态设置url参数
&form action="#" th:action="@{/users/add}" th:object="${myuser}" method="post"&
这里th:Object表示表单与 改myuser注入的实体映射,
在表单 th:field="*{id} 则表示 该表单的值 与 myuser的id绑定
th:if="${#fields.hasErrors('*')}"
th:if="${#strings.isEmpty(status)}"
${not #strings.isEmpty(status)}
if判断显示。
&div class="col-sm-9"&
&input type="text" th:field="*{id}" placeholder="Order Id" class="col-xs-10 col-sm-5" /&
&p style="color:red" th:if="${#fields.hasErrors('*{id}')}" th:errors="*{id}"&&/p&
th:errors错误信息显示如上图。
浏览 45630
[b][b][b]TTTTTTTTTTT[/b][/b][/b]
jishiweili
浏览: 174032 次
来自: 成都
引用[b][b][b]TTTTTTTTTTT[/b][/b][ ...
楼主写的很清晰,这种开发模式如果熟悉的话可以快速的开发应用系统 ...
JPA的实现hibernate唯一恶心的就是设置数据库众多关系 ...springboot整合thymeleaf老是提示下面的错误,请大神指点
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Aug 03 11:42:15 GMT+08:00 2016
There was an unexpected error (type=Not Found, status=404).
No message available
是要支持jsp 嘛 ···同问···
--- 共有 1 条评论 ---
支持thymeleaf,不过已经解决了,之前用的parent版本是1.25,有很多thymeleaf的jar包没有引进来。不过非常感谢。
可以试试魔方网表。有HTML5模块,我试了一下,很好上手。前台json传送到后台,自动装配成对象,spring支持这么做么? - ITeye问答
& 现在有一个产品添加页面,前台用过jquery获取数据,拼装成一个json,和产品的bean是相对应的,我后台如何获取json数据,并自动装配成产品对象?spring支持这么做么?如何做?
spring mvc提供了默认的解决方案
在mvc config中配置
&bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&
&property name="messageConverters"&
&bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /&
&/property&
在controller中
@RequestMapping(value="/{id}", method = RequestMethod.PUT)
@ResponseBody
public Map update(@PathVariable final Object id, @RequestBody final Map&String, Object& map, HttpServletRequest request) {
Map&String,Object& ret = new HashMap&String,Object&();
at1943前台json传送到后台,自动装配成对象,spring支持这么做么?
ajax提交的时候会将json对象转为key=value的形式,springmvc中的方法只要将对应的bean作为入参即可自动接收。
like this
$.post("/u",{name:"xiaoming",age:99},function(){alert("complate");});
@requstmapping(value="/u",method=requestmethod.post)
public string submit(User user){
...
}
class user{
可以使用 json-lib 或者 Gson 都可以将json封装成类或者将javabean专程json
Gson的例子
&&&& Gson gson = new Gson();
&&&& InterfaceResult result = gson.fromJson(jsonstring, new TypeToken&InterfaceResult&() {}.getType());
&&&& System.out.println(result.getMessage());
public class InterfaceResult implements Serializable {
private S&&& //结果代码
private S //结果消息
private List&Map&String, Object&&& //返回数据
* @return the code
public String getCode() {
* @param code the code to set
public void setCode(String code) {
this.code =
* @return the message
public String getMessage() {
* @param message the message to set
public void setMessage(String message) {
this.message =
* @return the data
public List&Map&String, Object&& getData() {
* @param data the data to set
public void setData(List&Map&String, Object&& data) {
this.data =
'type'&&&&&&& : 'post',
'contentType' : 'application/charset=UTF-8',
'data'&&&&&&& : JSON.stringify(JsonObject),
其中JsonObject就是你组装的JSON对象
@RequestMapping(value = "/query", method = RequestMethod.POST)
@ResponseBody
public Map query(@RequestBody QueryVO queryVO) {
&& ...
}
其中:
1、必须是POST方式
2、前台需要设置'contentType'
3、前台JSON对象要转成字符串,如JSON.stringify(JsonObject),
4、后台参数得用@RequestBody 注解
5、如果你是异步处理返回的JSON值(比如Map等)则@ResponseBody是需要的
6、这个时候,你的JsonObject 就会自动转为queryVO这个Bean
基本原理都是这样,在后台读取前台传过来的字符串,然后再解析为对应的bean.如果使用框架的话,只是它帮忙做了这个转换的过程而已。至于字符串转bean,3楼的就是答案。
直接发送Task属性名即可
key:value
@RequestMapping(value="editJob.htm",method=RequestMethod.POST)
@ResponseBody
public void editJob(HttpServletResponse response,Task task){}
Spring MVC的Controller自带此功能,前台传入的json对象与后台定义的bean结构一致,比如:
@RequestMapping(value="/xxx/xxx",method=RequestMethod.POST)
@ResponseBody
public Object xxx(@RequestBody TurnoverRecord record,
HttpServletRequest request, HttpServletResponse response){
可以通过json-org.jar 来做这个。
JSONObject jsonO
JSONArray jsonArr =
jsonObj = new JSONObject(json);
String boxes = jsonObj.getString("xxx");
jsonArr = new JSONArray(boxes);
StringBuffer jsonDeconded = new StringBuffer("{'xxxx':[");
for (int i = 0; i & jsonArr.length(); i++) {
这是我们解析的部分代码。
将json字符串整体作为一个参数传递给后台,后台接收到后再通过第三方jar包进行解析。
好像可以通过json-lib包实现
已解决问题
未解决问题

我要回帖

更多关于 springboot fastjson 的文章

 

随机推荐