9.13
Write a servlet and associated HTML code for the following very simple application: A user is allowed to submit a form containing a value, say \(n\), and should get a response containing \(n\) “*” symbols.
Python Version:
The following uses FastAPI
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
= FastAPI()
app
app.add_middleware(
CORSMiddleware,=["*"],
allow_origins=["GET"],
allow_methods=["*"],
allow_headers
)
@app.get("/stars/{n}")
def get_stars(n: int):
return "*" * n
Run your api:
uvicorn main:app --reload
Test it in insomnia
I would write the frontend with flutter and let the flutter engine compile the dart code to HTML for me.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
const MyApp());
runApp(
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {return MaterialApp(
: 'DSC',
title: ThemeData(
theme: Colors.blue,
primarySwatch,
): const MyHomePage(title: 'DSC Home Page'),
home
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
<MyHomePage> createState() => _MyHomePageState();
State
}
class _MyHomePageState extends State<MyHomePage> {
late TextEditingController tec;
String msg = "No message from server.";
@override
void initState() {
= TextEditingController();
tec super.initState();
}
@override
void dispose() {
.dispose();
tecsuper.dispose();
}
@override
Widget build(BuildContext context) {return Scaffold(
: AppBar(
appBar: Text(widget.title),
title,
): Center(
body: Column(
child: MainAxisAlignment.center,
mainAxisAlignment: <Widget>[
childrenconst Text("Enter the number of stars you want: "),
TextFormField(: tec,
controller,
)
ElevatedButton(: Text("Submit number of stars"),
child: () {
onPressed
try {
int number_of_stars = int.parse(tec.text);
.get(Uri.parse("http://127.0.0.1:8000/stars/$number_of_stars")).then(
http.Response r) {
(http
setState(() {= r.body;
msg
});
}
);catch (e) {
} .of(context).showSnackBar(
ScaffoldMessengerconst SnackBar(content: Text("Some error occured! that is all we know."))
);
}
},
),
Text(msg),
],
),
)
);
} }
Initial Screenshot:
After submitting a value:
Compile:
Servlet version:
// TODO.