spring boot jsp mvc jpa mysql
今天將spring boot 的官方 sample 做了些簡單調整
將 jsp mvc jpa mysql 合在了一起
樣例截圖
1. 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>com.yonyou</groupId> <artifactId>boot</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!-- Provided --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> </dependencies> </project>
2. application.properties
######## web ######## spring.mvc.view.prefix: /WEB-INF/jsp/ spring.mvc.view.suffix: .jsp application.message: Hello Phil spring.h2.console.enabled=true logging.level.org.hibernate.SQL=debug ######## database ######## spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot spring.datasource.username = root spring.datasource.password = 111111 spring.datasource..driver-class-name = com.mysql.jdbc.Driver spring.jpa.properties.hibernate.hbm2ddl.auto=update
3. SpringBootApplication
/* * Copyright 2012-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sample.data.jpa; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication public class SampleWebJspApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(SampleWebJspApplication.class); } public static void main(String[] args) throws Exception { SpringApplication.run(SampleWebJspApplication.class, args); } }
4. model repository service controller 部分程式碼
model
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.data.jpa.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class City implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String state;
@Column(nullable = false)
private String country;
@Column(nullable = false)
private String map;
protected City() {
}
public City(String name, String country) {
super();
this.name = name;
this.country = country;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getMap() {
return map;
}
public void setMap(String map) {
this.map = map;
}
@Override
public String toString() {
return "City [id=" + id + ", name=" + name + ", state=" + state + ", country=" + country + ", map=" + map + "]";
}
}
repository
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.data.jpa.service;
import sample.data.jpa.domain.City;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
interface CityRepository extends JpaRepository<City, Long> {
Page<City> findAll(Pageable pageable);
Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name, String country, Pageable pageable);
City findByNameAndCountryAllIgnoringCase(String name1, String country);
// @Modifying
// @Query("update city set name = :city.name, country=city.country, map=city.map where id = :city.id")
// void update(@Param("city") City city);
}
service
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.data.jpa.service;
import sample.data.jpa.domain.City;
import sample.data.jpa.domain.HotelSummary;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
public interface CityService {
Page<City> findCities(CitySearchCriteria criteria, Pageable pageable);
City getCity(String name, String country);
Page<HotelSummary> getHotels(City city, Pageable pageable);
public void saveCity(City city);
public List<City> findAll();
public City find(long id);
public void delCity(long id);
public void updateCity(City city);
}
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.data.jpa.service;
import sample.data.jpa.domain.City;
import sample.data.jpa.domain.HotelSummary;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@Service("cityService")
@Transactional
class CityServiceImpl implements CityService {
private final CityRepository cityRepository;
private final HotelRepository hotelRepository;
public CityServiceImpl(CityRepository cityRepository,
HotelRepository hotelRepository) {
this.cityRepository = cityRepository;
this.hotelRepository = hotelRepository;
}
@Override
public Page<City> findCities(CitySearchCriteria criteria, Pageable pageable) {
Assert.notNull(criteria, "Criteria must not be null");
String name = criteria.getName();
if (!StringUtils.hasLength(name)) {
return this.cityRepository.findAll(pageable);
}
String country = "";
int splitPos = name.lastIndexOf(",");
if (splitPos >= 0) {
country = name.substring(splitPos + 1);
name = name.substring(0, splitPos);
}
return this.cityRepository
.findByNameContainingAndCountryContainingAllIgnoringCase(name.trim(),
country.trim(), pageable);
}
@Override
public City getCity(String name, String country) {
Assert.notNull(name, "Name must not be null");
Assert.notNull(country, "Country must not be null");
return this.cityRepository.findByNameAndCountryAllIgnoringCase(name, country);
}
@Override
public Page<HotelSummary> getHotels(City city, Pageable pageable) {
Assert.notNull(city, "City must not be null");
return this.hotelRepository.findByCity(city, pageable);
}
@Override
public void saveCity(City city) {
this.cityRepository.save(city);
}
@Override
public List<City> findAll() {
return this.cityRepository.findAll();
}
@Override
public void delCity(long id) {
this.cityRepository.delete(id);
}
@Override
public void updateCity(City city) {
City c = this.cityRepository.findOne(city.getId());
c.setCountry(city.getCountry());
c.setName(city.getName());
c.setMap(city.getMap());
c.setState(city.getState());
}
@Override
public City find(long id) {
return this.cityRepository.findOne(id);
}
}
controller
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.data.jpa.web;
import sample.data.jpa.domain.City;
import sample.data.jpa.service.CityService;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("city")
public class CityController {
@Autowired
private CityService cityService;
@PostMapping("save")
public String save(City city, HttpServletResponse rsp) throws IOException {
this.cityService.saveCity(city);
rsp.sendRedirect("all");
return null;
}
@RequestMapping("all")
public String findAll(Map<String, Object> model) {
List<City> cities = this.cityService.findAll();
model.put("cities", cities);
return "cities";
}
@RequestMapping("del")
public String del(@RequestParam("id") long id, HttpServletResponse rsp) throws IOException {
this.cityService.delCity(id);
rsp.sendRedirect("all");
return null;
}
@RequestMapping("4edit/{id}")
public String find4edit(@PathVariable("id") long id, HttpServletResponse rsp,Map<String, Object> model) throws IOException {
City c = this.cityService.find(id);
model.put("city", c);
return "city-edit";
}
@RequestMapping("update")
public String update(City city, HttpServletResponse rsp) throws IOException {
this.cityService.updateCity(city);
rsp.sendRedirect("all");
return null;
}
}
5. jsp
index
<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<body>
<c:url value="/resources/text.txt" var="url"/>
<spring:url value="/resources/text.txt" htmlEscape="true" var="springUrl" />
Spring URL: ${springUrl} at ${time}
<br>
JSTL URL: ${url}
<br>
Message: ${message}
<h1><a href="city/all"> city list </a> </h1>
</body>
</html>
cities
<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h1>------------------ city list ------------------</h1>
<p><a href="/city-add"> add city </a></p>
<table border="1">
<tr>
<th>id</th><th>name</th><th>country</th><th>state</th><th>map</th><th>opt</th>
</tr>
<c:forEach items="${cities}" var="city">
<tr>
<td>${city.id}</td>
<td>${city.name}</td>
<td>${city.country}</td>
<td>${city.state}</td>
<td>${city.map}</td>
<td>
<a href="del?id=${city.id}">del</a>
<a href="4edit/${city.id}">edit</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
edit
<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h1>------------------city edit------------------</h1>
<form action="/city/update" method="post">
name:<input name="name" value="${city.name}" type="text"/>
state:<input name="state" value="${city.state}" type="text"/>
country:<input name="country" value="${city.country}" type="text"/>
map:<input name="map" value="${city.map}" type="text"/>
<input type="hidden" name="id" value="${city.id}"/>
<input type="submit"/>
</form>
</body>
</html>
原始碼下載
http://download.csdn.net/detail/stonexmx/9768321