Can I invoke Servlet without mapping it in web.xml? [duplicate] - servlets

This question already has answers here:
How to invoke a servlet without mapping in web.xml?
(3 answers)
Closed 2 years ago.
If I have action to a servlet, we should use mapping in XML which is recommended. So it would look like this:
HTML index:
<!DOCTYPE html>
</head><body>
<form action="go" method="POST">
Enter name: <input type="text" name="name">
<button>Submit form :)</button>
</form>
</body></html>
XML mapping:
<web-app..........
<servlet>
<servlet-name>servlet</servlet-name>
<servlet-class>ServletOne</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet</servlet-name>
<url-pattern>/go</url-pattern>
</servlet-mapping>
</web-app>
Servlet class
public class ServletOne extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String s = req.getParameter("name");
PrintWriter pw = resp.getWriter();
pw.println("Welcome " + s);
}
}
And it works fine. But my question is what if I don't want to make a mapping - I want to call Servlet class directly. I removed my XML file and I did all of these lines:
<form action="ServletOne" method="POST">
<form action="ServletOne.class" method="POST">
<form action="ServletOne.java" method="POST">
And.. none of them work. Can I actually call Servlet directly without mapping at all? If yes, how? Sometimes for testing purposes, I don't need to waste time on mapping every servlet.

You can use annotation e.g.
#WebServlet("/go")
public class ServletOne extends HttpServlet {
//...
}
In fact, Servlet 3.0 onwards, most of the developers prefer this to XML configuration.
Note that the Servlet Specification requires the mapping to start with a /. Check this to learn more about it.

Related

No mapping found for HTTP request with URI - No dispatcherservlet / servletmapping error

I know this is a common question but I'm getting desesperated here, Im pretty newbie and have been stuck with this for a long time now... I know this is not a DispatcherServlet or Servlet Mapping error as I'm working on a really big project that has everything working already.
What I need to do is add a form on an already existing jsp page, here is what I have
CONTROLLER:
#Controller
#RequestMapping("/messaging")
public class MessagingController {
#GetMapping
public String messagingView(Principal principal, Model model) throws ServiceException {
model.addAttribute("messagingInformation", new MessagingInformation());
return foo; -> this returns me to the main jsp where I'm creating the form
}
#PostMapping(value = "/submitInformation") -> I've also tried with #RequestMapping(value = "/submitInformation", method = RequestMethod.POST)
public String submitInformation(#ModelAttribute(value = "messagingInformation") #Valid MessagingInformation messagingInformation) {
return "redirect:/messaging"; -> shouldn't this redirect me to the main jsp?
}
}
JSP:
<form:form action="messaging/submitInformation" modelAttribute="messagingInformation" method="POST">
<div class="row col-sm-12 margin-top-container">
<div class="col-sm-4">
<span class="titles-select-box uppercase-text">RECEIVER</span>
<input name="receiver" type="email" id="receiverId" name="receiverName"
placeholder="Receiver" multiple>
</div>
</div>
<div class="col-sm-12 no-padding-left">
<div class="button-container pull-right">
<input type="submit" value="Send" class="btn btn-default"
id="sendButton" />
</div>
</div>
</form:form>
I'm mainly getting --No mapping found for HTTP request with URI [/foo/messaging/submitInformation] in DispatcherServlet -- I've asked around and I shouldn't add nothing to any cofiguration file or anything, clearly it's something wrong on my side but I can't see it
Leaving this in case anyone finds out... I was requiered to do a manual build so the java changes would show up. This is done through Projects -> Build All

Spring Form binding to List<Integer> not working when upgraded to Java 8

We are upgrading our Spring MVC system to Java 8 compiled from Java 6 compiled. During runtime, we are loading a form object into List which when iterated throws java.lang.ClassCastException: java.lang.String
cannot be cast to java.lang.Integer
The same code was working fine in our production environment which is compiled with Java 6.
Below is the excerpt from our code base.
JSP
<div class="row">
<span class="lbl"> <b>Menus</b>: </span>
<span class="formw">
<form:select path="selectedMenuIdList" multiple="true" id="selectedMenuIdList" size="5">
<c:forEach items="${menus}" var="topLevelMenu">
<form:option value="${topLevelMenu.menuId}">-<c:out value="${topLevelMenu.menuTitle}"/></form:option>
<c:forEach items="${topLevelMenu.childList}" var="subMenu"><form:option value="${subMenu.menuId}">---<c:out value="${subMenu.menuTitle}"/></form:option></c:forEach>
</c:forEach>
</form:select>
</span>
</div>
Controller
I have not added the complete method. But this is what it is exactly doing.
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, ManageUserCommand command, BindException errors) throws Exception
{
List<Integer> selectedMenuIdList = command.getSelectedMenuIdList();
for (Integer menu : selectedMenuIdList){//exception thrown here
userMenu.setMenuId(menuId);
userMenuDao.save(userMenu);
}
}
when I re-write the code as below it works.
Iterator<Integer> i = selectedMenuIdList.iterator();
while(i.hasNext()){
String temp = String.valueOf(i.next());
Integer menuId = Integer.parseInt(temp);
userMenu.setMenuId(menuId);
userMenuDao.save(userMenu);
}
Please clarify what is going wrong with using java 8 since we cannot re-write all the code as above to make it work with java 8.

image uploading using spring mvc to jboss server deployment tmp folder

hi my project is based on maven multi module project.
project structure is given below.
im using jboss 7 as my server.
Response
ResponseCommons
ResponseEar
ResponseModel
ResponseService
ResponseWeb
and im done a image upload form. uploading working fine and the image is uploaded to the resource folder of web module.
The problem is the image is uploading to tmp folder of the jboss server ,how can i changes to ResponseWeb/webapp/resources/css/ image name.
current image saving location
C:\jboss-as-7.1.1.Final\stand
alone\tmp\vfs\deploymenteec45ba06bd34543\ResponseWeb-1.2-SNAPSHOT.war-295
28a7e2cc4df5e\resources\css
im using ajax form submit to upload image.
controller for uploading image
#RequestMapping(value = "/uploadImage.html", method = RequestMethod.POST)
#ResponseBody
public String uploadImageTest(#RequestParam("demoImage") MultipartFile file) throws IllegalStateException, IOException {
try {
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (file.getSize() > 0) {
inputStream = file.getInputStream();
System.out.println("File Size:::" + file.getSize());
System.out.println("size::" + file.getSize());
fileName = request.getServletContext().getRealPath("/resources/") + "/css/"
+ file.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
System.out.println("fileName:" + file.getOriginalFilename());
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return "saved";
}
HTML
<form th:action="#{/school-admin/uploadImage.html}"
id="imageUploadForm" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-lg-2" style="margin-bottom: -40px;">
<div class="thumbnail">
<img id="imgStud" th:src="#{/resources/img/profile.png}"
style="width: 172px; height: 198px;" /> <br /> <input
type="file" accept="image/*" name="demoImage" id="demoImage"
onchange="fileSelected();" style="width: 170px;" />
</div>
<br />
</div>
</div>
<input type="button" class="btn btn-info pull-right"
id="btnUpload" value="upload" />
</form>
The location you want to save the file is invalid, as it is in fact, inside your WAR file, which gets exploded into the JBoss temp directory, hence you see the .../tmp/vfs/deployment.... folder.
However, you can specify a particular location for your default multi-part upload location, in multiple ways.
If you are using Servlet 3.0, you configure multipart servlet, either as annotation or in web.xml. You can annotate a pure servlet, in the following way.
#WebServlet("/myImageFileUploader")
#MultipartConfig(location = "/opt/myImageFileUploadLocation")
public class MyImageFileUploaderServlet extends HttpServlet {
.....}
XML configuration is as below
<servlet>
<servlet-name>MySpringDispatcher1</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/spring-servlet.xml</param-value>
</init-param>
<multipart-config>
<location>/opt/myImageFileUploadLocation</location>
<max-file-size>52428800</max-file-size>
<max-request-size>52428800</max-request-size>
<file-size-threshold>0</file-size-threshold>
</multipart-config>
</servlet>
The above XML example can be used directly in your project, if you are using Servlet 3.0. The sample code is configuring the Spring DispatcherServlet, for your convenience. JBoss 7 Web has Servlet 3.0, by default, so I guess it will work.
If your Servlet version is pre 3.0, I mean, older versions, then you can configure commons-fileupload in the spring configuration file, as given below.
<bean id="myImageMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000" />
<property name="uploadTempDir" ref="myImageFileUploadDirResource" />
</bean>
<bean id="myImageFileUploadDirResource" class="org.springframework.core.io.FileSystemResource">
<constructor-arg>
<value>/opt/myImageFileUploadLocation</value>
</constructor-arg>
</bean>
Hope this helps.

SPRING MVC post method call not working

By JSP has below :
<h2>Student Information</h2>
<form:form method="POST" action="/HelloWeb/addStudent">
<table>
and my java controller code has below
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb") Student student,
ModelMap model) {
when i try to hit the post doesnt work i,e /HelloWeb/addStudent,
I tried making both places /HelloWeb/addStudent or just /addStudent that doesnt work.
FYI : HelloWeb here is the DispatchServletName given in web,xml
I am trying example given in site
http://www.tutorialspoint.com/spring/spring_mvc_form_handling_example.htm
I apologize if i am asking very basic easisest issue, BUt tried this # late nite and fed up so requesting ppl to help/suggest
The attribute in jsp require modelAddribute or commandName which is the class instance of the domain object. You did not specify it. So the
<form:form method="POST" modelAttribute="SpringWeb" action="/HelloWeb/addStudent">.
There is a standard way to do form post submission in spring. You need to do GET request mapping to map/bind the Student table with jsp, and POST mapping to submit jsp form data. An example in your case would be.
#RequestMapping(value = "/addStudent", method = RequestMethod.GET)
public String addStudent(#ModelAttribute("SpringWeb") Student student) {
return "addstudentJsp"; // your jsp page name where the spring:form is placed
In jsp page do this
<h2>Student Information</h2>
<form:form modelAttribute="SpringWeb">
<form:input id="name" path="name" type="text" class="form-control" />
<form:errors path="name" cssClass="text-danger"></form:errors>
// your student fields
<button type="submit">submit</button>
</form:form>
Now again in your controller have a post request method like
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb") Student student, #BindingResult result) {
//Call to your data persistence layer like StudentService
}
The modelAttribute does the binding for you
I faced same problem, I just rename my project "HelloWeb" and the problem was solved.

Spring 3 MVC error: Neither BindingResult nor plain target object for bean name 'user' available

I know this issue might have been addressed elsewhere but I'm unable to find a satisfactory solution to my problem. Btw, I'm working with spring 3.0.2
Login.jsp
<form:form id="_LoginForm" name="LoginForm" modelAttribute="user" action="login" method="POST">
<form:input path="username" value=""/>
<form:input path="password" value=""/>
<input type="submit" value="Submit"/>
LoginController.java
#RequestMapping(value="login", method=RequestMethod.POST)
public String login(#ModelAttribute("user") User user, BindingResult result) {
System.out.println("recd request");
return null;
}
When I try to access the login.jsp page, I get the following error:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute
at org.springframework.web.servlet.support.BindStatus.(BindStatus.java:141)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:160)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:123)
at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:409)
at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:140)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
Can you please provide your RequestMethod.GET method in the controller?
Just want to make sure you are adding the modelAttribute in the GET method as well.
I added the the following method to make this work, though I feel there must be a better way to get this working without having to write a setup method everytime.
applicationContext.xml
<mvc:view-controller path="/" view-name="index" />
index.jsp
<jsp:forward page="index.action"/>
LoginController.java
#RequestMapping(value="index.action", method=RequestMethod.GET)
public String setupLogin(Map<String, Object> modelMap) {
modelMap.put("user", new User());
return "Login";
}

Resources