springbootshiro boot 页面参数传递到了controller,后台输出也执行了,但没有保存到数据库。

博客分类:
个人学习参考所用,勿喷!
1) 用Maven构建web项目:
构建过程参考limingnihao的blog(写得相当的详细!!!):
注解@ResponseBody可以将结果(一个包含字符串和JavaBean的Map),转换成JSON。由于Spring是采用对JSON进行了封装的jackson来生成JSON和返回给客户端,所以这里需要添加jackson的相关包。项目的pom.xml配置如下:
&project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&
&modelVersion&4.0.0&/modelVersion&
&groupId&com.watson&/groupId&
&artifactId&rest-spring&/artifactId&
&packaging&war&/packaging&
&version&0.0.1-SNAPSHOT&/version&
&name&rest-spring Maven Webapp&/name&
&url&http://maven.apache.org&/url&
&dependencies&
&!-- 省略其他配置,具体可以参考附件--&
&dependency&
&groupId&org.codehaus.jackson&/groupId&
&artifactId&jackson-mapper-asl&/artifactId&
&version&1.4.2&/version&
&/dependency&
&dependency&
&groupId&org.codehaus.jackson&/groupId&
&artifactId&jackson-core-asl&/artifactId&
&version&1.4.2&/version&
&/dependency&
&/dependencies&
&/project&
2) 在web.xml配置Spring的请求处理的Servlet,具体设置:
&?xml version="1.0" encoding="UTF-8"?&
&web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5"&
&display-name&Spring-Rest&/display-name&
&servlet-name&rest&/servlet-name&
&servlet-class&org.springframework.web.servlet.DispatcherServlet&/servlet-class&
&init-param&
&param-name&contextConfigLocation&/param-name&
&param-value&/WEB-INF/rest-servlet.xml&/param-value&
&/init-param&
&load-on-startup&1&/load-on-startup&
&/servlet&
&servlet-mapping&
&servlet-name&rest&/servlet-name&
&url-pattern&/&/url-pattern&
&/servlet-mapping&
&/web-app&
3) 在rest-servlet.xml中配置如下:
&beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"&
&context:component-scan base-package="com.mkyong.common.controller" /&
&mvc:annotation-driven /&
为了解决乱码问题,需要添加如下配置,并且这里可以显示的添加MappingJacksonHttpMessageConverter这个转换器。
&bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&
&property name="messageConverters"&
&bean class="org.springframework.http.converter.StringHttpMessageConverter"&
&property name="supportedMediaTypes"&
&value&text/charset=UTF-8&/value&
&/property&
&bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /&
&/property&
4) 编写自己的服务组件类,使用MVC的annotation风格,使用
@ResponseBody处理返回值。具体代码如下:
@RequestMapping("/jsonfeed")
public @ResponseBody Object getJSON(Model model) {
List&TournamentContent& tournamentList = new ArrayList&TournamentContent&();
tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "World Cup", "www.fifa.com/worldcup/"));
tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "U-20 World Cup", "www.fifa.com/u20worldcup/"));
tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "U-17 World Cup", "www.fifa.com/u17worldcup/"));
tournamentList.add(TournamentContent.generateContent("中超", new Date(), "中超", "www.fifa.com/confederationscup/"));
model.addAttribute("items", tournamentList);
model.addAttribute("status", 0);
5)将运行项目,在浏览器中输入http://[host]:[port]/[appname]/jsonfeed.json,例如楼主的实例中输入如下:http://localhost:7070/rest-spring/jsonfeed/,得到结果为:
{"status":0,"items":[{"name":"World Cup","id":8,"link":"www.fifa.com/worldcup/","author":"FIFA","publicationDate":0},{"name":"U-20 World Cup","id":9,"link":"www.fifa.com/u20worldcup/","author":"FIFA","publicationDate":0},{"name":"U-17 World Cup","id":10,"link":"www.fifa.com/u17worldcup/","author":"FIFA","publicationDate":0},{"name":"Confederations Cup","id":11,"link":"www.fifa.com/confederationscup/","author":"FIFA","publicationDate":0}]}
这里我们也可以利用Spring3MVC中对试图和内容协商的方法来处理返回JSON的情况,下面步骤接上面第2步:
3) 在rest-servlet.xml中对相关进行具体的设置:
&?xml version="1.0" encoding="UTF-8"?&
&beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"&
&!-- 自动搜索@Controller标注的类,包括其下面的子包 --&
&context:component-scan base-package="com.watson.rest" /&
&!-- 根据客户端的不同的请求决定不同的view进行响应, 如 /blog/1.json /blog/1.xml --&
&bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"&
&!-- 设置为true以忽略对Accept Header的支持 --&
&property name="ignoreAcceptHeader" value="true" /&
&!-- 在没有扩展名时即: "/blog/1" 时的默认展现形式 --&
&property name="defaultContentType" value="text/html" /&
&!-- 扩展名至mimeType的映射,即 /blog.json =& application/json --&
&property name="mediaTypes"&
&entry key="html" value="text/html" /&
&entry key="pdf" value="application/pdf" /&
&entry key="xsl" value="application/vnd.ms-excel" /&
&entry key="xml" value="application/xml" /&
&entry key="json" value="application/json" /&
&/property&
&!-- 用于开启 /blog/123?format=json 的支持 --&
&property name="favorParameter" value="false" /&
&property name="viewResolvers"&
&bean class="org.springframework.web.servlet.view.BeanNameViewResolver" /&
&bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"&
&property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /&
&property name="prefix" value="/pages" /&
&property name="suffix" value=".jsp"&&/property&
&/property&
&property name="defaultViews"&
&!-- for application/json --&
&bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" /&
&!-- for application/xml --&
&bean class="org.springframework.web.servlet.view.xml.MarshallingView"&
&property name="marshaller"&
&bean class="org.springframework.oxm.xstream.XStreamMarshaller"/&
&/property&
&/property&
4)编写自己的服务组件类,使用MVC的annotation风格,这里可以不再使用@ResponseBody断言。具体代码如下:
package com.watson.rest.
import org.springframework.stereotype.C
import org.springframework.ui.M
import org.springframework.web.bind.annotation.RequestM
import com.watson.rest.feeds.TournamentC
import java.util.ArrayL
import java.util.D
import java.util.L
@Controller
public class FeedController {
@RequestMapping("/jsonfeed")
public String getJSON(Model model) {
List&TournamentContent& tournamentList = new ArrayList&TournamentContent&();
tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "World Cup", "www.fifa.com/worldcup/"));
tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "U-20 World Cup", "www.fifa.com/u20worldcup/"));
tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "U-17 World Cup", "www.fifa.com/u17worldcup/"));
tournamentList.add(TournamentContent.generateContent("FIFA", new Date(), "Confederations Cup", "www.fifa.com/confederationscup/"));
model.addAttribute("items", tournamentList);
model.addAttribute("status", 0);
return "jsontournamenttemplate";
这里的TournamentContent是自定义的POJO类:
public class TournamentContent {
private static int idCounter = 0;
private Date publicationD
public static TournamentContent generateContent(String author, Date date, String name, String link) {
TournamentContent content = new TournamentContent();
content.author =
content.publicationDate =
content.name =
content.link =
content.id = idCounter++;
//省略getter、setter
5)将运行项目,在浏览器中输入http://[host]:[port]/[appname]/jsonfeed.json,例如楼主的实例中输入如下:http://localhost:7070/rest-spring/jsonfeed.json,得到结果为:
{"status":0,"items":[{"name":"World Cup","id":8,"link":"www.fifa.com/worldcup/","author":"FIFA","publicationDate":0},{"name":"U-20 World Cup","id":9,"link":"www.fifa.com/u20worldcup/","author":"FIFA","publicationDate":0},{"name":"U-17 World Cup","id":10,"link":"www.fifa.com/u17worldcup/","author":"FIFA","publicationDate":0},{"name":"Confederations Cup","id":11,"link":"www.fifa.com/confederationscup/","author":"FIFA","publicationDate":0}]}
至此,Spring RESTful服务返回JSON的实践基本完成(因为这里对EXCEPTION的处理还够)。个人认为第一种方式更加适合一般的使用,特别是显示的添加MappingJacksonHttpMessageConverter这个转换器和对乱码的处理。
使用 @RequestBody 注解前台只需要向 Controller 提交一段符合格式的 JSON,Spring 会自动将其拼装成 bean。
1)在上面的项目中使用第一种方式处理返回JSON的基础上,增加如下方法:
@RequestMapping(value="/add",method=RequestMethod.POST)
@ResponseBody
public Object addUser(@RequestBody User user)
System.out.println(user.getName() + " " + user.getAge());
return new HashMap&String, String&().put("success", "true");
这里的POJO如下:
public class User {
//getter setter
2)而在前台,我们可以用 jQuery 来处理 JSON。从这里,我得到了一个 jQuery 的插件,可以将一个表单的数据返回成JSON对象:
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function(){
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
o[this.name].push(this.value || '');
o[this.name] = this.value || '';
以下是使用 jQuery 接收、发送 JSON 的代码:
$(document).ready(function(){
jQuery.ajax({
type: 'GET',
contentType: 'application/json',
url: 'jsonfeed.do',
dataType: 'json',
success: function(data){
if (data && data.status == "0") {
$.each(data.data, function(i, item){
$('#info').append("姓名:" + item.name +",年龄:" +item.age);
error: function(){
alert("error")
$("#submit").click(function(){
var jsonuserinfo = $.toJSON($('#form').serializeObject());
jQuery.ajax({
type: 'POST',
contentType: 'application/json',
url: 'add.do',
data: jsonuserinfo,
dataType: 'json',
success: function(data){
alert("新增成功!");
error: function(){
alert("error")
但是似乎用Spring这套东西真是个麻烦的事情,相对Jersey对RESTful的实现来看,确实有很多不简洁的地方。
官方文档:
badqiu的BOLG:
liuweifeng的BOLG
Gary Mark等的书籍:《Spring Recipes》2ed
下载次数: 1694
浏览 98029
有一个小问题,就是配置默认的视图MappingJacksonJsonView的时候,报错:Could not instantiate bean class [org.springframework.web.servlet.view.json.MappingJacksonJsonView]: Constru nested exception is java.lang.NoClassDefFoundError: org/codehaus/jackson/Versioned& 可是查看文档,这个类本来就是一个无参数的构造方法,这是什么情况&
jackson-all-1.8.10.jar 缺少这个包
有一个小问题,就是配置默认的视图MappingJacksonJsonView的时候,报错:Could not instantiate bean class [org.springframework.web.servlet.view.json.MappingJacksonJsonView]: Constru nested exception is java.lang.NoClassDefFoundError: org/codehaus/jackson/Versioned& 可是查看文档,这个类本来就是一个无参数的构造方法,这是什么情况& 你好,这是个没有找到类的BUG,很常见。原因是没有加入需要的jar,或者jar的版本不对。
浏览: 828854 次
来自: 上海
baseservice、dao代码是同一个,但是实例配置多个, ...
写得不错,望楼主再接再厉
psubscribe对我有用
js中怎么调用配置文件的参数呢
ws715 写道如果文件内容一致,后面的会覆盖前面的配置吗肯定 ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'无意中发现对于时间字符串转Date类,根本不用自己去写转换类,spring mvc已经实现了该功能,还是基于注解的,轻松省事,使用org.springframework.format.support.FormattingConversionServiceFactoryBean
之后,只要在vo里加注解就行了
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date dateRangeS// 通行日期范围开始
@DateTimeFormat(pattern="yyyy-MM-dd") 可将形如的字符串转换到Date类
@NumberFormat(pattern="#,###.##") 可将形如4,500.00的字符串转换成long类型
怎么注册呢?
&bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean"&
&mvc:annotation-driven validator="validator"
conversion-service="conversionService" /&
使用&mvc:annotation-driven /& 的话,默认就启用FormattingConversionServiceFactoryBean了,所以上面的配置也省了。
但是&mvc:annotation-driven /&基本不用,因为总得做些个性化设置,那怎么注册FormattingConversionServiceFactoryBean给spring mvc呢?
起初我以为得从DefaultAnnotationHandlerMapping入手,后来通过看&mvc:annotation-driven /&的解析器AnnotationDrivenBeanDefinitionParser源码,才发现原来是AnnotationMethodHandlerAdapter的属性
RuntimeBeanReference conversionService = getConversionService(element, source, parserContext);
RuntimeBeanReference validator = getValidator(element, source, parserContext);
RootBeanDefinition bindingDef = new RootBeanDefinition(ConfigurableWebBindingInitializer.class);
bindingDef.setSource(source);
bindingDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
bindingDef.getPropertyValues().add("conversionService", conversionService);
bindingDef.getPropertyValues().add("validator", validator);
RootBeanDefinition annAdapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class);
annAdapterDef.setSource(source);
annAdapterDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
annAdapterDef.getPropertyValues().add("webBindingInitializer", bindingDef);
annAdapterDef.getPropertyValues().add("messageConverters", getMessageConverters(source));
getConversionService方法内部
if (element.hasAttribute("conversion-service")) {
return new RuntimeBeanReference(element.getAttribute("conversion-service"));
RootBeanDefinition conversionDef = new RootBeanDefinition(FormattingConversionServiceFactoryBean.class);
conversionDef.setSource(source);
conversionDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
String conversionName = parserContext.getReaderContext().registerWithGeneratedName(conversionDef);
parserContext.registerComponent(new BeanComponentDefinition(conversionDef, conversionName));
return new RuntimeBeanReference(conversionName);
原来&mvc:annotation-driven /&是这么注册FormattingConversionServiceFactoryBean的
如果不使用&mvc:annotation-driven /&标签的话,只要配置AnnotationMethodHandlerAdapter的属性就可以了
&property name="webBindingInitializer"&
&bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"&
&property name="conversionService"&
&bean class="org.springframework.format.support.FormattingConversionServiceFactoryBean"&&/bean&
&/property&
&/property&
浏览 56413
浏览: 191486 次
来自: 天津
楼上的能不能配置一个简单的例子出来
管用,谢谢!
不错,受用了,也是初学,赞一个
是篇好文章,按照文章做了很多demo,学到了很多东西,子这里谢 ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'关于springboot中Controller调整到JSP的问题
[问题点数:50分]
本版专家分:1
CSDN今日推荐
本版专家分:1
本版专家分:873
本版专家分:0
本版专家分:873
本版专家分:13145
2017年12月 Java大版内专家分月排行榜第二
2017年2月 Java大版内专家分月排行榜第三
本版专家分:415
本版专家分:330
本版专家分:1
匿名用户不能发表回复!
其他相关推荐1.@RequestParam与@PathVariable的区别
共同点:作用都是将请求中的参数值获取到,绑定到controller的相应方法中
不同点:@RequestParam
url: http://xxxxxx/xxx?name=value
@PathVariable
url:http://xxxxx/xxxxx/value
2.@RestController
相当于@Controller+@ResponseBody
使用@RestController的时候,返回应该是一个对象,在没有页面的情况i下,也可以看到一个对象所对应的json字符串,前端只需要对返回的json字符串进行解析就可以。
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
restful风格,restcontroller与controller
初步接触springmvc的时候,被要求使用restful风格,彼时一头雾水,不懂何谓restful,参阅了很多资料,慢慢的接触的也越来越多,如今spring的况且已基本运用熟练,简单谈一下我的一些看法,当然,只是我自己的浅显粗陋的见解,不对的地方还望指正。
restful风格
简单的理解,restful是一种url风格,或者说是规范,在以前的网址中,假定一个业务,取得数据网址为,添加信息的网址为,类似这样。
但是在restful风格中,取得数据和添加数据的网址均应为,方法为get或者post;所以,在restful风格中,一个网址就是一个资源,其形式类似于{id}/{id} ,例如某购物网站,产品有很多种类,每种产品下有很多子类型,那么 代表了联想1103型号电脑,而 代表了2014型号电脑。
在spring mvc中,有@requestparm, @requestbody和@pathvariable 三种注解来获得浏览器端的参数,其中前两者都是由浏览器post提交的参数,而@pathvariable 则是从网址中取得参数;假设代码如下:
@Requestmapping(value="/{category}/{brand}/{id},method=RequestMethod.POST)
public void getbyid(@PathVariable("category") String category
@PathVariable("brand") String brand
@PathVariable("id") String id){
//具体代码略
在上述代码中,访问网址时,则,category为“laptop”,brand为”hp”,id为”1024”;所以说,在restful风格中,一个网址即表示了一个资源。
restcontroller与controller
假定一个user对象,对象有很多属性(name,sex,age,birth,address,tel)
在我的了解中,这二者的区分为:@restcontroller为@controller和@responsebody的结合
在@controller注解中,返回的是字符串,或者是字符串匹配的模板名称,即直接渲染视图,与html页面配合使用的,在这种情况下,前后端的配合要求比较高,java后端的代码要结合html的情况进行渲染,使用model对象(或者modelandview)将user的属性渲染到页面;
java示例代码如下:
@Controller
@RequestMapping(method = RequestMethod.GET, value = "/")
public String getuser(Model model) throws IOException {
model.addAttribute("name",bob);
model.addAttribute("sex",boy);
return "user";
对应的html代码:
而在@restcontroller中,返回的应该是一个对象,即return一个user对象,这时,在没有页面的情况下,也能看到返回的是一个user对象对应的json字符串,而前端的作用是利用返回的json进行解析渲染页面,java后端的代码比较自由。
java端代码:
@RestController
@RequestMapping(method = RequestMethod.GET, value = "/")
public User getuser( ) throws IOException {
User bob=new User();
bob.setName("bob");
bob.setSex("boy");
访问网址得到的是json字符串{“name”:”bob”,”sex”:”boy”},前端页面只需要处理这个字符串即可。
http://blog.csdn.net/pinebud55/article/details/?locationNum=12
spring boot 中@Autowired注解无法自动注入的错误
SpringBoot中的注解使用
SpringBoot中常见注解含义总结
没有更多推荐了,& 著作权归作者所有
人打赏支持
码字总数 16951
前言 在Spring 4推出来之前,我们的编码是存在一些问题,比如:大量的xml配置存在项目中,配置相当繁琐;整合第三方框架非常麻烦;开发效率和部署效率不高等问题。正是因为这些问题,Spring开...
springboot + shiro 权限注解、请求乱码解决、统一异常处理 前篇 后台权限管理系统 相关: spring boot + mybatis + layui + shiro后台权限管理系统 springboot + shiro之登录人数限制、登录...
SpringBoot是基于spring框架衍生的一种新的微服务框架,如果对Spring有一定了解的同学肯定知道在Spring中需要配置各种xml文件完成bean的注册操作,随着服务越来越多,配置就变得越来越复杂,...
概述 该项目包含springBoot-example-ui 和 springBoot-example,分别为前端与后端,前后端分离,利用ajax交互。 前端html 技术: + + + + 该项目git地址:https://github.com/jiangcaijun/sp...
开源小菜鸟2333
一、为什么会诞生SpringBoot? 先看看spring的优势: 1、代码解耦、简化开发:代码中不再需要new去构造对象,而是交由spring去管理对象。 2、支持AOP:面向切面的编程,方便进行权限拦截、日...
没有更多内容
加载失败,请刷新页面
参考网页 https://www.linux178.com/web/httprequest.html 分析背景 服务器以SpringBoot(tomcat为web服务器)为例。 Tomcat作为web服务器,也作为一个Servlet容器,装载了SpringMVC作为Ser...
深度学习目前是一个非常活跃的领域---每天都会有许多应用出现。进一步学习Deep Learning最好的方法就是亲自动手。尽可能多的接触项目并且尝试自己去做。这将会帮助你更深刻地掌握各个主题,成...
package com.yh.emmm.public class Prototype implements Cloneable {
public void setName(String name) {
this.name = ......
新增的类用到gson-1.7.2.jar包,所以编译报错,以前也引入了该jar包,仅仅是用于测试阶段而已。 解决办法: 去掉&scope&test&/scope&即可 &dependency& &groupId&com.google.code.gson&/grou......
首先将HTML结构搭建好: &div id="container"& &div id="list" style="left: -600"& &img src="img/5.jpg" alt="1"/& &img src="img/1.jpg" alt="1"/& &img src="img/2.jpg" alt="2"/& &im......
没有更多内容
加载失败,请刷新页面
文章删除后无法恢复,确定取消删除此文章吗?
亲,自荐的博客将通过私信方式通知管理员,优秀的博客文章审核通过后将在博客推荐列表中显示
确定推荐此文章吗?
确定推荐此博主吗?
聚合全网技术文章,根据你的阅读喜好进行个性推荐
指定官方社区
深圳市奥思网络科技有限公司版权所有

我要回帖

更多关于 springboot入门 的文章

 

随机推荐