I am working with AngularJs with spring mvc module. I am uploading files from UI and displaying the file in UI in table format. When i upload for the first time its working fine but when I upload for the second time my code is not working. If i refresh the page and upload the file that its working fine. Please help me where I went wrong. I need to upload files multiple times without page refresh.
JSP COde:
<%# 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>
<title>Angular JS Custom Directives</title>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "StudentController">
<table width="100%" border="0" cellspacing="5" cellpadding="0" id="uploadFile">
<tr>
<td align="left" valign="middle">Upload File:</td><br/>
<td align="left" valign="middle">
<input name="file2" id="file2" type="file" file-model="file2"/><br/>
</td>
<td><input type="button" value="Submit" ng-click="uploadFormData();"></td>
</tr>
<tr>
<td align="left" valign="middle">
</td>
</tr>
</table>
<table border="1" cellspacing="0" cellpadding="4">
<tr ng-repeat="row in rows">
<td ng-repeat="column in row.split(',')">{{column}}</td>
</tr>
</table>
<mydirc></mydirc>
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('StudentController', function($scope,$http)
{
$scope.uploadFormData= function()
{
var oMyForm = new FormData();
oMyForm.append("file",file2.files[0]);
$http({
method: 'POST',
url: 'uploadFile',
headers: {'Content-Type': undefined},
data: oMyForm,
transformRequest: function(response, headersGetterFunction) {
return response;
}
}).success(function(data, headers)
{
$scope.rows=data.list;
});
}; //end of click
});
</script>
</body>
</html>
Controller :
#RequestMapping(value = "/uploadFile")
public #ResponseBody void upLoadFile(HttpServletRequest request,HttpServletResponse response,
#RequestParam(value = "file") MultipartFile file) {
JSONObject object = new JSONObject();
StringBuilder result=null;
try
{
System.out.println(file.getOriginalFilename());
InputStream in=file.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
List<String> ite=new ArrayList<String>();
object.put("list", ite);
response.getWriter().write(object.toString());
} catch (IOException e) {e.printStackTrace();
} catch (JSONException e) {e.printStackTrace();
}
}
Based on your code, please find the pseudo code for a directive with isolated scope and a separate controller handling the file upload.
Code for HTML:
<div ng-app = "mainApp" ng-controller = "StudentController">
<table width="100%" border="0" cellspacing="5" cellpadding="0" id="uploadFile">
<tr>
<td align="left" valign="middle">Upload File:</td><br/>
<td align="left" valign="middle">
<input name="file2" id="file2" type="file" file-model="file2"/><br/>
</td>
<td><input type="button" value="Submit" ng-click="uploadFormData();"></td>
</tr>
<tr>
<td align="left" valign="middle">
</td>
</tr>
</table>
<list-files rows="fileList"></list-files>
</div>
Code for the directive:
angular.module("mainApp").directive('listFiles', function() {
var template = '<table border="1" cellspacing="0" cellpadding="4">';
template += '<tr ng-repeat="row in rows">';
template += '<td ng-repeat="column in row.split(',')">{{column}}</td>';
template += '</tr>';
return {
restrict: 'E',
replace: true,
template : template,
scope: {
rows: '='
}
};
});
Pseudo code for StudentController:
angular.module("mainApp").controller("StudentController", function($scope, $http){
$scope.fileList = [];
$scope.uploadFormData = function() {
// Code to upload file.
// Ex:
$http(...).success(function(response){
$scope.fileList = response.list;
});
};
});
Hope this helps to solve the issue.
Related
I'm currently developing an online banking application where you can buy stocks. It is being built with spring boot and the front-end is html/css.
I am using the YahooFinance API to get stock quotes but I need to refresh my page to get the live stock quotes, how can I automatically update the page every 30 seconds to get the new prices for each stock?
Also, is there a way I could implement this using Threads?
Banking Controller
#GetMapping("/banking/stocks")
public String stocks(Model model) {
model.addAttribute("stock", new StockDto());
try {
List<Stock> stocks = stockService.getDefaultStocks();
model.addAttribute("stocks", stocks);
} catch (IOException e) {
e.printStackTrace();
}
return "stocks.html";
}
StockServiceImpl:
#Service
public class StockServiceImpl implements StockService {
private String[] startingStocks = { "AAPL", "BABA", "MSFT", "AXP", "BA", "AMD", "TSLA", "MA", "SHOP", "GOOGL",
"KL" };
#Override
public Stock getStock(String stockName) throws IOException {
Stock stock = YahooFinance.get(stockName);
return stock;
}
#Override
public Map<String, Stock> getStock(String[] s) throws IOException {
Map<String, Stock> stocks = YahooFinance.get(s);
return stocks;
}
#Override
public List<Stock> getDefaultStocks() throws IOException {
Map<String, Stock> stocks = YahooFinance.get(startingStocks);
List<Stock> stockList = new ArrayList<Stock>();
for(String s : startingStocks) {
stockList.add(stocks.get(s));
}
return stockList;
}
}
HTML Page For Displaying Stocks:
<main class='main-content bgc-grey-100'>
<div id='mainContent'>
<div class="container-fluid">
<br>
<h4 class="c-grey-900 mT-10 mB-30">Stock Table</h4>
<form action="#" th:object="${stock}" th:action="#{/banking/stock-search}"
method="POST" class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search"
th:field="*{name}" placeholder="Search Stock"
aria-label="Search">
<button class="btn btn-outline-primary my-2 my-sm-0" type="submit">Search</button>
</form>
<br>
<div class="row">
<div class="col-md-12">
<div class="bgc-white bd bdrs-3 p-20 mB-20">
<table id="dataTable" class="table table-striped table-bordered"
cellspacing="0" width="100%">
<thead>
<tr>
<th>Ticker</th>
<th>Trade</th>
<th>Name</th>
<th>Price</th>
<th>(%) Change</th>
<th>Div Yield (%)</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Ticker</th>
<th>Trade</th>
<th>Name</th>
<th>Price</th>
<th>(%) Change</th>
<th>Div Yield (%)</th>
</tr>
</tfoot>
<tbody>
<tr th:each="stock : ${stocks}">
<td th:text="${stock.getSymbol()}"></td>
<td>
<form action="#" th:action="#{/banking/stocks/} + ${stock.symbol}" method="get">
<button class="btn btn-outline-success my-2 my-sm-0" th:id="'table_entry_childs_button_' + ${stock.symbol}" type="submit">
<i>Trade</i>
</button>
</form>
</td>
<td th:text="${stock.getName()}"></td>
<td th:text="${stock.getQuote().getPrice()}"></td>
<td th:class="${stock.getQuote().getChangeInPercent() > 0 ? 'text-success' : 'text-danger'}" th:text="${stock.getQuote().getChangeInPercent() + '%'} "></td>
<td th:if="${stock.getDividend().getAnnualYield() != null}" th:text="${stock.getDividend().getAnnualYield() + '%'}">0.00%</td>
<td th:if="${stock.getDividend().getAnnualYield() == null}" >0.00%</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</main>
You can exploit STOMP protocol and web sockets using spring boot.
For reference:
https://www.baeldung.com/spring-websockets-send-message-to-user
on back end side you can use
#Autowired
SimpMessagingTemplate messagetemplate;
public void somemethod(String strParam){
while (true){
// build string or json whatever you need to send
messagetemplate.convertAndSend("/blabla/blabla",strParam);
Thread.sleep(30*1000);
}
}
on front end side you have to use stomp.js
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.js">
<script type="text/javascript">
function load(){
var stompClient = Stomp.client("ws://localhost:8080/ws");
stompClient.connect({}, function (frame) {
stompClient.subscribe('/blabla/blabla', function (message) {
// do something here
});
});
}
lastly, part of html where you want to call on load
<html>
<body onload="load()">
</body>
</html>
You can create an #Scheduled method that can call this API request every 30 seconds to get data and update your Front-End.
#Scheduled(fixedRate = 30000)
public void updateStocksElement() {
//Call your /banking/stocks rest endpoint
}
https://spring.io/guides/gs/scheduling-tasks/
here I want to upload my file into my upload folder but in my scenario, it cannot store in that folder. The file name is printed in the console but the file does not store in the upload folder. In the Developer tool console, I get an error called Failed to load resource: the server responded with a status of 404 (Not Found).
DemoForm.java
package controller;
import java.io.*;
import java.util.* ;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* Servlet implementation class DemoForm
*/
#WebServlet("/DemoForm")
#MultipartConfig(
fileSizeThreshold = 1024 * 1024 * 10, //10MB
maxFileSize = 1024 * 1024 * 50, //50MB
maxRequestSize = 1024 * 1024 * 100 //100MB
)
public class DemoForm extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIR = "upload";
/**
* #see HttpServlet#HttpServlet()
*/
public DemoForm() {
super();
// 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
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("username", request.getParameter("username"));
request.setAttribute("password", request.getParameter("password"));
request.setAttribute("sex", request.getParameter("sex"));
request.setAttribute("favious", Arrays.toString(request.getParameterValues("favious")));
request.setAttribute("description", request.getParameter("description"));
request.setAttribute("experience", request.getParameter("experience"));
request.setAttribute("fileName", uploadFile(request));
request.getRequestDispatcher("form_result.jsp").forward(request, response);
}
private String uploadFile(HttpServletRequest request) {
String fileName = "";
try {
Part filePart = request.getPart("photo");
fileName = getfileName(filePart);
String applicationPath = request.getServletContext().getRealPath("");
String basePath = applicationPath + File.separator + UPLOAD_DIR
+ File.separator;
// creates the save directory if it does not exists
File fileSaveDir = new File(basePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
InputStream inputStream = null;
OutputStream outputStream = null;
try {
File outputFilePath = new File(basePath + fileName);
inputStream =filePart.getInputStream();
outputStream = new FileOutputStream(outputFilePath);
int read = 0;
final byte[] bytes = new byte[1024];
while((read = inputStream.read(bytes))!= -1) {
outputStream.write(bytes,0,read);
}
}catch(Exception ex) {
ex.printStackTrace();
fileName="";
}finally {
if(outputStream != null) {
outputStream.close();
}
if(inputStream != null) {
inputStream.close();
}
}
}catch(Exception ex){
fileName = "";
}
return fileName;
}
private String getfileName(Part part) {
final String partHeader = part.getHeader("content-disposition");
System.out.println("*****partHeader:" + partHeader);
for(String content : part.getHeader("content-disposition").split(";")) {
if(content.trim().startsWith("fileName")) {
return content.substring(content.indexOf('=')+ 1).trim()
.replace("\"", "");
}
}
return null;
}
}
Form.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Upload file</title>
</head>
<body>
<form method="post" action="DemoForm" enctype="multipart/form-data">
<table border="0" cellpadding="2" cellspacing="2" width="300">
<tr>
<td> username:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td> Password:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td valign="top"> Sex </td>
<td>
<input type="radio" name="sex" value="male" checked="checked"/>Male
<br>
<input type="radio" name="sex" value="female"/>Female
</td>
</tr>
<tr>
<td valign="top"> Favious </td>
<td>
<input type="checkbox" name="favious" value="fav1"/>Favios 1<br>
<input type="checkbox" name="favious" value="fav2"/>Favios 2<br>
<input type="checkbox" name="favious" value="fav1"/>Favios 3<br>
<input type="checkbox" name="favious" value="fav1"/>Favios 4<br>
<input type="checkbox" name="favious" value="fav1"/>Favios 5<br>
</td>
</tr>
<tr>
<td valign="top"> Description:</td>
<td><textarea rows="10" cols="20" name="description"></textarea></td>
</tr>
<tr>
<td>Experiences</td>
<td>
<select name="experience">
<option value="1"> 1 year </option>
<option value="2"> 2 year </option>
<option value="3"> 3 year </option>
<option value="4"> 4 year </option>
</select>
</td>
</tr>
<tr>
<td valign="top"> Photo</td>
<td><input type="file" name="photo "/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="save"/></td>
</tr>
</table>
</form>
</body>
</html>
Form_result.jsp
[<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>Account Information</h3>
<table border="0" cellpadding="2" cellspacing="2" width="300">
<tr>
<td>Username</td>
<td> ${username}</td>
</tr>
<tr>
<td>Password</td>
<td> ${password}</td>
</tr>
<tr>
<td valign="top">Sex</td>
<td> ${sex}</td>
</tr>
<tr>
<td valign="top">Favious</td>
<td> ${favious}</td>
</tr>
<tr>
<td valign="top">Description</td>
<td> ${description}</td>
</tr>
<tr>
<td>Experience</td>
<td> ${experience}</td>
</tr>
<tr>
<td valign="top">Photo</td>
<td><img src="upload/${fileName}"></td>
</tr>
</table>
</body>
</html>][1]
I think the error is not in your file uploading. Your request has not been received by your servelet. Just comment out all the codes and check whether your doPost is working or not? Check the URL you are hitting.
The endpoint on which you are trying to upload the file is invalid.
Errorcode 404 means that the endpoint can not be found.
I am trying to generate the document from html using docx4j 3.3.1. I am facing below issue can some one help me on these?
HTML Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" lang="en">
<head>
<title>MonthlyReport</title>
<style>
table
{
border:double #000;
table-layout: fixed;
vertical-align: top;
border-collapse: collapse;
width: 7.25in;
}
.main-title
{
margin-top:25%;
font-size:48pt;
font-family:Century Gothic;
color:#2F5897;
text-align:center;
font-weight:300;
}
.year
{
padding-top:10%;
text-align:center;
font-size:18px;
}
.other-detail
{
padding-top:10%;
padding-bottom:10%;
font-weight:bold;
text-align:center;
font-size:18px;
}
.cont
{
font-family:Palatino Linotype;
margin:0 auto;
margin-top:10px;
}
.cont-table
{
border:double #000;
table-layout: fixed;
vertical-align: top;
border-collapse: collapse;
width: 7.25in;
}
.cont h1
{
font-family:Century Gothic;
color:#2F5897;
font-weight:400;
margin-left:.15in;
}
.cont h4
{
font-family:Century Gothic;
font-weight:400;
margin-left:.15in;
}
.cont .school-detail
{
margin-left:.1in;
margin-right:.1in;
}
.cont ol
{
margin-left:1in;
margin-right:1in;
}
.cont li
{
margin-bottom:.25in;
}
.cont-heading
{
margin-left:.5in;
font-weight:bold;
text-decoration:underline;
margin-top:.35in;
}
span
{
display:block;
padding-bottom:10px;
}
.rheight
{
height: 3.6in;
}
img
{
width:100%;
}
.img-table
{
width:5in;
}
.img-table td
{
width:5in;
}
.cont-img
{
width:4in;
}
</style>
</head>
<body>
<table align="center" cellspacing="0" cellpadding="0">
<tr class="rheight">
<td> </td>
</tr>
<tr>
<td>
<div class="main-title"> Monthly report </div>
</td>
</tr>
<tr>
<td>
<div class="year"> 2016-2017 </div>
</td>
</tr>
<tr>
<td>
<div class="other-detail">MONTH: January<br />
CITY: TEST_CITY<br /> FACILITATOR:
TEST_PERSON<br />
</div>
</td>
</tr>
<tr class="rheight">
<td> </td>
</tr>
</table>
<table class="cont-table" align="center" cellspacing="0" cellpadding="0">
<tr>
<td>
<div class="cont">
<h1>Monthly Report</h1>
<h4>2016-2017</h4>
<br />
<p class="school-detail">
<p class="cont-heading">TEST SCHOOL</p>
<ol>
<li>
<strong>Test Question</strong>
<br />TEST_ANSWER</li>
</ol>
<p>Photos</p>
<table class="img-table" cellspacing="0" cellpadding="0">
<tr>
<td>
<img class="cont-img" src="C:\CodeBase\SampleProjects\fmstest\fms\TESTIMAGE.jpg" alt="TESTIMAGE.jpg" />
</td>
</tr>
</table>
</p>
</div>
</td>
</tr>
</table>
</body>
</html>
Issue 1:
On Converting html without any image to document i am getting proper document style but if i use image in html styles are completely changed.
Code is given below
`private static void documentGenerator(String html, File file) throws Docx4JException, JAXBException {
//Word Processing Package
WordprocessingMLPackage wordMLPackage = getWordMLPackage();
NumberingDefinitionsPart ndp = new NumberingDefinitionsPart();
wordMLPackage.getMainDocumentPart().addTargetPart(ndp);
ndp.unmarshalDefaultNumbering();
//Saving the Document
wordMLPackage.getMainDocumentPart().addAltChunk(AltChunkType.Xhtml, html.getBytes());
wordMLPackage.save(file);
}`
Issue 2:
On Using XHTMLImporterImpl Doc is generated with same content twice and styles are not proper.
Code is given below
private static void documentGenerator(String html, File file) throws Docx4JException, JAXBException {
//Word Processing Package
WordprocessingMLPackage wordMLPackage = getWordMLPackage();
NumberingDefinitionsPart ndp = new NumberingDefinitionsPart();
wordMLPackage.getMainDocumentPart().addTargetPart(ndp);
ndp.unmarshalDefaultNumbering();
// Convert the XHTML, and add it into the empty docx we made
XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(wordMLPackage);
XHTMLImporter.setHyperlinkStyle("Hyperlink");
String baseurl = file.getPath();
baseurl = baseurl.substring(0, baseurl.lastIndexOf("\\"));
wordMLPackage.getMainDocumentPart().getContent().addAll(XHTMLImporter.convert(html, baseurl));
//Saving the Document
wordMLPackage.getMainDocumentPart().addAltChunk(AltChunkType.Xhtml, html.getBytes());
wordMLPackage.save(file);
}
Issue 3:
Generated document cannot be viewed in any application except MS Word.
Regarding issue 1: addAltChunk just adds an altChunk (aka AlternativeFormatInput part), and since you just save the docx, you are relying on Word to convert the content, so your behaviour is Word specific.
Regarding issue 2: you're are getting duplicate content, since you do both XHTMLImporter.convert and addAltChunk.
I am developing an application with AngularJS and Spring MVC. Everything is working fine but my object is going as null to the Spring Controller so it's returning null. I just don`t know how to make the AngularJS populates the object.
I will post the code here.
AngularJS
<%#taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core'%>
<%#taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!doctype html>
<html>
<head>
<title>Settings</title>
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/workflow.css">
<link rel="stylesheet" href="css/upload.css">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<link rel="shortcut icon" href="images/logo-small.png" />
</head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('formSubmit', []);
app.controller('FormSubmitController', function($scope, $http) {
$scope.formData = {};
$scope.headerText = 'AngularJS Post Form Spring MVC example: Submit below form';
$scope.submit = function() {
var formData = {
"name1" : "nome 1",
"name2" : "nome 2",
"name3" : "nome 3",
};
var response = $http.post('http://localhost:8080/fire-fatca-web/SubmitMock.html', formData); //passing mockForm
response.success(function(data, status, headers, config) {
/* alert('Success!' + JSON.stringify({
data: $scope.formData //used formData model here
}) ); */
$scope.mockForm = data;
$scope.formData.push(data);
});
response.error(function(data, status, headers, config) {
alert("Exception details: " + JSON.stringify({
data: $scope.formData //used formData model here
}));
})
};
});
</script>
<style>
input.ng-invalid {
border: 2px red solid;
}
</style>
<body data-ng-app="formSubmit">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<form data-ng-submit="submit()" name="myForm" data-ng-controller="FormSubmitController">
<!-- novalidate prevents HTML5 validation since we will be validating ourselves -->
<table border="1">
<tr>
<td colspan="2">
<label>Name Line 1:</label>
</td>
</tr>
<tr>
<td colspan="2">
<div class="form-group">
<input type="text" name="name1" class="form-control" data-ng-model="formData.name1" required ng-Maxlength="40">
<p ng-show="myForm.name1.$error.required" class="help-block">Name is required.</p>
<p ng-show="myForm.name1.$error.maxlength" class="help-block">Maximum 40 characters</p>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<label>Name Line 2:</label>
</td>
</tr>
<tr>
<td colspan="2">
<div class="form-group">
<input type="text" name="name2" class="form-control" data-ng-model="formData.name2" ng-Maxlength="40">
<p ng-show="myForm.name2.$error.maxlength" class="help-block">Maximum 40 characters</p>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<label>Name Line 3:</label>
</td>
</tr>
<tr>
<td colspan="2">
<div class="form-group">
<input type="text" name="name3" class="form-control" data-ng-model="formData.name3" ng-Maxlength="40">
<p ng-show="myForm.name3.$error.maxlength" class="help-block">Maximum 40 characters</p>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<h4>You submitted below data through post:</h4>
<pre>Form data ={{formData}}</pre>
</td>
</tr>
<tr>
<td colspan="2">
<p>Response: {{mockForm}}</p>
</td>
</tr>
<tr>
<td colspan="2">
<!-- SUBMIT BUTTON -->
<button type="submit" class="btn btn-primary" ng-disabled="myForm.$invalid">Submit</button>
</td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
Spring Controller
#Controller
public class MockController {
private Logger log = LoggerFactory.getLogger(MockController.class);
#RequestMapping("/mock")
public String getSettingsPage(){
return "mock";
}
#RequestMapping(value = "/SubmitMock", method = RequestMethod.POST)
public #ResponseBody String getMock(#RequestBody MockForm mockForm){
StringBuilder reponseData = new StringBuilder();
reponseData.append("Name1: "+ mockForm.getName1()+" ");
reponseData.append("Name2: "+ mockForm.getName2()+" ");
reponseData.append("Name3: "+ mockForm.getName3());
log.debug(reponseData.toString());
return reponseData.toString();
}
The return is aways: Name1: null, Name2: null and Name3: null
I know that I need to populate my mockForm with my formData. It was suggested me to do this:
var response = $http.post('http://localhost:8080/fire-fatca-web/SubmitMock.html', {mockform: formData});
But when I use that piece of code above my Controller Stops responding, I don't know why, maybe Sintaxe Error, I have no idea. Any help?
EDIT:
MockForm.java
package com.opessoftware.beans;
public class MockForm {
private String name1;
private String name2;
private String name3;
public String getName1() {
return name1;
}
public void setName1(String name1) {
this.name1 = name1;
}
public String getName2() {
return name2;
}
public void setName2(String name2) {
this.name2 = name2;
}
public String getName3() {
return name3;
}
public void setName3(String name3) {
this.name3 = name3;
}
}
EDIT 2:
Finally I solve the problem. my ng-data-model was formData.name1, formData.name2 and formData.name3. I changed for name1, name2 and name3. Problem solved. Thank you all!
I have a success.jsp page which displays multiple rows and columns with an Edit button and a checkbox for each row. If the user clicks on Edit button, the checkbox is selected.
Below is success.jsp :
<%#page import="mymvc.model.TableColumns"%>
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.Iterator"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%--
Document : success
Created on : Jul 8, 2014, 1:43:17 PM
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Success</title>
<script type="text/javascript">
function validate(n) {
v = document.getElementById("check"+n)
v.checked = !v.checked;
x = document.getElementById("typeId"+n).removeAttribute('readonly');
y = document.getElementById("paramSeq"+n).removeAttribute('readonly');
z = document.getElementById("paramName"+n).removeAttribute('readonly');
}
</script>
</head>
<body>
<form action="DBController" method="post">
Welcome ${requestScope['user'].username}.
<table>
<tr style="background-color:#f0a64e;">
<th class="border">ID</th>
<th class="border">Param Sequence</th>
<th class="border">Param Name</th>
</tr>
<c:forEach var="element" items="${requestScope['listData']}" varStatus="status">
<tr>
<td><input id="typeId${status.index}" value="${element.typeId}" readonly="true"</td>
<td><input id="paramSeq${status.index}" value="${element.paramSeq}" readonly="true"</td>
<td><input id="paramName${status.index}" value="${element.paramName}" readonly="true"</td>
<td>
<input id="edit${status.index}" type="button" value="Edit" name="edit" onclick="validate(${status.index})"</input>
</td>
<td><input type="checkbox" id="check${status.index}" name="selectedItems" value="<c:out value="${status.index}"/>"</td>
</tr>
</c:forEach>
</table>
<input type="submit" value="Update" name="update" />
</form>
</body>
</html>
I don't know how to send the whole row data to my servlet if more than one row is selected. I am able to get all the indexes of the checkboxes which are selected. But I am unable to extract other related values like typeId, paramSeq and paramName. My servlet is as follows :
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String[] edited = request.getParameterValues("selectedItems");
//String pName = request.getParameter("paramName"+edited[1]);
Enumeration<String> paramName = request.getParameterNames();
String[] param = new String[10];
int i=0;
while(paramName.hasMoreElements()){
param[i]=paramName.nextElement();
}
RequestDispatcher rd = null;
rd = request.getRequestDispatcher("/update.jsp");
request.setAttribute("param", param);
request.setAttribute("edited", edited);
rd.forward(request, response);
}
In the above code, currently, I am trying to get all the parameters passed and the rows which are selected. I want to modify this servlet and access the selected row along with other data like typeId, etc. to create UPDATE statements for every row. I referred this and this but not much help.
I think what you are missing is that you are giving each input type a unique id but you are not specifying the name of the input types, and in the servlet you are trying to get values by name.
So please add names along with the id's in order to get them in the servlet
<c:forEach var="element" items="${requestScope['listData']}" varStatus="status">
<tr>
<td><input name="typeId${status.index}" value="${element.typeId}" readonly="true"</td>
<td><input name="paramSeq${status.index}" value="${element.paramSeq}" readonly="true"</td>
<td><input name="paramName${status.index}" value="${element.paramName}" readonly="true"</td>
<td>
<input id="edit${status.index}" type="button" value="Edit" name="edit" onclick="validate(${status.index})"</input>
</td>
<td><input type="checkbox" id="check${status.index}" name="selectedItems" value="<c:out value="${status.index}"/>"</td>
</tr>
</c:forEach>
</table>