- Python (使用Flask框架)
app.py
python
from flask import Flask, render_template, request
app = Flask(name)
假设的游戏商品列表
games = [
{“id”: 1, “name”: “Game 1”, “price”: 9.99},
{“id”: 2, “name”: “Game 2”, “price”: 19.99},
# … 更多游戏
]
@app.route(‘/’)
def index():
return render_template(‘index.html’, games=games)
@app.route(‘/purchase’, methods=[‘POST’])
def purchase():
game_id = request.form.get(‘game_id’)
# 这里应该添加购买逻辑,如检查库存、处理支付等
# …
return “Purchase successful!” # 仅为示例,应返回更详细的响应或重定向到成功页面
if name == ‘main’:
app.run(debug=True)
templates/index.html
html
Welcome to Game Store
{% for game in games %}{{ game.name }}
Price: ${{ game.price }}
Purchaseserver.js
javascript
const express = require(‘express’);
const app = express();
const port = 3000;
// 假设的游戏商品列表
const games = [
// … 与Python示例中的游戏列表类似
];
app.get(‘/’, (req, res) => {
res.send(‘HTML页面或重定向到前端页面’);
});
app.post(‘/purchase’, (req, res) => {
const gameId = req.body.game_id;
// 添加购买逻辑…
res.send(‘Purchase successful!’);
});
app.listen(port, () => {
console.log(Server is running on port ${port}
);
});
3. Java (使用Spring Boot)
Spring Boot项目会更大且更复杂,但以下是一个简单的控制器示例。
GameController.java
java
import org.springframework.web.bind.annotation.*;
import java.util.List;
// … 其他必要的导入
@RestController
@RequestMapping(“/”)
public class GameController {
// 假设的游戏商品列表(在真实应用中,这将是数据库查询)
private List<Game> games = // ... 初始化游戏列表
@GetMapping
public String index() {
// 返回HTML模板或重定向到前端页面
return "index";
}
@PostMapping("/purchase")
public String purchase(@RequestParam Long gameId) {
// 添加购买逻辑...
return "Purchase successful!";
}
// Game类、服务层、数据库交互等将在此处扩展
}
注意:以上示例仅用于演示目的,并未包含完整的错误处理、验证、安全性或数据库交互。在构建实际的游戏商城时,你需要考虑这些因素。