springMVC入门二
一、准备工作
参考springMVC入门一,搭建maven项目如下:
前台结构如下:
项目介绍:使用springMVC实现前后台数据交互,例如controller返回json,页面传入pojo
二、具体代码
controller类:HelloWorldController
- package com.cn.project.controller;
- import java.util.ArrayList;
- import java.util.List;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
- import com.cn.common.Result;
- import com.cn.project.entity.TProjectInfo;
- @Controller
- public class HelloWorldController {
- /**
- * 返回json
- * 1、@ResponseBody
- * 2、引入 jackson包
- * 3、配置spring json转换器、或者spring驱动注解 <mvc:annotation-driven/>
- * @param model
- * @return
- */
- @RequestMapping("/hello1") //访问http://localhost:8080/HelloSpringMVC/hello1
- @ResponseBody
- public List<TProjectInfo> query(Model model){
- List<TProjectInfo> projectInfos = new ArrayList<TProjectInfo>();
- projectInfos.add(new TProjectInfo("1", "项目1"));
- projectInfos.add(new TProjectInfo("2", "项目2"));
- projectInfos.add(new TProjectInfo("3", "项目3"));
- projectInfos.add(new TProjectInfo("4", "项目4"));
- projectInfos.add(new TProjectInfo("5", "项目5"));
- return projectInfos; //前台接收:response.data
- }
- /**
- * 封装返回值与自定义状态码
- * @param model
- * @return
- */
- @RequestMapping("/hello2") //访问http://localhost:8080/HelloSpringMVC/hello2
- @ResponseBody
- public Result query2(Model model){
- List<TProjectInfo> projectInfos = new ArrayList<TProjectInfo>();
- projectInfos.add(new TProjectInfo("1", "项目1"));
- projectInfos.add(new TProjectInfo("2", "项目2"));
- projectInfos.add(new TProjectInfo("3", "项目3"));
- projectInfos.add(new TProjectInfo("4", "项目4"));
- projectInfos.add(new TProjectInfo("5", "项目5"));
- return Result.ok().put("data", projectInfos); //前台接收:response.data.data
- }
- /**
- * 前台传入pojo
- * 传入的是pojo的json字符串
- * 如data : angular.toJson($scope.project)
- * data:'{"projectNo":"11","projectName":"22"}'
- * data:JSON.stringify($scope.project)
- * data:$scope.project
- *
- * 注意:@RequestBody json转pojo,pojo一定要有空的构造函数,否则,前台找不到路径
- * "Content-Type": "application/json; charset=UTF-8"
- * @param projectInfo
- * @return
- */
- @RequestMapping("/insert")
- @ResponseBody
- public void insert(@RequestBody TProjectInfo projectInfo){
- System.out.println(projectInfo);
- }
- /**
- * 前台传入 json字符串
- * data:$.param({jsonStr:JSON.stringify($scope.project)}) //后台接收String jsonStr
- *
- * 注意:content-type:application/x-www-form-urlencoded
- *
- * @param jsonStr
- */
- @RequestMapping("/insert2")
- @ResponseBody
- public void insert2(String jsonStr){
- System.out.println(jsonStr);
- }
- /**
- * 返回字符串
- * @param model
- * @return
- */
- @RequestMapping("/hello") //访问http://localhost:8080/HelloSpringMVC/hello
- public String hay(Model model){
- model.addAttribute("greeting","hello Spring MVC"); //jsp页面接收 ${greeting}
- return "index"; //跳转到 index.html 页面需要遵循 spring视图配置
- }
- }
html页面:project.html
- <!DOCTYPE html>
- <html>
- <head>
- <!-- 兼容edge页面 -->
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <title>Insert title here</title>
- <link href="../css/bootstrap.min.css" rel="stylesheet">
- </head>
- <body data-ng-app="projectApp" data-ng-controller="projectCtrl">
- <div class="container-fluid" ng-if="cx">
- <!-- 面包屑 -->
- <ol class="breadcrumb">
- <li><a href="#">Home</a></li>
- <li><a href="#">人员管理</a></li>
- <li class="active">人员查询</li>
- </ol>
- <!-- 查询条件 -->
- <form class="form-inline" role="form">
- <div class="form-group">
- <label for="" class="control-label">姓名:</label> <input type="text"
- class="form-control" id="" placeholder="" ng-model="usreName">
- </div>
- <div class="form-group">
- <label for="" class="control-label">身份证号:</label> <input type="text"
- class="form-control" id="" placeholder="" ng-model="passPort">
- </div>
- <div class="form-group">
- <button type="button" class="btn btn-success" ng-click="query()">查询</button>
- <button type="reset" class="btn btn-success" ng-click="reset()">重置</button>
- </div>
- <div class="form-group">
- <button type="button" class="btn btn-success" ng-click="add()">新增</button>
- </div>
- </form>
- <!-- 查询结果 -->
- <div class="row-fluid">
- <div class="span12">
- <table class="table">
- <thead>
- <tr>
- <th>编号</th>
- <th>项目号</th>
- <th>项目名称</th>
- </tr>
- </thead>
- <tbody>
- <tr data-ng-repeat="x in dataItems" repeat-finish href="#">
- <td ng-bind="$index + 1"></td>
- <td>
- <div ng-bind=x.projectNo></div>
- </td>
- <td>
- <div ng-bind=x.projectName></div>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- </div>
- </div>
- <!-- 编辑页 -->
- <div ng-if="xz">
- <form class="form-inline" role="form">
- <div class="form-group">
- <label for="" class="control-label">项目号:</label> <input type="text"
- class="form-control" id="" placeholder="" ng-model="project.projectNo">
- </div>
- <div class="form-group">
- <label for="" class="control-label">项目名称:</label> <input type="text"
- class="form-control" id="" placeholder="" ng-model="project.projectName">
- </div>
- </form>
- <div>
- <div class="form-group">
- <button type="button" class="btn btn-success" ng-click="save()">保存</button>
- </div>
- </div>
- </div>
- </body>
- <script src="../js/lib/jquery.min.js"></script>
- <script src="../js/lib/bootstrap.min.js"></script>
- <script src="../js/lib/angular-1.3.1.min.js"></script>
- <script>
- var app = angular.module('projectApp', []);
- app.controller('projectCtrl',function($scope,$http) {
- //变量设置
- $scope.cx = true;
- $scope.project={}; //保证修改页面$scope.project能取到值
- //查询方法
- $scope.query = function() {
- $http(
- {
- method : 'POST',
- headers : {
- "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" //或者application/json x-www-form-urlencoded
- },
- url : '../hello1',
- data :''
- })
- .then(
- function successCallback(response) {
- debugger;
- console.log(response);
- $scope.dataItems = response.data;
- },
- function errorCallback(response) {
- debugger;
- alert("查询失败");
- });
- }
- $scope.add = function(){
- $scope.cx = false;
- $scope.xz = true;
- }
- //保存方法
- $scope.save = function() {
- debugger;
- $http(
- {
- method : 'POST',
- headers : {
- "Content-Type": "application/json; charset=UTF-8" //或者application/json
- },
- url : '../insert',
- //data : angular.toJson($scope.project) //"{"projectNo":"11","projectName":"22"}"
- //data:'{"projectNo":"11","projectName":"22"}'
- //data:$.param({jsonStr:JSON.stringify($scope.project)}) //后台接收String jsonStr,注意:content-type:application/x-www-form-urlencoded
- //data:JSON.stringify($scope.project), //"{"projectNo":"11","projectName":"22"}"
- data:$scope.project
- })
- .then(
- function successCallback(response) {
- debugger;
- alert("新增成功");
- },
- function errorCallback(response) {
- debugger;
- alert("新增失败");
- });
- }
- });
- </script>
- </html>
springMVC配置:spring-mvc-servlet.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.1.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
- <!-- 自动扫描注解 -->
- <context:component-scan base-package="com.cn"/>
- <!--
- 处理静态资源,如img等,这类资源不通过DispatcherServlet转发,由容器自己处理
- <mvc:default-servlet-handler default-servlet-name="所使用的Web服务器默认使用的Servlet名称" />
- 对静态资源文件的访问
- <mvc:resources mapping="/img/**" location="/img/" />
- -->
- <mvc:default-servlet-handler />
- <!-- <mvc:resources /> -->
- <!--
- 使用注解时需要配置这个,springMVC为@Controller分发请求所必须的
- -->
- <mvc:annotation-driven/>
- <!-- <mvc:annotation-driven /> 该配置会默认注入以下两个bean,如果需要对以下bean进行修改,需要显示的注入这两个bean -->
- <!-- <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> -->
- <!-- spring MVC提供的适配器 spring默认加载 (如果不修改默认加载的4类转换器,该bean可不配置)-->
- <!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
- <property name="messageConverters">
- 该适配器默认加载以下4类转换器,spring提供了很多转换器
- <list>
- <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter" />
- <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
- <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
- <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />
- 前台json传后台,否则报415
- <bean class="org.springframework.http.converter.StringHttpMessageConverter" />
- controller返回json
- <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
- <property name="supportedMediaTypes">
- <list>
- <value>application/json;charset=UTF-8</value>
- </list>
- </property>
- </bean>
- </list>
- </property>
- </bean> -->
- <!--
- 视图控制器:
- 如果返回的是视图逻辑名称,如success,那么视图解析器就必须配置
- 如果返回的是真实视图名称,如/index.jsp,那么视图解析器为可选配置
- -->
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/html/" /> <!-- 前缀 -->
- <property name="suffix" value=".html" /> <!-- 后缀 -->
- </bean>
- </beans>
web.xml配置:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5" 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_2_5.xsd" id="WebApp_ID">
- <display-name>HelloSpringMVC</display-name>
- <servlet>
- <!-- 加载springmvc配置: 1、这里的servlet-name默认指向“spring-mvc-servlet.xml” 2、手动指定:<init-param> -->
- <servlet-name>spring-mvc</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <!-- <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc-servlet.xml</param-value>
- </init-param> -->
- <!-- <load-on-startup>:容器启动时,加载这个servlet的顺序 取值:0,1,2,3... 数字越小,越先加载 -->
- <load-on-startup>1</load-on-startup>
- </servlet>
- <!-- url-pattern:servlet访问地址url配置 /* path.endsWith("/*") *. path.starsWith("*.")
- / path.equals("/") 其他 -->
- <servlet-mapping>
- <servlet-name>spring-mvc</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- <!-- 加载其他的xml配置 -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/root-context.xml</param-value>
- </context-param>
- <!-- Spring 监听器 -->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <!-- 页面编码设置 -->
- <filter>
- <filter-name>encodingFilter</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- <init-param>
- <param-name>forceEncoding</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>encodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.html</welcome-file>
- <welcome-file>index.htm</welcome-file>
- <welcome-file>index.jsp</welcome-file>
- <welcome-file>default.html</welcome-file>
- <welcome-file>default.htm</welcome-file>
- <welcome-file>default.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
controller返回封装类:Result.java
- package com.cn.common;
- import java.util.HashMap;
- import java.util.Map;
- /**
- * 返回数据封装类
- *
- */
- public class Result extends HashMap<String, Object> {
- private static final long serialVersionUID = 1L;
- public Result() {
- this.put("code", 0);
- }
- public static Result error() {
- return error(500, "未知异常,请联系管理员");
- }
- public static Result error(String msg) {
- return error(500, msg);
- }
- public static Result error(int code, String msg) {
- Result r = new Result();
- r.put("code", code);
- r.put("msg", msg);
- return r;
- }
- public static Result ok(String msg) {
- Result r = new Result();
- r.put("msg", msg);
- return r;
- }
- public static Result ok(Map<String, Object> map) {
- Result r = new Result();
- r.putAll(map);
- return r;
- }
- public static Result ok() {
- return new Result();
- }
- public Result put(String key, Object value) {
- super.put(key, value);
- return this;
- }
- }
三、页面访问
springMVC入门二的更多相关文章
- SpringMVC入门二: 1规范结构, 2简单整合MyBatis
昨天拿springMVC写的helloworld结构不好, 这次先调整一下体系结构 , 然后简单整合一下MyBatis spring的配置还是以注解为主, 不过MyBatis的映射文件什么的还是拿xm ...
- springMvc 入门二
目的:请求参数接受,输出,常见的注解(在上一篇入门1基础上) 1:请求参数的绑定 1.1绑定的机制 表单中请求参数都是基于key=value的. SpringMVC绑定请求参数的过程是通过把表单提交请 ...
- SpringMVC入门二:SSM整合(spring+springmvc+mybatis)
一.编程步骤 1.引入依赖 spring.springmvc.mybatis.mybatis-spring.mysql.druid.log4j.servlet-api.jstl.fastjson 2. ...
- SpringMvc入门二----HelloWorld
1. 导入需要的架包: 2. 配置web.xml,添加Servlet <servlet> <servlet-name>springmvc</servlet-name> ...
- <SpringMvc>入门二 常用注解
1.@RequestMapping @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME ...
- Spring+SpringMVC+MyBatis深入学习及搭建(十二)——SpringMVC入门程序(一)
转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/6999743.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十一)——S ...
- SpringMVC入门学习(二)
SpringMVC入门学习(二) ssm框架 springMVC 在上一篇博客中,我简单介绍了一下SpringMVC的环境配置,和简单的使用,今天我们将进一步的学习下Springmvc的操作. mo ...
- SpringMVC.入门篇《二》form表单
SpringMVC.入门篇<二>form表单 项目工程结构: 在<springmvc入门篇一.HelloWorld>基础上继续添加代码,新增:FormController.ja ...
- Java开发学习(二十三)----SpringMVC入门案例、工作流程解析及设置bean加载控制
一.SpringMVC概述 SpringMVC是隶属于Spring框架的一部分,主要是用来进行Web开发,是对Servlet进行了封装.SpringMVC是处于Web层的框架,所以其主要的作用就是用来 ...
随机推荐
- 实现Callable的对象中,用@Autowired注入别的对象失败
场景是这样: 我需要在一个实现类A中写一个拿到返回值的多线程,于是用的Callable,在这个实现类A外我又写了一个专门实现Callable的实现类B,在B中用spring注解@Autowired注入 ...
- 用 React 编写的基于Taro + Dva构建的适配不同端(微信小程序、H5、React-Native 等)的时装衣橱
前言 Taro 是一套遵循 React 语法规范的 多端开发 解决方案.现如今市面上端的形态多种多样,Web.React-Native.微信小程序等各种端大行其道,当业务要求同时在不同的端都要求有所表 ...
- Angular搭建脚手架
1.安装CLI: cnpm install -g @angular/cli //卸载: npm uninstall -g @angular/cli npm cache clean 2.检测是否成功 ...
- #include stdio.h(7)
#include <stdio.h> int main() { //***********一.循环语句*************** //什么叫做循环: //重复的做某件事情,重复的执行一 ...
- Swift中as as! as?的区别
as :类型一致或者子类 仅当一个值的类型在运行时(runtime)和as模式右边的指定类型一致 - 或者是该类型的子类 - 的情况下,才会匹配这个值.如果匹配成功,被匹配的值的类型被转换成as模 ...
- DB2安装教程图解
下载好之后,是exe文件,但是双击后基本上都是解压,但是使用自身的解压的话会有很多文件解压失败的情况,所以推荐使用自己电脑上自带的解压工具直接解压(如360解压,好压等). 解压之后直接运行setup ...
- 光标显示样式 css 中 cursor 属性使用
记录一下 cursor 的各种样式,方便自己查找.之前用到不常用的每次去 百度 或 Google 找不如自己记录下好找些. cursor光标类型 auto default none context-m ...
- JavaScript 常用的Math对象
Math.ceil(x); //返回x向上取整后的整数值. Math.floor(x); //返回x向下取整后的整数值.. Math.round(x); //返回四舍五入后的整数. Math.abs( ...
- jquery对checkbox的操作汇总
1.全选 $("#btn1").click(function(){ $("input[name='checkbox']").attr("checked ...
- 查看Linux网卡地址,网络地址
查看网络地址 ip a 或ip addr show 或ifconfig,此指令在部分linux系统中不支持