Understanding the MVC framework with server-side Java 3/4 Controller


** ↑ Image of this framework **


This time is the mountain. I don't think it comes to my mind very much, but at first it is. Let's do our best.

things to do

Let's create a website using the framework of the subject Breakdown of all 4 times


--Eclipse installed --DB2 installed (required for 4th time)


jsp fix


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%><!--Character code specification-->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<form action="/MVC/Controller" method="post">   <!--Declaration to send ↓ information in post [Addition] Set the action value to Controller-->
    <input type="text" name="keyword">   <!--Search keyword input field-->
    <input type="hidden" name="beanid" value="practice.Product"><!--[Add] Declare the bean to be used-->
    <input type="hidden" name="pageto" value="Result.jsp"><!--[Addition] Specifying the transition destination-->
    <input type="submit" value="Search"> <!--Keyword send button-->


Model creation (partially reprinted)


package practice;

public class Product extends SuperBean{
        //Keep member variables private
    private int price;
    private int weight;
    private String name;
    private String material1;
    private String category;

    public void runBean(){//[Change] The method name has been changed from setAll.
    	String keyword = (String) super.request.getParameter("keyword");//[Change] Output the received value and check
    	System.out.println("The search keyword is"+keyword+"was. I will search the DB using this next time");

    	//Since we will not make a DB connection this time, we will set the value directly to each attribute of the bean.
        this.name=""My disappearance" Fuminori Nakamura";


    public int getPrice() {
        return price;
    public int getWeight() {
        return weight;
    public String getName() {
        return name;
    public String getMaterial1() {
        return material1;
    public String getCategory() {
        return category;

Creating a SuperBean

Created to organize common bean processing into parent class


package practice;

import javax.servlet.http.HttpServletRequest;

public abstract class SuperBean {
	protected HttpServletRequest request;//Hold request
	void setJspInfo(HttpServletRequest request){
		this.request = request;
	protected void runBean(){//Run bean



Creating a Controller

Since then, Controller is designed so that editing is not required even when adding functions (jsp, beans). I think it's hard to write now, but it's useful when adding features. To create a Servlet, right-click the practice package → New → Servlet.


package practice;

import java.io.IOException;

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 javax.servlet.http.HttpSession;
 * Servlet implementation class Controller
public class Controller extends HttpServlet {
	private static final long serialVersionUID = 1L;

     * Default constructor.
    public Controller() {
        // TODO Auto-generated constructor stub

	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		//session(A container for returning an instance to the jsp side)Generate a.
		HttpSession session= request.getSession();

			//It takes the bean name as a variable and instantiates that bean. This allows you to use methods such as getters. The Product class is instantiated here.
			//Character code specification
			String beanid = (String)request.getParameter("beanid");
			String pageto = (String)request.getParameter("pageto");
			try {
				SuperBean bean = (SuperBean) Class.forName(beanid).newInstance();

			//Pass the information received from jsp to the bean

			//Run bean

			//Store beans in session
			session.setAttribute("bean", bean);

			RequestDispatcher rd =request.getRequestDispatcher(pageto);
			rd.forward(request, response);
			} catch (InstantiationException e) {
				//TODO auto-generated catch block
			} catch (IllegalAccessException e) {
				//TODO auto-generated catch block
			} catch (ClassNotFoundException e) {
				//TODO auto-generated catch block



Creating a result output page


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="practice.Product"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%request.setCharacterEncoding("UTF-8"); %>
<%Product bean = (Product)session.getAttribute("bean"); %>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

Product name:<%=bean.getName() %><br>
price:\&nbsp;<%=bean.getPrice() %><br>
weight:<%=bean.getWeight() %><br>
Product Category:<%=bean.getCategory() %><br>

This completes MVC excluding DB connection. The content of this time was much more difficult than before. Thank you for your hard work. I think I'll run into errors, so I'm waiting for your question.

Recommended Posts

Understanding the MVC framework with server-side Java 3/4 Controller
Understanding the MVC framework with server-side Java 1/4 View
Understanding the MVC framework with server-side Java 2/4 Model
Get started with serverless Java with the lightweight framework Micronaut!
Java Config with Spring MVC
[Java] [Play Framework] Until the project is started with Gradle
Consideration on the 2017 Java Persistence Framework (1)
I tried the Java framework "Quarkus"
Follow the link with Selenium (Java)
Test Spring framework controller with Junit
Guess about the 2017 Java Persistence Framework (3) Reladomo
java framework
Console input in Java (understanding the mechanism)
Try using the Wii remote with Java
[Java] Get the date with the LocalDateTime class
Be careful with requests and responses when using the Serverless Framework in Java
Test controller with Mock MVC in Spring Boot
[LeJOS] Let's control the EV3 motor with Java
What is the Java Servlet / JSP MVC model?
[Java] Set the time from the browser with jsoup
How to use Java framework with AWS Lambda! ??
Calculate the similarity score of strings with JAVA
Find the Fibonacci number with the Fork / Join Framework
Java starting with JShell-A peek into the Java world
Java framework comparison
[Java] Collection framework
Trace the SQL executed with the application Insights java agent
[wip] Server-side development comfortably and freely with the server
[Tutorial] Download Eclipse → Run the application with Java (Pleiades)
CI the architecture of Java / Kotlin applications with ArchUnit
Limit files created with the rails g controller command
How to deploy Java to AWS Lambda with Serverless Framework
Monitor the internal state of Java programs with Kubernetes
Check the behavior of Java Intrinsic Locks with bpftrace
[Java] Get the date 10 days later with the Calendar class
[Java] Get the file path in the folder with List
[Java] When writing the source ... A memorandum of understanding ①
HTTPS connection with Java to the self-signed certificate server
[LeJOS] Let's remotely control the EV3 motor with Java
Prepare the environment for java11 and javaFx with Ubuntu 18.4
[Rails] Put together the same code with controller actions
I investigated the super that I met with the devise controller
A survey of the Kubernetes native Java framework Quarkus
The story of making dto, dao-like with java, sqlite
Java desktop with the same front end as the WEB.
Replace only part of the URL host with java