Spring4 MVC + REST + List + Bootstrap 简单示例

本篇文章,我们将教会你通过eclipse创建并转换为maven的web项目。通过spring4 mvc提供的REST方式将List对象中的值通JSTL 的 c:forEach 标签输出到页面中(本篇文章涉及到前面整合bootstrap的内容)。
开发环境:
1. jdk 1.7
2. Maven 3.3.9
3. Eclipse Mars.1
4.Spring 4.2.1.RELEASE
5.Bootstrap

1.最终的目录结构

2. 创建项目
Eclipse - File - New - Dynamic Web Project 输入项目名称,然后右击该项目Configure-Convert to Maven project
并在WebContent/WEB-INF下新建一个web.xml文件
3.项目依赖---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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.thinkingingis</groupId>
  <artifactId>SpringMvcListExample</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>war</packaging>
  
  <dependencies>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>4.2.1.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jstl</artifactId>
		<version>1.2</version>
	</dependency>
	<dependency>
		<groupId>ch.qos.logback</groupId>
		<artifactId>logback-classic</artifactId>
		<version>1.1.3</version>
	</dependency>
  </dependencies>
  
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.6</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
4.Spring MVC
4.1 Spring Controller-返回一个List对象
package org.thinkingingis.controller;

import java.util.Map;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.thinkingingis.service.HelloWorldService;

import ch.qos.logback.classic.Logger;

@Controller
public class WelcomeController {
	
	private final Logger logger = (Logger) LoggerFactory.getLogger(WelcomeController.class);
	private HelloWorldService helloWorldService;
	
	@Autowired
	public WelcomeController(HelloWorldService helloWorldService){
		this.helloWorldService = helloWorldService;
	}
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String index(Map<String, Object> model){
		
		logger.debug("index() method is executed");
		
		model.put("title", helloWorldService.getTitle(""));
		model.put("msg", helloWorldService.getDesc());
		
		return "index";
	}
	
	@RequestMapping(value = "/{name:.+}", method = RequestMethod.GET)
	public ModelAndView hello(@PathVariable("name") String name){
		
		logger.debug("hello() is executed - $name {}", name);
			
		ModelAndView model = new ModelAndView();
		model.setViewName("index");
		model.addObject("title", helloWorldService.getTitle(name));
		model.addObject("msg", helloWorldService.getDesc());
		model.addObject("list", helloWorldService.getList());
		
		return model;	
	}
	
}
4.2 Service 层,生成相关信息
package org.thinkingingis.service;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import ch.qos.logback.classic.Logger;

@Service
public class HelloWorldService {
	
	private static final Logger logger = (Logger) LoggerFactory.getLogger(HelloWorldService.class);
	
	public String getDesc(){
		logger.debug("getDesc() is executed!");
		return "[Maven + Spring MVC + Bootstrap + List] Example";
	}
	
	public String getTitle(String name){
		logger.debug("getTitle() is executed! $name : {}", name);
		if(StringUtils.isEmpty(name)){
			return "Hello ThinkingInGIS";
		}else {
			return "Hello " + name;
		}
	}
	
	public List<String> getList(){
		List<String> list = new ArrayList<String>();
		list.add("List M");
		list.add("List A");
		list.add("List P");
		list.add("List S");
		
		list.add("List C");
		list.add("List A");
		list.add("List N");
		
		list.add("List T");
		list.add("List A");
		list.add("List L");
		list.add("List K");
		
		return list;
	}
}
4.3 index.jsp展现层 JSP + JSTL + Bootstrap . /WEB-INF/views/jsp/index.jsp
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Maven + Spring mvc + Bootstrap</title>

<spring:url value="/resources/core/css/bootstrap.css" var="bootstrapCss"></spring:url>
<link href="${bootstrapCss}" rel="stylesheet" />

</head>

<body>

<nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container">
	<div class="navbar-header">
		<a class="navbar-brand" href="#">Spring Mvc List Example</a>
	</div>
  </div>
</nav>


<div class="jumbotron">
  <div class="container">
	<h1>${title}</h1>
	<p>
		<c:if test="${not empty msg}">
			Hello ${msg}
		</c:if>

		<c:if test="${empty msg}">
			Welcome ThinkingInGIS!
		</c:if>
    </p>
    <p>
		<c:if test="${not empty list }">
			<ul>
				<c:forEach var="list" items="${list }">
					<li>${list}</li>
				</c:forEach>
			</ul>
		</c:if>
	</p>
	</div>
</div>

<div class="container">

  <div class="row">
	<div class="col-md-4">
		<h2>Maps</h2>
		<p>Maps</p>
	</div>
	
	<div class="col-md-4">
		<h2>Can</h2>
		<p>Can</p>
	</div>
	
	<div class="col-md-4">
		<h2>Talk.</h2>
		<p>Talk.</p>
	</div>
  </div>


  <hr>
  <footer>
	<p>© ThinkingInGIS 2016</p>
  </footer>
</div>

<spring:url value="/resources/core/js/jquery.js" var="jquery" />
<spring:url value="/resources/core/js/bootstrap.js" var="bootstrapJs" />

<script src="${jquery}"></script>
<script src="${bootstrapJs}"></script>

</body>
</html>
4.4 配置日志信息:输出日志到控制台中 log.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>

	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
	  <layout class="ch.qos.logback.classic.PatternLayout">

		<Pattern>
		%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
		</Pattern>

	  </layout>
	</appender>

	<logger name="org.springframework" level="debug"
                additivity="false">
		<appender-ref ref="STDOUT" />
	</logger>

	<logger name="org.thinkingingis" level="debug"
                additivity="false">
		<appender-ref ref="STDOUT" />
	</logger>

	<root level="debug">
		<appender-ref ref="STDOUT" />
	</root>

</configuration>
5 以 XML 方式配置 spring
5.1 spring-core-config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd ">

	<context:component-scan base-package="org.thinkingingis.service" />

</beans>
5.2 spring-mvc-config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd ">

	<context:component-scan base-package="org.thinkingingis.controller" />

	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
		<property name="prefix" value="/WEB-INF/views/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<mvc:resources mapping="/resources/**" location="/resources/" />

	<mvc:annotation-driven />

</beans>
5.3 部署描述文件 web.xml
<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_2_5.xsd"
	version="2.5">

	<display-name>Maven + Spring MVC Hello World + XML</display-name>
	<description>Spring MVC web application</description>

	<!-- For web context -->
	<servlet>
		<servlet-name>hello-dispatcher</servlet-name>
		<servlet-class>
                        org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring-mvc-config.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>hello-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- For root context -->
	<listener>
		<listener-class>
                  org.springframework.web.context.ContextLoaderListener
        </listener-class>
	</listener>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring-core-config.xml</param-value>
	</context-param>

</web-app>
6.部署项目
6.1 通过终端进入SpringMvcListExample 项目目录下(windows系统通过cmd进入),输入 mvn package后,出现"BUILD SUCCESS" 说明项目达成war包成功

6.2将项目target目录下的 SpringMvcListExample-1.0.0-SNAPSHOT.war 拷贝到 tomcat根目录下的webapps文件夹下,启动tomcat
输入 http://localhost:8080/SpringMvcListExample/


输入 http://localhost:8080/SpringMvcListExample/China


这也一个通过REST风格访问的web程序就搭建好啦,页面会遍历List对象

(如遇到问题,请留言给作者,以便共同探讨gis知识。thinkingingis@qq.com

微信公众号:ThinkingInGIS


欢迎大家关注:)
<think>我们正在讨论如何将基于SSM框架和JSP的系统与手机端进行连接。用户的问题:如何将基于SSM框架和JSP的系统与手机端进行连接?关键点:SSM框架(Spring+SpringMVC+MyBatis)、JSP(用于视图层)、连接手机端。分析:1.原有的系统是B/S架构,使用JSP作为视图层,主要面向浏览器(PC端)。2.现在需要连接手机端,意味着需要让手机能够访问这个系统。手机端通常有两种方式:-通过手机浏览器访问(响应式网页设计)-通过原生App或混合App(需要提供API接口)因此,有两种主要方案:方案一:改造前端,使用响应式设计(适应手机浏览器)方案二:为移动端(App)提供后端API接口考虑到用户原来的系统使用JSP,如果希望继续使用JSP,那么方案一比较合适。但是JSP在移动端响应式设计上需要结合HTML5和CSS3。如果用户希望开发App(原生或混合),那么需要将原有的系统改造为提供RESTfulAPI接口,这样手机App可以通过这些API与后端交互。详细步骤:方案一:响应式网页设计(适用于手机浏览器访问)步骤1:在原有的JSP页面中使用响应式布局(例如使用Bootstrap框架)步骤2:调整页面元素,使其能够适应不同屏幕尺寸步骤3:在SpringMVC控制器中,可以根据请求的设备类型(通过User-Agent判断)返回不同的视图(例如为手机返回专门的JSP页面)或者同一个响应式页面优点:不需要改变后端架构,只需修改前端页面缺点:对于复杂的移动端交互可能不够理想方案二:为移动App提供API接口(适用于原生App或混合App)步骤1:在原有SSM框架的基础上,将后端改造成同时支持页面渲染(JSP)和API接口(JSON/XML)步骤2:使用SpringMVC的注解(如@RestController)创建RESTful风格的API接口步骤3:原有的业务逻辑可以复用,但需要将返回的数据由原来的ModelAndView改为直接返回数据对象(由SpringMVC转换为JSON)步骤4:手机端通过HTTP请求调用这些接口,获取数据并展示步骤5:对于安全性,可能需要增加身份认证(如JWT)和授权机制同时,两种方案也可以并存:即系统同时支持响应式网页和API接口。参考引用[^1]中提到的系统架构图,我们可以将系统扩展为:控制层(Controller):-一部分处理JSP视图(返回ModelAndView)-另一部分处理API请求(返回JSON)因此,我们可以这样设计:在SpringMVC的配置中,我们可以配置多个视图解析器,同时配置消息转换器(如MappingJackson2HttpMessageConverter)来处理JSON。示例代码(SpringMVC控制器):```java@ControllerpublicclassUserController{//原有的JSP页面请求处理方法@RequestMapping("/userList")publicStringuserList(Modelmodel){List<User>users=userService.getAllUsers();model.addAttribute("users",users);return"userList";//对应一个JSP页面}//新增的API接口,返回JSON@RequestMapping(value="/api/userList",produces="application/json")@ResponseBodypublicList<User>apiUserList(){returnuserService.getAllUsers();}}```对于手机App,它访问的是`/api/userList`,得到JSON数据。另外,为了适应移动端,我们还需要考虑:-跨域问题(如果App与网站不同域):使用@CrossOrigin注解或配置全局CORS-安全性:移动端登录认证(可以使用Token机制,如JWT)总结:1.如果只是让手机浏览器能够访问,采用响应式设计改造JSP页面。2.如果要开发手机App,则增加API接口,后端同时提供JSP和JSON数据。3.也可以同时采用两种方案。根据用户的需求,他们可能需要选择其中一种或两种都采用。相关问题:1.如何设计响应式JSP页面以适应手机端?2.在SSM框架中如何配置RESTfulAPI?3.移动端与后端交互时如何保证安全性?4.如何解决跨域问题?5.移动端和PC端使用同一套后端接口时,如何区分不同的请求?</think>### SSM框架JSP系统连接手机端实现方式 要将基于SSM框架和JSP的系统扩展到手机端,主要有两种实现方案: #### 方案一:响应式前端改造(适合移动浏览器访问) 1. **前端技术升级** - 使用Bootstrap或Vue.js等响应式框架重构JSP视图层 - 通过CSS媒体查询实现自适应布局: ```css @media (max-width: 768px) { /* 移动端样式调整 */ .container { padding: 5px; } } ``` - 将JSP中的静态资源替换为响应式组件 2. **后端适配** - 在SpringMVC中增加设备检测: ```java @GetMapping("/data") public String getData(Device device) { if (device.isMobile()) { return "mobile/data"; // 返回移动版视图 } return "pc/data"; // 返回PC版视图 } ``` 3. **优点** - 复用现有SSM业务逻辑和持久层 - 开发成本低,无需单独维护API - 适合轻量级移动应用场景 #### 方案二:API接口分离(适合原生APP开发) 1. **后端改造** - 添加RESTful控制器层: ```java @RestController @RequestMapping("/api") public class MobileController { @Autowired private UserService userService; // 复用原有Service @GetMapping("/users") public ResponseEntity<List<User>> getUsers() { return ResponseEntity.ok(userService.getAll()); } } ``` - 配置JSON序列化(在spring-mvc.xml中): ```xml <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> </mvc:message-converters> </mvc:annotation-driven> ``` 2. **前端实现** - **Web APP**:使用React Native/Flutter开发混合应用 - **原生APP**:Android/iOS通过HTTPClient调用API - **小程序**:通过wx.request()对接接口 3. **关键技术点** - **认证安全**:使用JWT替代Session ```java // 生成JWT令牌 String token = Jwts.builder() .setSubject(username) .signWith(SignatureAlgorithm.HS512, SECRET_KEY) .compact(); ``` - **跨域处理**:添加CORS配置 ```java @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("*") .allowedMethods("GET","POST"); } } ``` - **数据压缩**:启用GZIP减少流量消耗 #### 混合架构建议 ```mermaid graph TD A[手机浏览器] -->|HTTP请求| B(SSM后端) C[原生APP] -->|API调用| B D[微信小程序] -->|API调用| B B --> E[SpringMVC控制器] E --> F{JSP视图/REST API} F -->|移动端| G[响应式HTML] F -->|API| H[JSON数据] I[MyBatis持久层] --> J[MySQL数据库] E --> I ``` **部署注意事项**: 1. 使用Nginx做反向代理和负载均衡 2. 启用HTTPS保障传输安全 3. API版本控制(如`/api/v1/users`) 4. 使用Swagger生成API文档 > 参考实践:某企业人事管理系统在扩展移动端时,保留原有JSP界面供PC使用,同时新增`/api`路径下的REST接口供APP调用,复用率达70%[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值