How to convert this JSP to an MVC approach? [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I've written the below JSP. Now I want to make it into a MVC pattern, could you please help me how to do it?
<%#page import="java.util.Date"%>
<%#include file="DBCon.jsp" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script language="javascript">
function UnBloc1(test){
var temp3id= 'temp3' + test;
var temp4id= 'temp4' + test;
//alert(temp3id);
document.getElementById(temp3id).style.display='block';
document.getElementById(temp4id).style.display='block';
}
function invoke(but1)
{
//var x=document.getElementById("temp3"+but).value;
//alert(x);
document.abc.action="Up_Query_DB.jsp?val1="+but1;
document.abc.submit();
}
function invoke1(but)
{
document.abc.action="Users_2.jsp?val="+but;
document.abc.submit();
//var t=document.getElementById("ab")+z;
//alert(t);
}
</script>
</head>
<body>
<form name="abc" method="post" action=""><table>
<%
try
{
String s=(String)session.getAttribute("muusername");
int i=0;
int temp=0, temp1=0,temp2=0, temp3=0, temp4=0;
ps=con.prepareStatement("Select DBID,Query_Raised,TR from Scope2 where TR!='null' AND (Query_Answered is null OR Count1 is null) And Specialist='"+s+"'");
rs=ps.executeQuery();
out.println("<b>QueryRaised</b>");
while(rs.next())
{
i++;
%>
<tr>
<td><input type="text" value="<%=i%>" name="id1" id="id1"></td>
<td><center><input type="text" value="<%=rs.getString("DBID")%>" readonly id="abc<%=i%>" name="abc<%=i%>" size="100"></center></td>
<td><input type="Submit" value="Resume" name="temp1<%=i%>" id="temp1<%=i%>" onclick="invoke1(<%=i%>)"></td>
<td><input type="button" value="Update Answer" name="temp2<%=i%>" id="temp2<%=i%>" onClick="UnBloc1(<%=i%>)"></td>
<td><input type="text" name="temp3<%=i%>" id="temp3<%=i%>" style="display: none"/></td>
<td><input type="Submit" value="Submit Answer" name="temp4<%=i%>" id="temp4<%=i%>" style="display: none" onClick="invoke(<%=i%>)"/> </td>
</tr>
<% }
}
catch(Exception e)
{
out.println(e);
}
%>
</table>
</form>
</body>
</html>

Let's say you go to the database and get a list of objects that contain few attributes (with setter and getter methods), among them, the dbid attribute. The object would be your model. Let's call it myBean.
The Java class from you will do the query will be the Controller class. Let's call it myController. So, the controller should: 1. Get the list of objects you need. 2. Do anything that should be done before representing the information (in your case, I would say nothing) and 3. pass the information to the JSP through the list of your beans setting the information in the request so the information can be displayed.
Your JSP, now, should look like this:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script language="javascript">
...
</script>
</head>
<body>
<form name="abc" method="post" action="">
<table>
<c:forEach var="myItem" items="${listDbid}" varStatus="i">
<tr>
<td><input type="text" value="${i.count}" name="id1" id="id1"></td>
<td><center><input type="text" value="${myItem.getDbid}" readonly id="abc${i.count}" name="abc${i.count}" size="100"></center></td>
<td><input type="Submit" value="Resume" name="temp1${i.count}" id="temp1${i.count}" onclick="invoke1(${i.count})"></td>
<td><input type="button" value="Update Answer" name="temp2${i.count}" id="temp2${i.count}" onClick="UnBloc1(${i.count})"></td>
<td><input type="text" name="temp3${i.count}" id="temp3${i.count}" style="display: none"/></td>
<td><input type="Submit" value="Submit Answer" name="temp4${i.count}" id="temp4${i.count}" style="display: none" onClick="invoke(${i.count})"/> </td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
So, basically, you need to remove from your JSP all the code that is not "view", take it to a "controller" and use a "model" for sending the information from the "controller" to the "view".
Also
You should avoid scriptles (<% %>) in your JSP, better to use JSTL and others similar tools. If you do it, probably your JSP will not have "controller" code.
I recommend you to use a MVC framework, like Spring MVC or Struts, among others.
It is also nice if you create another layer in your code just for database access. This database layer will be used by the controllers so the controllers. You can reuse code, make controllers independent of database and keep them clearer.

I am new too MVC as well, but I can suggest you some tips. Make a bean. Beans are Java class with getter and setter. In your case the bean would be
public class Scope2
{
String dbID;
//all other attributes of the table.Beans should be reusable so usually there is only one bean for one corresponding table
public String getDBID()
{
return dbID;
}
public void setDBID(String dbId)
{
this.dbId=dbId;
}
//Other getters and setters for all other attributes
}
Now make a class that would perform database query. And return bean Scope2 from that class to jsp. And in your jsp you will simply print the values as out.println(bean.getDBID());

Related

Using a form to display model objects in Thymeleaf. Is there a better way to do this?

been trying to get comfortable with Spring Boot/Thymeleaf/frontend development in general. I'm currently using a table on the frontend to display a list of objects from the backend, as well as a form to allow users to view properties of each item in the list.
I feel like the way I'm doing this is really weird and feel that there could be a better way. Would appreciate any tips/feedback, thank you.
HTML/Thymeleaf
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Gambler Card List</title>
<link th:href="#{/css/styles.css}" rel="stylesheet" />
</head>
<body>
<h1>Gambler Card List</h1>
<div class="cardlist-wrapper">
<div class="cardlist-names">
<form action="/gambler/cardlist" method="get">
<table class="cardlist-table">
<tr th:each="card : ${cardList.getCardList()}">
<td>
<input th:class="card-btn"
th:attr="id=${{card.getId()} == {currentCard.getId()} ? 'selected' : ''}"
type="submit" th:value="${card.getName()}" name="cardName">
</td>
</tr>
</table>
</form>
</div>
<div class="cardlist-description">
<h4 th:text="${currentCard.getDescriptionTitle()}"></h4>
<p th:text="${currentCard.getDescription()}"></p>
</div>
</div>
</body>
</html>
Controller
#RequestMapping(value = "gambler/cardlist")
public String baseCardList(Model model,
#RequestParam(value="cardName", required=false) String cardName) {
model.addAttribute("currentCard", cardList.getCardByName(cardName));
model.addAttribute("cardList", cardList);
return "gambler/cardlist";
}
Output (need 10 rep to post image, so here's a link)
One potential improvement/simplification is to remove the form and replace the inputs with anchors. The anchors would look something like this (not tested!):
<a th:href="#{/gambler/cardlist(cardName=${card.name})}">
<button th:text="${card.name}"
th:classappend="${card.id == currentCard.id ? 'selectedButton' : 'deselectedButton'}">Card Name</button>
</a>
You can style selectedButton and deselectedButton as you wish.

Spring MVC having trouble getting JSP to display Controller Value

I am new to Spring MVC I have setup a test DB to try to get a single flow through and have a table displayed in a JSP page. I assume I have something configured wrong but I cannot find it. Maybe a naming convention.
I have a mySql DB
A DAO Class that just does a select * from my table that works as I can step into it.
My controller just gets a list of my Run Models. No errors are thrown The JSP simple loads an empty table. The controller seems to have the correct info in it.
Model (snippet all the getters and setters seem to work as the controller gets a list of them fine)
public class QAModel {
private int idRun;
private String SuiteID;
private String run_name;
Controller Code
#RequestMapping(value="/RunList")
public ModelAndView listRun(ModelAndView model) throws IOException{
//#ModelAttribute
System.out.println("**** Controller ******");
List<QAModel> listRun = runDao.list();
model.addObject("RunList", listRun);
model.setViewName("RunList");
return model;
}
That does get a list of Run Model Objects that contain the correct DB info I can see them if I step into it. However the JSP loads a blank table.
JSP Code (I assume I'm missing some mapping or naming convention?)
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Contact Manager Home</title>
</head>
<body>
<div align="center">
<h1>Contact List</h1>
<h3>New Run</h3>
<table border="1">
<th>No</th>
<th>Suite ID</th>
<th>Run Name</th>
<c:forEach var="QAModel" items="${RunList}" varStatus="status">
<tr>
<td>${status.index + 1}</td>
<td>${QAModel.SuiteID}</td>
<td>${QAModel.run_name}</td>
<td>
Edit
Delete
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
If you are not able to print any jstl variable then one possible reason can be that your jstl core tag is not added.
Add this to begining of your JSP file.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Radio Button Struts 1.3

I would like to create a radio button to select the values displayed on a jsp page.
how can I use radio buttons to select values from this JSP page ?
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%! int i=0; %>
<h1 align="center">DOCUMENT INFORMATION CENTER</h1>
<table border="12" align="center">
<tr><td>Employee ID</td><td>Document ID</td><td>Topic</td><td>Text</td><td>Files</td></tr>
<% int j=(Integer)session.getAttribute("i");
HttpSession session2=request.getSession();
for(i=0;i<j;i++)
{ out.println("<tr><td>"+session.getAttribute("eid"+i)+"</td><td>"+session2.getAttribute("id"+i)+"</td><td>"+session2.getAttribute("topic"+i)+"</td><td>"+session2.getAttribute("text"+i)+"</td><td>"+session2.getAttribute("files"+i)+"</td></tr>");
}
%>
</table>
</body>
</html>
You can use struts logic tags for this purpose. If the session logic present set the value of particular radio button as true. For iterating purpose also you can use logic:iterate tag. Following piece of code may help you.
<logic:present name="i" scope="session">
<logic:equal value="1" name="i" scope="session">
<script>
$('input[name=some_name][value=1]').prop("checked",true);
</script>
</logic:equal>
</logic:present>
Let me know if this helps..

Including JSP file within another JSP file

I'm writing a wizard for creating a user in my application with Spring MVC. At each step the controller will set session attributes for the completed wizard fields.
I want the wizard to look the same regardless of which page it's on, except for each page's fields, obviously. For example, menus and links at the top of the page and buttons at the bottom should remain the same.
I have the following JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Create a new User</title>
</head>
<body>
<h1>User Creation Wizard</h1>
Step <c:out value = "${pageNum}"/>/<c:out value = "${pageMax}"/>
<form action="" method="POST">
<jsp:include page="userform${pageView}.jsp"/>
<input name = "currentPage" type = "hidden" value = "${pageNum}"/>
<c:if test = "${pageNum > 1}">
<input name = "prev" type = "submit" value = "Previous" />
</c:if>
<c:if test = "${pageNum < pageMax}">
<input name = "next" type = "submit" value = "Next" />
</c:if>
<c:if test = "${pageNum == pageMax}">
<input name = "submit" type = "submit" value = "Finish" />
</c:if>
</form>
</body>
</html>
In the jsp I'm including, do I need to remove the <html>, <head>, and <body> tags? The above code is based on this example.
Yes, you'd need to remove the <html>, <head> and <body> tags from the included JSP file. As they'd already be present in the including file keeping them would result in invalid HTML.
Only the content that you want to vary would be in the JSP file you're including. Everything else, including the necessary <html>, <head> and <body> tags, would be in the JSP file that does the including.

text values to be entered in jsp for registration form

I am doing one small requirement on servlet and jsp.
servlet will contain variables id,name,email,gender. some times the values will be null.
Some times the values of the varaible are null. For example id and name are containing the values 1123 and pratap.
response.setContentType("text/html;charset=UTF-8");
try {
//TODO output your page here
RequestDispatcher view = request.getRequestDispatcher("registration.jsp");
view.forward(request, response);
request.setAttribute("id","value");
} finally {
}
my jsp page
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form method="GET" action='registration1'>
<input type="text" name="address"/>
<input type="text" name="phoneno"/>
<input type="text" name="pincode" />
<label>${id}</label>
<input type="submit"/>
</form>
</body>
</html>
so that the control is going to registration.jsp
In registration.jsp i should get the text boxes for email and gender and for the id and name i should get the values in the text boxes such that the user can not change those values.(because those are already filled and proved to be correct.)
for the above jsp i tried with id but i am unable to see the id value in jsp.
how to pass those varaibles to the text boxes of the jsp and making the prompt to enter the values if the value is null.
Thank you..
You need set values as request attributes in Servlet and get them in JSP.
After getting them in JSP, Check accordingly and enable /disable the form controls.
Servlet:
request.setAttribute("phoneno","9998386033");
JSP:
<%
String phoneno=null;
if(request.getAttribute("phoneno")!=null)
phoneno = request.getAttribute("phoneno").toString();
%>
<% if(phoneno!=null) {
out.println("<INPUT TYPE=\"text\" name=\"phoneno\" value=\""+phoneno+"\" disabled=\"disabled\" ");
} else {
out.println("<INPUT TYPE=\"text\" name=\"phoneno\" ");
}
%>
FOR JSP EL
<c:if test="${empty phoneno}">
<INPUT TYPE="text" name="phoneno" value="${phoneno}" disabled="disabled"/>
</c:if>
<c:if test="${not empty phoneno}">
<INPUT TYPE="text" name="phoneno"/>
</c:if>

Categories