MyFirstServletTest.java

Курсовая работа

По дисциплине «Разработка интернет приложений»

 

Выполнил:

студент группы ПС-41

Васильев А.А.

 

Проверил:

Габдуллин Д.И.

 

г. Йошкар-Ола

2018

Оглавление

Задание. 3

Решение. 3

Листинг. 4

Список использованной литературы. 19

 


 


Задание

 

1. Создать веб-страницу для добавления и отображения книг, используя сервлет, протестировать приложение на фреймворке Junit,реализовать собственный шаблонизатор, провести статический анализ и исправить ошибки.

2. Перенести приложение на один из современных фреймворков.

 

Решение

 

Предметной областью были выбраны книги.

Атрибуты книги: название, автор, дата, жанр, рейтинг.

В качестве фреймворка была выбрана технология Springboot.


 


Листинг

Задание №1

MyFirstServlet.java package servlet; import com.google.common.base.Charsets; import com.google.common.io.Files; import database.DatabaseHelper; import javafx.util.Pair; import model.Book; import util.ApplicationUtils; import util.FileEventLogger; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.util.HashMap; import java.util.List; /** * servlet class */@WebServlet("/MyFirstServlet") publicclass MyFirstServlet extends HttpServlet { HashMap< String, String > templateMap = new HashMap<>(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {FileEventLogger.logEvent("get request: "+ req.toString()); resp.setContentType("text/html"); PrintWriter out =resp.getWriter(); List <Book> books = null; try {books= DatabaseHelper.readBooks();} catch (ParseException e){e.printStackTrace();} String output =""; for (Book b: books){output+=("<h1>"+ b.toString()+"</h1>");}templateMap.put("books", output); out.write(getBaseHtml().replace("{%%content%%}", output));out.flush();} @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {FileEventLogger.logEvent("post request: "+ req); try { Book book = new Book(req.getParameter("book"),req.getParameter("author"),     ApplicationUtils.DATE_FORMAT.parse(req.getParameter("date")),req.getParameter("genre"), Integer. parseInt(req.getParameter("rating")));DatabaseHelper.addBook(book);} catch (ParseException e){ System. out.println("Err occured");e.printStackTrace();} resetPage(req, resp);} /** *@param req request *@param resp response *@throws ServletException *@throws IOException */ private void resetPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { RequestDispatcher requestDispatcher =req.getRequestDispatcher("/index.html");requestDispatcher.forward(req, resp);} /** *@return minimal html response */ privateString getBaseHtml(){ return "<html>"+"<head>"+"<title>Books</title>"+"</head>"+"<body>"+"{%%content%%}"+"</body>"+"</html>";}} Book.java package model; import util.ApplicationUtils; import java.util.Date; /** * Book model */ publicclass Book {/** * name */ privateString name;/** * author */ privateString author;/** * date. */ privateDate date;/** * genre */ privateString genre;/** * rating */ private int rating; /** *@param name name of Book *@param author author of Book *@param date date of Book *@param genre genre of Book *@param rating rating of Book */ public Book(String name, String author, Date date, String genre,int rating){ this. name = name; this. author = author; this. date = date; this. genre = genre; this. rating = rating;} /** *@return string value of object */@Override publicString toString(){ return "Book: "+ name+"<p>author: "+ author +"</p>"+"<p>date: "+ ApplicationUtils.DATE_FORMAT.format(date)+"</p>"+"<p>genre: "+ genre +"</p>"+"<p>rating: "+ rating +"</p>"+"<p>_______________</p>";} /** *@return getter */ publicString getName(){ return name;} /** *@param name setter */ public void setName(String name){ this. name = name;} /** *@return setter */ publicString getAuthor(){ return author;} /** *@param author setter */ public void setAuthor(String author){ this. author = author;} /** *@return getter */ publicDate getDate(){ return date;} /** *@param date setter */ public void setDate(Date date){ this. date = date;} /** *@return getter */ publicString getGenre(){ return genre;} /** *@param genre setter */ public void setGenre(String genre){ this. genre = genre;} /** *@return getter */ public int getRating(){ return rating;} /** *@param rating setter */ public void setRating(int rating){ this. rating = rating;}}

ApplicationUtils.java

package util;

 

import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Locale;

 

/**

* Util class for date format

*/

 

publicclass ApplicationUtils {

/**

* date - format for date - objects

*/

publicstaticfinalDateFormat DATE_FORMAT =

newSimpleDateFormat ("dd.mm.yyyy", Locale. ENGLISH);

/**

* date - format for database

*/

publicstaticfinalDateFormat DB_FORMAT =

newSimpleDateFormat ("yyyy-mm-dd", Locale. ENGLISH);

 

publicstaticfinalString formatDate(Date date){

return DATE_FORMAT.format(date);

}

 

/**

*@param date string value of date

*@return Date object

*@throws ParseException if parsing failed

*/

publicstaticfinalDate fromDatabase(String date) throwsParseException {

return DB_FORMAT.parse(date);

}

}

DatabaseHelper.java

package database;

 

import model.Book;

import util.ApplicationUtils;

import util.FileEventLogger;

 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.text.ParseException;

import java.util.Date;

import java.util.LinkedList;

import java.util.List;

 

 

/**

* Class which is responsible for working with MySQL database

*/

publicclass DatabaseHelper {

publicstaticfinalString url ="jdbc:mysql://localhost:3306/books";

publicstaticfinalString user ="root";

publicstaticfinalString password ="qwerty";

privatestaticfinal int SQL_PARAM_ID_NAME =1;

privatestaticfinal int SQL_PARAM_ID_AUTHOR =2;

privatestaticfinal int SQL_PARAM_ID_DATE =3;

privatestaticfinal int SQL_PARAM_ID_GENRE =4;

privatestaticfinal int SQL_PARAM_ID_RATING =5;

 

/**

* Connection to db

*/

privatestaticConnection con;

 

/**

* Class which is responsible for working with MySQL database

*/

public DatabaseHelper(){

}

 

/**

*@param book Book which should be added to database

*/

publicstatic void addBook(Book book){

 

FileEventLogger.logEvent("Adding new book: "+ book.toString());

try {

Class. forName("com.mysql.jdbc.Driver");

con= DriverManager. getConnection(url, user, password);

PreparedStatement stmt =con.prepareStatement(

"INSERT INTO Books (name, author, date, genre, rating) VALUES (?,?,?,?,?)");

stmt.setString(SQL_PARAM_ID_NAME, book.getName());

stmt.setString(SQL_PARAM_ID_AUTHOR, book.getAuthor());

stmt.setDate(

     SQL_PARAM_ID_DATE, new java.sql. Date (book.getDate().getTime()));

stmt.setString(SQL_PARAM_ID_GENRE, book.getGenre());

stmt.setInt(SQL_PARAM_ID_RATING, book.getRating());

stmt.addBatch();

stmt.executeBatch();

} catch (SQLException e){

e.printStackTrace();

FileEventLogger.logEvent(e.getMessage());

} catch (ClassNotFoundException e){

e.printStackTrace();

}

}

 

/**

*@return list of books from database

*@throws ParseException

*/

publicstaticList <Book> readBooks() throwsParseException {

if (con == null){

try {

con= DriverManager. getConnection(url, user, password);

} catch (SQLException e){

e.printStackTrace();

FileEventLogger.logEvent(e.getMessage());

}

}

FileEventLogger.logEvent("Reading books from database.");

ResultSet rs = null;

try {

rs= queryRead("select name, author, date, genre, rating from books");

} catch (ClassNotFoundException e){

e.printStackTrace();

FileEventLogger.logEvent(e.getMessage());

} catch (SQLException e){

e.printStackTrace();

FileEventLogger.logEvent(e.getMessage());

}

List <Book> result = new LinkedList<Book>();

try {

while (rs.next()){

String name =rs.getString(1);

String author =rs.getString(2);

Date date =ApplicationUtils.fromDatabase(String. valueOf(rs.getDate(3)));

String genre =rs.getString(4);

int rating = rs.getInt(5);

 

result.add(new Book(name, author, date, genre, rating));

}

} catch (SQLException e){

e.printStackTrace();

FileEventLogger.logEvent(e.getMessage());

}

FileEventLogger.logEvent("Reading successful!.");

return result;

}

 

 

privatestaticResultSet queryRead(String query) throwsClassNotFoundException, SQLException {

Class. forName("com.mysql.jdbc.Driver");

con= DriverManager. getConnection(url, user, password);

return con.createStatement().executeQuery(query);

}

}

FileEventLogger.java

package util;

 

import com.sun.jna.platform.FileUtils;

 

import java.io.File;

import java.io.IOException;

import java.nio.file.Files;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import java.util.Date;

 

/**

* logger class

*/

publicclass FileEventLogger {

publicstaticDateFormat dateFormat = newSimpleDateFormat ("yyyy/MM/dd HH:mm:ss");

publicstaticfinalString fileName ="logs.txt";

 

/**

*@param message text to be logged

*/

publicstatic void logEvent(String message){

File file = newFile (fileName);

if (!file.exists()){

try {

file.createNewFile();

} catch (IOException e){

e.printStackTrace();

}

}

file.setWritable(true);

 

try {

Files.write(Paths.get(fileName),

(dateFormat.format(newDate ())+": "+ message +"\n").getBytes(), StandardOpenOption.APPEND);

} catch (IOException e){

e.printStackTrace();

}

}

}

MyFirstServletTest.java

package servlet; import org.junit. *; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.junit.Assert. *; /** * test class */ publicclass MyFirstServletTest {/** * Webdriver */ private WebDriver driver; /** * beginning url */ privatestaticfinalString BASE_URL ="http://localhost:8080/"; /** * */@Before public void createDriver(){ System. setProperty("webdriver.gecko.driver","D:\\sdk\\geckodriver.exe"); DesiredCapabilities capabilities =DesiredCapabilities.firefox();capabilities.setCapability(CapabilityType.ForSeleniumServer.ENSURING_CLEAN_SESSION, true);driver= new FirefoxDriver(capabilities);driver.get(BASE_URL);} /** * */@After public void quitDriver(){driver.manage().deleteAllCookies();driver.quit();} /** * book is valid */@Test public void testValidBook(){ System. out.println("html!:"+ driver.getPageSource());fillField("book","Effective Java");fillField("author","Joshua Bloch");fillField("date","12.12.1400");fillField("genre","Popular");fillField("rating","4");submitForm();checkBooksCount(1);} /** * incorrect date format */@Test public void testBadDate(){fillField("book","Qwerty");fillField("author","Alexander");fillField("date","1224.20");fillField("genre","Popular");fillField("rating","2");submitForm();checkBooksCount(0);} /** * request without date param */@Test public void testMissingDate(){fillField("book","2zxc2");fillField("author","tt5");fillField("genre","historic");fillField("rating","5");submitForm();checkBooksCount(0);} /** * request without any filled field */@Test public void testMissingAllFields(){submitForm();checkBooksCount(0);} /** * if we put string value into rating field */@Test public void testStringRating(){fillField("book","xzc");fillField("author","sfdr");fillField("date","12.12.2012");fillField("genre","science");fillField("rating","a");submitForm();checkBooksCount(0);} /** * test for very long integer */@Test public void testVeryLongRating(){fillField("book","zxcvc");fillField("author","gfdtrtt");fillField("date","10.01.2015");fillField("genre","science");fillField("rating","111111111111111111111111111111111"+"111111111111111111111111111111111"+"111111111111111111111111111111111"+"111111111111111111111111111111111"+"111111111111111111111111111111111");wait(7000);submitForm();checkBooksCount(0);} /** *@param field field that we want to fill *@param value value of this field */ private void fillField(String field, String value){ WebElement input =driver.findElement(By.name(field));assertNotNull(input);input.sendKeys(value);} /** * click on input */ private void submitForm(){ WebElement input =driver.findElement(By.id("addBtn"));assertNotNull(input);input.click();wait(4000);} /** * go to page with all books */ private void showAllBooks(){ WebElement input =driver.findElement(By.id("showBtn"));assertNotNull(input);input.click();wait(1000); } /** *@param milliSeconds waiting time */ private void wait(final int milliSeconds){driver.manage().timeouts().implicitlyWait(milliSeconds, TimeUnit.MILLISECONDS);} private int getCountOfBooks(finalString html){ Pattern pattern =Pattern.compile("<p>_______________</p>"); Matcher matcher =pattern.matcher(html);int count =0; while (matcher.find()){count++;} return count;} /** *@param count expected number */ private void checkBooksCount(final int count){showAllBooks(); String html =driver.getPageSource();assertEquals(count, getCountOfBooks(html));}}

Index.html

<html> <head>
<title>New book</title>
</head>
<body>
<formmethod="post"action="MyFirstServlet">
Name: <inputtype="text"name="book">
Author: <inputtype="text"name="author">
Date: <inputtype="text"name="date">
Genre: <inputtype="text"name="genre">
Rating: <inputtype="text"name="rating">
<buttonid="addBtn">Add</button>
</form>
<formaction="/MyFirstServlet">
<buttonid="showBtn">Show all books</button>
</form>
</body>
</html>

Задание №2


Понравилась статья? Добавь ее в закладку (CTRL+D) и не забудь поделиться с друзьями:  



double arrow
Сейчас читают про: